terraproof 0.0.0-stage → 0.4.0

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +356 -2
  3. package/bin/terraproof.js +4 -0
  4. package/dist/router/apply.js +147 -0
  5. package/dist/router/classify.js +111 -0
  6. package/dist/router/explain.js +9 -0
  7. package/dist/router/index.js +272 -0
  8. package/dist/router/resolve.js +239 -0
  9. package/dist/router/score.js +60 -0
  10. package/dist/router/types.js +1 -0
  11. package/dist/router/validate.js +81 -0
  12. package/instructions/engineering.md +14 -0
  13. package/instructions/security.md +14 -0
  14. package/instructions/simplicity.md +13 -0
  15. package/package.json +65 -4
  16. package/routing/DOMAIN_ROUTING.md +161 -0
  17. package/routing/ROUTER_DESIGN.md +173 -0
  18. package/routing/SKILL_MANIFEST.md +86 -0
  19. package/routing/checks.json +121 -0
  20. package/routing/collections.json +47 -0
  21. package/routing/registry.json +2211 -0
  22. package/routing/rules.json +64 -0
  23. package/skills/accuracy-assessment/SKILL.md +213 -0
  24. package/skills/accuracy-assessment/UPSTREAM.md +7 -0
  25. package/skills/accuracy-assessment/references/stratified-estimator.md +127 -0
  26. package/skills/accuracy-assessment/skill.json +103 -0
  27. package/skills/brainstorming/SKILL.md +250 -0
  28. package/skills/brainstorming/UPSTREAM.md +29 -0
  29. package/skills/brainstorming/scripts/frame-template.html +213 -0
  30. package/skills/brainstorming/scripts/helper.js +167 -0
  31. package/skills/brainstorming/scripts/server.cjs +723 -0
  32. package/skills/brainstorming/scripts/start-server.sh +209 -0
  33. package/skills/brainstorming/scripts/stop-server.sh +120 -0
  34. package/skills/brainstorming/skill.json +73 -0
  35. package/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
  36. package/skills/brainstorming/visual-companion.md +299 -0
  37. package/skills/crs-and-units/SKILL.md +200 -0
  38. package/skills/crs-and-units/UPSTREAM.md +7 -0
  39. package/skills/crs-and-units/skill.json +74 -0
  40. package/skills/design-postgis-tables/SKILL.md +494 -0
  41. package/skills/design-postgis-tables/UPSTREAM.md +21 -0
  42. package/skills/design-postgis-tables/skill.json +90 -0
  43. package/skills/gdal/SKILL.md +125 -0
  44. package/skills/gdal/UPSTREAM.md +22 -0
  45. package/skills/gdal/references/gdal-recipes.md +103 -0
  46. package/skills/gdal/skill.json +66 -0
  47. package/skills/geomaster/README.md +105 -0
  48. package/skills/geomaster/SKILL.md +366 -0
  49. package/skills/geomaster/UPSTREAM.md +21 -0
  50. package/skills/geomaster/references/advanced-gis.md +376 -0
  51. package/skills/geomaster/references/big-data.md +363 -0
  52. package/skills/geomaster/references/code-examples.md +531 -0
  53. package/skills/geomaster/references/coordinate-systems.md +364 -0
  54. package/skills/geomaster/references/core-libraries.md +273 -0
  55. package/skills/geomaster/references/data-sources.md +330 -0
  56. package/skills/geomaster/references/gis-software.md +369 -0
  57. package/skills/geomaster/references/industry-applications.md +420 -0
  58. package/skills/geomaster/references/machine-learning.md +462 -0
  59. package/skills/geomaster/references/programming-languages.md +456 -0
  60. package/skills/geomaster/references/remote-sensing.md +370 -0
  61. package/skills/geomaster/references/scientific-domains.md +416 -0
  62. package/skills/geomaster/references/specialized-topics.md +428 -0
  63. package/skills/geomaster/references/troubleshooting.md +439 -0
  64. package/skills/geomaster/skill.json +157 -0
  65. package/skills/geopandas/SKILL.md +250 -0
  66. package/skills/geopandas/UPSTREAM.md +22 -0
  67. package/skills/geopandas/references/crs-management.md +231 -0
  68. package/skills/geopandas/references/data-io.md +323 -0
  69. package/skills/geopandas/references/data-structures.md +207 -0
  70. package/skills/geopandas/references/geometric-operations.md +262 -0
  71. package/skills/geopandas/references/spatial-analysis.md +294 -0
  72. package/skills/geopandas/references/visualization.md +230 -0
  73. package/skills/geopandas/scripts/_common.py +605 -0
  74. package/skills/geopandas/scripts/crs_reprojection_plan.py +210 -0
  75. package/skills/geopandas/scripts/export_plan.py +305 -0
  76. package/skills/geopandas/scripts/geometry_validity_report.py +227 -0
  77. package/skills/geopandas/scripts/sensitive_coordinates_checklist.py +230 -0
  78. package/skills/geopandas/scripts/spatial_join_audit.py +368 -0
  79. package/skills/geopandas/scripts/vector_inventory.py +140 -0
  80. package/skills/geopandas/skill.json +116 -0
  81. package/skills/geoparquet-validation/SKILL.md +125 -0
  82. package/skills/geoparquet-validation/UPSTREAM.md +24 -0
  83. package/skills/geoparquet-validation/references/distribution-best-practices.md +118 -0
  84. package/skills/geoparquet-validation/references/gpio-commands.md +264 -0
  85. package/skills/geoparquet-validation/references/tool-comparison.md +155 -0
  86. package/skills/geoparquet-validation/skill.json +71 -0
  87. package/skills/geospatial-data-discovery/SKILL.md +49 -0
  88. package/skills/geospatial-data-discovery/UPSTREAM.md +15 -0
  89. package/skills/geospatial-data-discovery/skill.json +51 -0
  90. package/skills/geospatial-frontend/SKILL.md +86 -0
  91. package/skills/geospatial-frontend/UPSTREAM.md +23 -0
  92. package/skills/geospatial-frontend/references/design-system.md +283 -0
  93. package/skills/geospatial-frontend/references/user-preferences.md +96 -0
  94. package/skills/geospatial-frontend/skill.json +87 -0
  95. package/skills/geozarr/SKILL.md +244 -0
  96. package/skills/geozarr/UPSTREAM.md +21 -0
  97. package/skills/geozarr/skill.json +97 -0
  98. package/skills/networkx/SKILL.md +440 -0
  99. package/skills/networkx/UPSTREAM.md +22 -0
  100. package/skills/networkx/references/algorithms.md +384 -0
  101. package/skills/networkx/references/generators.md +385 -0
  102. package/skills/networkx/references/graph-basics.md +284 -0
  103. package/skills/networkx/references/io.md +457 -0
  104. package/skills/networkx/references/visualization.md +531 -0
  105. package/skills/networkx/skill.json +93 -0
  106. package/skills/raster-processing/SKILL.md +222 -0
  107. package/skills/raster-processing/UPSTREAM.md +7 -0
  108. package/skills/raster-processing/skill.json +81 -0
  109. package/skills/sar-basics/SKILL.md +202 -0
  110. package/skills/sar-basics/UPSTREAM.md +7 -0
  111. package/skills/sar-basics/references/calibration-lut.md +98 -0
  112. package/skills/sar-basics/skill.json +97 -0
  113. package/skills/satellite-preprocessing/SKILL.md +241 -0
  114. package/skills/satellite-preprocessing/UPSTREAM.md +7 -0
  115. package/skills/satellite-preprocessing/skill.json +84 -0
  116. package/skills/scientific-visualization/SKILL.md +285 -0
  117. package/skills/scientific-visualization/UPSTREAM.md +25 -0
  118. package/skills/scientific-visualization/assets/color_palettes.py +263 -0
  119. package/skills/scientific-visualization/assets/nature.mplstyle +68 -0
  120. package/skills/scientific-visualization/assets/presentation.mplstyle +68 -0
  121. package/skills/scientific-visualization/assets/publication.mplstyle +77 -0
  122. package/skills/scientific-visualization/assets/publisher_profiles.json +269 -0
  123. package/skills/scientific-visualization/references/color_palettes.md +227 -0
  124. package/skills/scientific-visualization/references/journal_requirements.md +169 -0
  125. package/skills/scientific-visualization/references/matplotlib_examples.md +336 -0
  126. package/skills/scientific-visualization/references/publication_guidelines.md +196 -0
  127. package/skills/scientific-visualization/references/sources.md +76 -0
  128. package/skills/scientific-visualization/scripts/_common.py +136 -0
  129. package/skills/scientific-visualization/scripts/export_plan.py +493 -0
  130. package/skills/scientific-visualization/scripts/figure_export.py +642 -0
  131. package/skills/scientific-visualization/scripts/image_metadata.py +731 -0
  132. package/skills/scientific-visualization/scripts/palette_audit.py +327 -0
  133. package/skills/scientific-visualization/scripts/style_presets.py +501 -0
  134. package/skills/scientific-visualization/scripts/style_preview.py +232 -0
  135. package/skills/scientific-visualization/skill.json +95 -0
  136. package/skills/spectral-indices/SKILL.md +235 -0
  137. package/skills/spectral-indices/UPSTREAM.md +7 -0
  138. package/skills/spectral-indices/skill.json +88 -0
  139. package/skills/stac-and-cloud-access/SKILL.md +209 -0
  140. package/skills/stac-and-cloud-access/UPSTREAM.md +7 -0
  141. package/skills/stac-and-cloud-access/references/run-manifest.md +94 -0
  142. package/skills/stac-and-cloud-access/skill.json +98 -0
  143. package/skills/statistical-analysis/SKILL.md +446 -0
  144. package/skills/statistical-analysis/UPSTREAM.md +24 -0
  145. package/skills/statistical-analysis/references/assumptions_and_diagnostics.md +379 -0
  146. package/skills/statistical-analysis/references/bayesian_statistics.md +686 -0
  147. package/skills/statistical-analysis/references/effect_sizes_and_power.md +649 -0
  148. package/skills/statistical-analysis/references/reporting_standards.md +482 -0
  149. package/skills/statistical-analysis/references/test_selection_guide.md +129 -0
  150. package/skills/statistical-analysis/scripts/assumption_checks.py +652 -0
  151. package/skills/statistical-analysis/skill.json +127 -0
  152. package/skills/systematic-debugging/SKILL.md +283 -0
  153. package/skills/systematic-debugging/UPSTREAM.md +28 -0
  154. package/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  155. package/skills/systematic-debugging/condition-based-waiting.md +115 -0
  156. package/skills/systematic-debugging/defense-in-depth.md +122 -0
  157. package/skills/systematic-debugging/find-polluter.sh +72 -0
  158. package/skills/systematic-debugging/root-cause-tracing.md +169 -0
  159. package/skills/systematic-debugging/skill.json +88 -0
  160. package/skills/time-series-and-change/SKILL.md +217 -0
  161. package/skills/time-series-and-change/UPSTREAM.md +7 -0
  162. package/skills/time-series-and-change/references/change-methods.md +42 -0
  163. package/skills/time-series-and-change/skill.json +116 -0
  164. package/skills/vector-quality/SKILL.md +204 -0
  165. package/skills/vector-quality/UPSTREAM.md +7 -0
  166. package/skills/vector-quality/skill.json +82 -0
  167. package/skills/verification/SKILL.md +120 -0
  168. package/skills/verification/UPSTREAM.md +31 -0
  169. package/skills/verification/skill.json +67 -0
  170. package/skills/writing-plans/SKILL.md +171 -0
  171. package/skills/writing-plans/UPSTREAM.md +23 -0
  172. package/skills/writing-plans/plan-document-reviewer-prompt.md +49 -0
  173. package/skills/writing-plans/skill.json +80 -0
  174. package/sources/SOURCES.md +374 -0
  175. package/third_party/isaaccorley-geospatial-skills/LICENSE +176 -0
  176. package/third_party/isaaccorley-geospatial-skills/NOTICE.md +17 -0
  177. package/third_party/kdense-scientific-agent-skills/LICENSE +21 -0
  178. package/third_party/kdense-scientific-agent-skills/NOTICE.md +19 -0
  179. package/third_party/superpowers/LICENSE +21 -0
  180. package/third_party/superpowers/NOTICE.md +17 -0
  181. package/third_party/timescale-pg-aiguide/LICENSE +176 -0
  182. package/third_party/timescale-pg-aiguide/NOTICE.md +14 -0
@@ -0,0 +1,686 @@
1
+ # Bayesian Statistical Analysis
2
+
3
+ This document provides guidance on conducting and interpreting Bayesian statistical analyses, which offer an alternative framework to frequentist (classical) statistics.
4
+
5
+ ## Contents
6
+
7
+ - [Bayesian vs. Frequentist Philosophy](#bayesian-vs-frequentist-philosophy)
8
+ - [Bayes' Theorem](#bayes-theorem)
9
+ - [Prior Distributions](#prior-distributions)
10
+ - [Bayesian Hypothesis Testing](#bayesian-hypothesis-testing)
11
+ - [Bayesian Estimation](#bayesian-estimation)
12
+ - [Common Bayesian Analyses](#common-bayesian-analyses)
13
+ - [Hierarchical (Multilevel) Models](#hierarchical-multilevel-models)
14
+ - [Model Comparison](#model-comparison)
15
+ - [Checking Bayesian Models](#checking-bayesian-models)
16
+ - [Reporting Bayesian Results](#reporting-bayesian-results)
17
+ - [Advantages and Limitations](#advantages-and-limitations)
18
+ - [Key Python Packages](#key-python-packages)
19
+ - [When to Use Bayesian Methods](#when-to-use-bayesian-methods)
20
+
21
+ ## Bayesian vs. Frequentist Philosophy
22
+
23
+ ### Fundamental Differences
24
+
25
+ | Aspect | Frequentist | Bayesian |
26
+ |--------|-------------|----------|
27
+ | **Probability interpretation** | Long-run frequency of events | Degree of belief/uncertainty |
28
+ | **Parameters** | Fixed but unknown | Random variables with distributions |
29
+ | **Inference** | Based on sampling distributions | Based on posterior distributions |
30
+ | **Primary output** | p-values, confidence intervals | Posterior probabilities, credible intervals |
31
+ | **Prior information** | Not formally incorporated | Explicitly incorporated via priors |
32
+ | **Hypothesis testing** | Reject/fail to reject null | Probability of hypotheses given data |
33
+ | **Sample size** | Often requires minimum | Works at any n, but small-n posteriors are prior-dominated — report a prior-sensitivity check |
34
+ | **Interpretation** | Indirect (probability of data given H₀) | Direct (probability of hypothesis given data) |
35
+
36
+ ### Key Question Difference
37
+
38
+ **Frequentist**: "If the null hypothesis is true, what is the probability of observing data this extreme or more extreme?"
39
+
40
+ **Bayesian**: "Given the observed data, what is the probability that the hypothesis is true?"
41
+
42
+ The Bayesian question is more intuitive and directly addresses what researchers want to know.
43
+
44
+ ---
45
+
46
+ ## Bayes' Theorem
47
+
48
+ **Formula**:
49
+ ```
50
+ P(θ|D) = P(D|θ) × P(θ) / P(D)
51
+ ```
52
+
53
+ **In words**:
54
+ ```
55
+ Posterior = Likelihood × Prior / Evidence
56
+ ```
57
+
58
+ Where:
59
+ - **θ (theta)**: Parameter of interest (e.g., mean difference, correlation)
60
+ - **D**: Observed data
61
+ - **P(θ|D)**: Posterior distribution (belief about θ after seeing data)
62
+ - **P(D|θ)**: Likelihood (probability of data given θ)
63
+ - **P(θ)**: Prior distribution (belief about θ before seeing data)
64
+ - **P(D)**: Marginal likelihood/evidence (normalizing constant)
65
+
66
+ ---
67
+
68
+ ## Prior Distributions
69
+
70
+ ### Types of Priors
71
+
72
+ #### 1. Informative Priors
73
+
74
+ **When to use**: When you have substantial prior knowledge from:
75
+ - Previous studies
76
+ - Expert knowledge
77
+ - Theory
78
+ - Pilot data
79
+
80
+ **Example**: Meta-analysis shows effect size d ≈ 0.40, SD = 0.15
81
+ - Prior: Normal(0.40, 0.15)
82
+
83
+ **Advantages**:
84
+ - Incorporates existing knowledge
85
+ - More efficient (smaller samples needed)
86
+ - Can stabilize estimates with small data
87
+
88
+ **Disadvantages**:
89
+ - Subjective (but subjectivity can be strength)
90
+ - Must be justified and transparent
91
+ - May be controversial if strong prior conflicts with data
92
+
93
+ ---
94
+
95
+ #### 2. Weakly Informative Priors
96
+
97
+ **When to use**: Default choice for most applications
98
+
99
+ **Characteristics**:
100
+ - Regularizes estimates (prevents extreme values)
101
+ - Has minimal influence on posterior with moderate data
102
+ - Prevents computational issues
103
+
104
+ **Example priors**:
105
+ - Effect size: Normal(0, 1) or Cauchy(0, 0.707)
106
+ - Variance: Half-Cauchy(0, 1)
107
+ - Correlation: Uniform(-1, 1), a rescaled Beta on (-1, 1) (e.g. 2×Beta(2, 2)−1; plain Beta(2, 2) has support [0, 1]), or an LKJ prior for correlation matrices
108
+
109
+ **Advantages**:
110
+ - Balances objectivity and regularization
111
+ - Computationally stable
112
+ - Broadly acceptable
113
+
114
+ ---
115
+
116
+ #### 3. Non-Informative (Flat/Uniform) Priors
117
+
118
+ **When to use**: When attempting to be "objective"
119
+
120
+ **Example**: Uniform(-∞, ∞) for any value
121
+
122
+ **⚠️ Caution**:
123
+ - Can lead to improper posteriors
124
+ - May produce non-sensible results
125
+ - Not truly "non-informative" (still makes assumptions)
126
+ - Often not recommended in modern Bayesian practice
127
+
128
+ **Better alternative**: Use weakly informative priors
129
+
130
+ ---
131
+
132
+ ### Prior Sensitivity Analysis
133
+
134
+ **Always conduct**: Test how results change with different priors
135
+
136
+ **Process**:
137
+ 1. Fit model with default/planned prior
138
+ 2. Fit model with more diffuse prior
139
+ 3. Fit model with more concentrated prior
140
+ 4. Compare posterior distributions
141
+
142
+ **Reporting**:
143
+ - If results are similar: Evidence is robust
144
+ - If results differ substantially: Data are not strong enough to overwhelm prior
145
+
146
+ **Python example**:
147
+ ```python
148
+ import pymc as pm
149
+
150
+ prior_specs = [
151
+ ('weakly_informative', 0, 1),
152
+ ('diffuse', 0, 10),
153
+ ('informative', 0.5, 0.3),
154
+ ]
155
+
156
+ results = {}
157
+ for name, mu_prior, sigma_prior in prior_specs:
158
+ with pm.Model() as model:
159
+ effect = pm.Normal('effect', mu=mu_prior, sigma=sigma_prior)
160
+ # ... likelihood and observed data
161
+ trace = pm.sample(2000, tune=1000)
162
+ results[name] = trace
163
+ ```
164
+
165
+ ---
166
+
167
+ ## Bayesian Hypothesis Testing
168
+
169
+ ### Bayes Factor (BF)
170
+
171
+ **What it is**: Ratio of evidence for two competing hypotheses
172
+
173
+ **Formula**:
174
+ ```
175
+ BF₁₀ = P(D|H₁) / P(D|H₀)
176
+ ```
177
+
178
+ **Interpretation**:
179
+
180
+ | BF₁₀ | Evidence |
181
+ |------|----------|
182
+ | >100 | Decisive for H₁ |
183
+ | 30-100 | Very strong for H₁ |
184
+ | 10-30 | Strong for H₁ |
185
+ | 3-10 | Moderate for H₁ |
186
+ | 1-3 | Anecdotal for H₁ |
187
+ | 1 | No evidence |
188
+ | 1/3-1 | Anecdotal for H₀ |
189
+ | 1/10-1/3 | Moderate for H₀ |
190
+ | 1/30-1/10 | Strong for H₀ |
191
+ | 1/100-1/30 | Very strong for H₀ |
192
+ | <1/100 | Decisive for H₀ |
193
+
194
+ **Advantages over p-values**:
195
+ 1. Can provide evidence for null hypothesis
196
+ 2. Less dependent on sampling intentions than p-values — but only Bayes factors with fixed priors are relatively insensitive to optional stopping; posterior-based decision rules are still affected, and transparency requires reporting the stopping rule
197
+ 3. Directly quantifies evidence
198
+ 4. Can be updated with more data
199
+
200
+ **Python calculation**:
201
+ ```python
202
+ # Pingouin 0.5+: BF10 for independent two-sided t-tests; one-sided BF removed.
203
+ import pingouin as pg
204
+
205
+ result = pg.ttest(group1, group2, correction=False)
206
+ bf10 = result['BF10'].values[0]
207
+
208
+ # Rigorous Bayes Factors: BayesFactor (R), JASP, or PyMC model comparison (see pymc skill)
209
+ ```
210
+
211
+ ---
212
+
213
+ ### Region of Practical Equivalence (ROPE)
214
+
215
+ **Purpose**: Define range of negligible effect sizes
216
+
217
+ **Process**:
218
+ 1. Define ROPE (e.g., d ∈ [-0.1, 0.1] for negligible effects)
219
+ 2. Calculate % of posterior inside ROPE
220
+ 3. Make decision:
221
+ - >95% in ROPE: Accept practical equivalence
222
+ - >95% outside ROPE: Reject equivalence
223
+ - Otherwise: Inconclusive
224
+
225
+ **Advantage**: Directly tests for practical significance
226
+
227
+ **Python example**:
228
+ ```python
229
+ # Define ROPE
230
+ rope_lower, rope_upper = -0.1, 0.1
231
+
232
+ # Calculate % of posterior in ROPE
233
+ in_rope = np.mean((posterior_samples > rope_lower) &
234
+ (posterior_samples < rope_upper))
235
+
236
+ print(f"{in_rope*100:.1f}% of posterior in ROPE")
237
+ ```
238
+
239
+ ---
240
+
241
+ ## Bayesian Estimation
242
+
243
+ ### Credible Intervals
244
+
245
+ **What it is**: Interval containing parameter with X% probability
246
+
247
+ **95% Credible Interval interpretation**:
248
+ > "There is a 95% probability that the true parameter lies in this interval."
249
+
250
+ **This is what people THINK confidence intervals mean** (but don't in frequentist framework)
251
+
252
+ **Types**:
253
+
254
+ #### Equal-Tailed Interval (ETI)
255
+ - 2.5th to 97.5th percentile
256
+ - Simple to calculate
257
+ - May not include mode for skewed distributions
258
+
259
+ #### Highest Density Interval (HDI)
260
+ - Narrowest interval containing 95% of distribution
261
+ - Always includes mode
262
+ - Better for skewed distributions
263
+
264
+ **Python calculation**:
265
+ ```python
266
+ import arviz as az
267
+
268
+ # Equal-tailed interval
269
+ eti = np.percentile(posterior_samples, [2.5, 97.5])
270
+
271
+ # HDI (ArviZ 1.x renamed the keyword hdi_prob= to prob=)
272
+ hdi = az.hdi(posterior_samples, prob=0.95)
273
+ ```
274
+
275
+ ---
276
+
277
+ ### Posterior Distributions
278
+
279
+ **Interpreting posterior distributions**:
280
+
281
+ 1. **Central tendency**:
282
+ - Mean: Average posterior value
283
+ - Median: 50th percentile
284
+ - Mode: Most probable value (MAP - Maximum A Posteriori)
285
+
286
+ 2. **Uncertainty**:
287
+ - SD: Spread of posterior
288
+ - Credible intervals: Quantify uncertainty
289
+
290
+ 3. **Shape**:
291
+ - Symmetric: Similar to normal
292
+ - Skewed: Asymmetric uncertainty
293
+ - Multimodal: Multiple plausible values
294
+
295
+ **Visualization**:
296
+ ```python
297
+ import matplotlib.pyplot as plt
298
+ import arviz as az
299
+
300
+ # Posterior plot with 95% credible interval
301
+ # (ArviZ 1.x replaced plot_posterior with plot_dist and hdi_prob= with ci_prob=)
302
+ az.plot_dist(trace, ci_prob=0.95)
303
+
304
+ # Trace plot (check convergence)
305
+ az.plot_trace(trace)
306
+
307
+ # Forest plot (multiple parameters)
308
+ az.plot_forest(trace)
309
+ ```
310
+
311
+ ---
312
+
313
+ ## Common Bayesian Analyses
314
+
315
+ ### Bayesian T-Test
316
+
317
+ **Purpose**: Compare two groups (Bayesian alternative to t-test)
318
+
319
+ **Outputs**:
320
+ 1. Posterior distribution of mean difference
321
+ 2. 95% credible interval
322
+ 3. Bayes Factor (BF₁₀)
323
+ 4. Probability of directional hypothesis (e.g., P(μ₁ > μ₂))
324
+
325
+ **Python implementation**:
326
+ ```python
327
+ import pymc as pm
328
+ import arviz as az
329
+
330
+ # Bayesian independent samples t-test
331
+ with pm.Model() as model:
332
+ # Priors for group means
333
+ mu1 = pm.Normal('mu1', mu=0, sigma=10)
334
+ mu2 = pm.Normal('mu2', mu=0, sigma=10)
335
+
336
+ # Prior for pooled standard deviation
337
+ sigma = pm.HalfNormal('sigma', sigma=10)
338
+
339
+ # Likelihood
340
+ y1 = pm.Normal('y1', mu=mu1, sigma=sigma, observed=group1)
341
+ y2 = pm.Normal('y2', mu=mu2, sigma=sigma, observed=group2)
342
+
343
+ # Derived quantity: mean difference
344
+ diff = pm.Deterministic('diff', mu1 - mu2)
345
+
346
+ # Sample posterior
347
+ trace = pm.sample(2000, tune=1000)
348
+
349
+ # Analyze results
350
+ print(az.summary(trace, var_names=['mu1', 'mu2', 'diff']))
351
+
352
+ # Probability that group1 > group2
353
+ prob_greater = np.mean(trace.posterior['diff'].values > 0)
354
+ print(f"P(μ₁ > μ₂) = {prob_greater:.3f}")
355
+
356
+ # Plot posterior (ArviZ 1.x: plot_posterior was replaced by plot_dist;
357
+ # add a reference line at 0 with matplotlib if needed)
358
+ az.plot_dist(trace, var_names=['diff'])
359
+ ```
360
+
361
+ ---
362
+
363
+ ### Bayesian ANOVA
364
+
365
+ **Purpose**: Compare three or more groups
366
+
367
+ **Model**:
368
+ ```python
369
+ import pymc as pm
370
+
371
+ with pm.Model() as anova_model:
372
+ # Hyperpriors
373
+ mu_global = pm.Normal('mu_global', mu=0, sigma=10)
374
+ sigma_between = pm.HalfNormal('sigma_between', sigma=5)
375
+ sigma_within = pm.HalfNormal('sigma_within', sigma=5)
376
+
377
+ # Group means (hierarchical)
378
+ group_means = pm.Normal('group_means',
379
+ mu=mu_global,
380
+ sigma=sigma_between,
381
+ shape=n_groups)
382
+
383
+ # Likelihood
384
+ y = pm.Normal('y',
385
+ mu=group_means[group_idx],
386
+ sigma=sigma_within,
387
+ observed=data)
388
+
389
+ trace = pm.sample(2000, tune=1000)
390
+
391
+ # Posterior contrasts
392
+ contrast_1_2 = trace.posterior['group_means'][:,:,0] - trace.posterior['group_means'][:,:,1]
393
+ ```
394
+
395
+ ---
396
+
397
+ ### Bayesian Correlation
398
+
399
+ **Purpose**: Estimate correlation between two variables
400
+
401
+ **Advantage**: Provides distribution of correlation values
402
+
403
+ **Python implementation**:
404
+ ```python
405
+ import numpy as np
406
+ import pymc as pm
407
+
408
+ # Standardize both variables first: with z-scored data the bivariate normal
409
+ # can fix mu = [0, 0] and unit variances, leaving rho as the only free
410
+ # parameter (correlation is unchanged by linear rescaling). Alternatively,
411
+ # model the means and SDs as parameters (or use pm.LKJCholeskyCov).
412
+ xz = (x - x.mean()) / x.std()
413
+ yz = (y - y.mean()) / y.std()
414
+
415
+ with pm.Model() as corr_model:
416
+ # Prior on correlation
417
+ rho = pm.Uniform('rho', lower=-1, upper=1)
418
+
419
+ # Correlation (= covariance) matrix for standardized data
420
+ cov_matrix = pm.math.stack([[1, rho],
421
+ [rho, 1]])
422
+
423
+ # Likelihood (bivariate normal on standardized data)
424
+ obs = pm.MvNormal('obs',
425
+ mu=[0, 0],
426
+ cov=cov_matrix,
427
+ observed=np.column_stack([xz, yz]))
428
+
429
+ trace = pm.sample(2000, tune=1000)
430
+
431
+ # Summarize correlation
432
+ print(az.summary(trace, var_names=['rho']))
433
+
434
+ # Probability that correlation is positive
435
+ prob_positive = np.mean(trace.posterior['rho'].values > 0)
436
+ ```
437
+
438
+ ---
439
+
440
+ ### Bayesian Linear Regression
441
+
442
+ **Purpose**: Model relationship between predictors and outcome
443
+
444
+ **Advantages**:
445
+ - Uncertainty in all parameters
446
+ - Natural regularization (via priors)
447
+ - Can incorporate prior knowledge
448
+ - Credible intervals for predictions
449
+
450
+ **Python implementation**:
451
+ ```python
452
+ import pymc as pm
453
+
454
+ with pm.Model() as regression_model:
455
+ # Mutable data container: required for pm.set_data() to swap in new
456
+ # predictors later (a raw array would make set_data fail)
457
+ X_data = pm.Data('X', X)
458
+
459
+ # Priors for coefficients
460
+ alpha = pm.Normal('alpha', mu=0, sigma=10) # Intercept
461
+ beta = pm.Normal('beta', mu=0, sigma=10, shape=n_predictors)
462
+ sigma = pm.HalfNormal('sigma', sigma=10)
463
+
464
+ # Expected value
465
+ mu = alpha + pm.math.dot(X_data, beta)
466
+
467
+ # Likelihood (shape=mu.shape lets predictions resize with new data)
468
+ y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, shape=mu.shape)
469
+
470
+ trace = pm.sample(2000, tune=1000)
471
+
472
+ # Posterior predictive checks
473
+ with regression_model:
474
+ ppc = pm.sample_posterior_predictive(trace)
475
+
476
+ az.plot_ppc_dist(ppc) # ArviZ 1.x: plot_ppc was replaced by plot_ppc_dist
477
+
478
+ # Predictions with uncertainty
479
+ with regression_model:
480
+ pm.set_data({'X': X_new})
481
+ posterior_pred = pm.sample_posterior_predictive(trace, predictions=True)
482
+ ```
483
+
484
+ ---
485
+
486
+ ## Hierarchical (Multilevel) Models
487
+
488
+ **When to use**:
489
+ - Nested/clustered data (students within schools)
490
+ - Repeated measures
491
+ - Meta-analysis
492
+ - Varying effects across groups
493
+
494
+ **Key concept**: Partial pooling
495
+ - Complete pooling: Ignore groups (biased)
496
+ - No pooling: Analyze groups separately (high variance)
497
+ - Partial pooling: Borrow strength across groups (Bayesian)
498
+
499
+ **Example: Varying intercepts**:
500
+ ```python
501
+ with pm.Model() as hierarchical_model:
502
+ # Hyperpriors
503
+ mu_global = pm.Normal('mu_global', mu=0, sigma=10)
504
+ sigma_between = pm.HalfNormal('sigma_between', sigma=5)
505
+ sigma_within = pm.HalfNormal('sigma_within', sigma=5)
506
+
507
+ # Group-level intercepts
508
+ alpha = pm.Normal('alpha',
509
+ mu=mu_global,
510
+ sigma=sigma_between,
511
+ shape=n_groups)
512
+
513
+ # Likelihood
514
+ y_obs = pm.Normal('y_obs',
515
+ mu=alpha[group_idx],
516
+ sigma=sigma_within,
517
+ observed=y)
518
+
519
+ trace = pm.sample()
520
+ ```
521
+
522
+ ---
523
+
524
+ ## Model Comparison
525
+
526
+ ### Methods
527
+
528
+ #### 1. Bayes Factor
529
+ - Directly compares model evidence
530
+ - Sensitive to prior specification
531
+ - Can be computationally intensive
532
+
533
+ #### 2. Information Criteria
534
+
535
+ **WAIC (Widely Applicable Information Criterion)**:
536
+ - Bayesian analog of AIC
537
+ - Reported on the elpd (expected log pointwise predictive density) scale: HIGHER elpd is better (only on the deviance scale, −2 × elpd, is lower better)
538
+ - Accounts for effective number of parameters
539
+ - `az.waic` was removed in ArviZ 1.x — use LOO
540
+
541
+ **LOO (Leave-One-Out Cross-Validation)**:
542
+ - Estimates out-of-sample prediction error
543
+ - Also on the elpd scale: higher elpd is better
544
+ - More robust than WAIC
545
+
546
+ **Python calculation**:
547
+ ```python
548
+ import arviz as az
549
+ import pymc as pm
550
+
551
+ # LOO needs pointwise log-likelihoods
552
+ with model:
553
+ pm.compute_log_likelihood(trace)
554
+
555
+ loo = az.loo(trace)
556
+ print(f"LOO elpd: {loo.elpd:.2f}") # higher is better
557
+
558
+ # Compare multiple models: az.compare ranks them correctly (rank 0 = best)
559
+ comparison = az.compare({
560
+ 'model1': trace1,
561
+ 'model2': trace2,
562
+ 'model3': trace3
563
+ })
564
+ print(comparison)
565
+ ```
566
+
567
+ ---
568
+
569
+ ## Checking Bayesian Models
570
+
571
+ ### 1. Convergence Diagnostics
572
+
573
+ **R-hat (Gelman-Rubin statistic)**:
574
+ - Compares within-chain and between-chain variance
575
+ - Values close to 1.0 indicate convergence
576
+ - R-hat < 1.01: Good
577
+ - R-hat > 1.05: Poor convergence
578
+
579
+ **Effective Sample Size (ESS)**:
580
+ - Number of independent samples
581
+ - Higher is better
582
+ - Bulk-ESS > 400 in total across all chains recommended (Vehtari et al., 2021); also check tail-ESS
583
+
584
+ **Trace plots**:
585
+ - Should look like "fuzzy caterpillar"
586
+ - No trends, no stuck chains
587
+
588
+ **Python checking**:
589
+ ```python
590
+ # Automatic summary with diagnostics
591
+ print(az.summary(trace, var_names=['parameter']))
592
+
593
+ # Visual diagnostics
594
+ az.plot_trace(trace)
595
+ az.plot_rank(trace) # Rank plots
596
+ ```
597
+
598
+ ---
599
+
600
+ ### 2. Posterior Predictive Checks
601
+
602
+ **Purpose**: Does model generate data similar to observed data?
603
+
604
+ **Process**:
605
+ 1. Generate predictions from posterior
606
+ 2. Compare to actual data
607
+ 3. Look for systematic discrepancies
608
+
609
+ **Python implementation**:
610
+ ```python
611
+ with model:
612
+ ppc = pm.sample_posterior_predictive(trace)
613
+
614
+ # Visual check (ArviZ 1.x: plot_ppc was replaced by plot_ppc_dist)
615
+ az.plot_ppc_dist(ppc, num_samples=100)
616
+
617
+ # Quantitative check: compute the statistic per posterior draw over the
618
+ # observation dimension (do NOT iterate the array directly - that loops
619
+ # over chains, not draws)
620
+ obs_mean = np.mean(observed_data)
621
+ pp = ppc.posterior_predictive['y_obs'] # dims: (chain, draw, obs)
622
+ pred_means = pp.mean(dim=pp.dims[-1]).values.ravel() # one mean per draw
623
+ p_value = np.mean(pred_means >= obs_mean) # Bayesian (posterior predictive) p-value
624
+ ```
625
+
626
+ ---
627
+
628
+ ## Reporting Bayesian Results
629
+
630
+ ### Example T-Test Report
631
+
632
+ > "A Bayesian independent samples t-test was conducted to compare groups A and B. Weakly informative priors were used: Normal(0, 1) for the mean difference and Half-Cauchy(0, 1) for the pooled standard deviation. The posterior distribution of the mean difference had a mean of 5.2 (95% CI [2.3, 8.1]), indicating that Group A scored higher than Group B. The Bayes Factor BF₁₀ = 23.5 provided strong evidence for a difference between groups, and there was a 99.7% probability that Group A's mean exceeded Group B's mean."
633
+
634
+ ### Example Regression Report
635
+
636
+ > "A Bayesian linear regression was fitted with weakly informative priors (Normal(0, 10) for coefficients, Half-Cauchy(0, 5) for residual SD). The model explained substantial variance (R² = 0.47, 95% CI [0.38, 0.55]). Study hours (β = 0.52, 95% CI [0.38, 0.66]) and prior GPA (β = 0.31, 95% CI [0.17, 0.45]) were credible predictors (95% CIs excluded zero). Posterior predictive checks showed good model fit. Convergence diagnostics were satisfactory (all R-hat < 1.01, ESS > 1000)."
637
+
638
+ ---
639
+
640
+ ## Advantages and Limitations
641
+
642
+ ### Advantages
643
+
644
+ 1. **Intuitive interpretation**: Direct probability statements about parameters
645
+ 2. **Incorporates prior knowledge**: Uses all available information
646
+ 3. **Flexible**: Handles complex models easily
647
+ 4. **Less sensitive to optional stopping**: Bayes factors with fixed priors are relatively robust to analyzing data as it arrives, but posterior-based decision rules are still affected — always report the stopping rule
648
+ 5. **Quantifies uncertainty**: Full posterior distribution
649
+ 6. **Small samples**: Works at any sample size (but small-n posteriors are prior-dominated — report a prior-sensitivity check)
650
+
651
+ ### Limitations
652
+
653
+ 1. **Computational**: Requires MCMC sampling (can be slow)
654
+ 2. **Prior specification**: Requires thought and justification
655
+ 3. **Complexity**: Steeper learning curve
656
+ 4. **Software**: Fewer tools than frequentist methods
657
+ 5. **Communication**: May need to educate reviewers/readers
658
+
659
+ ---
660
+
661
+ ## Key Python Packages
662
+
663
+ Install with uv (see SKILL.md). ArviZ requires Python >= 3.10. ArviZ 1.x is the current line and is a breaking rewrite: `az.summary` defaults to 89% intervals and takes `ci_prob=` (the old `hdi_prob=` keyword is gone), `az.hdi` takes `prob=`, `az.plot_posterior`/`az.plot_ppc` were replaced by `az.plot_dist`/`az.plot_ppc_dist`, and `az.waic` was removed (use `az.loo`).
664
+
665
+ - **PyMC** (`pymc>=5`): Full Bayesian modeling framework
666
+ - **ArviZ** (`arviz>=1.0`): Visualization and diagnostics ([docs](https://python.arviz.org))
667
+ - **Bambi**: High-level interface for regression models (`uv pip install bambi`)
668
+ - **cmdstanpy**: Python interface to Stan (use instead of the discontinued PyStan)
669
+ - **TensorFlow Probability**: Bayesian inference with TensorFlow
670
+
671
+ ---
672
+
673
+ ## When to Use Bayesian Methods
674
+
675
+ **Use Bayesian when**:
676
+ - You have prior information to incorporate
677
+ - You want direct probability statements
678
+ - Sample size is small
679
+ - Model is complex (hierarchical, missing data, etc.)
680
+ - You want to update analysis as data arrives
681
+
682
+ **Frequentist may be sufficient when**:
683
+ - Standard analysis with large sample
684
+ - No prior information
685
+ - Computational resources limited
686
+ - Reviewers unfamiliar with Bayesian methods