papilon 0.3.0__tar.gz → 1.0.0__tar.gz

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 (58) hide show
  1. papilon-1.0.0/NOTICE +30 -0
  2. papilon-1.0.0/PKG-INFO +380 -0
  3. papilon-1.0.0/README.md +328 -0
  4. papilon-1.0.0/papilon/__init__.py +49 -0
  5. papilon-1.0.0/papilon/_deprecation.py +39 -0
  6. papilon-1.0.0/papilon/ai.py +280 -0
  7. papilon-1.0.0/papilon/causal.py +43 -0
  8. {papilon-0.3.0 → papilon-1.0.0}/papilon/datasets.py +56 -1
  9. papilon-1.0.0/papilon/discovery.py +156 -0
  10. papilon-1.0.0/papilon/energy.py +18 -0
  11. papilon-1.0.0/papilon/entropy.py +23 -0
  12. papilon-1.0.0/papilon/graph.py +441 -0
  13. papilon-1.0.0/papilon/io.py +128 -0
  14. papilon-1.0.0/papilon/loop.py +228 -0
  15. papilon-1.0.0/papilon/mcp_server.py +113 -0
  16. papilon-1.0.0/papilon/mmm/__init__.py +19 -0
  17. papilon-1.0.0/papilon/mmm/geo.py +294 -0
  18. papilon-1.0.0/papilon/mmm/model.py +1653 -0
  19. {papilon-0.3.0 → papilon-1.0.0}/papilon/mmm/transforms.py +13 -0
  20. papilon-1.0.0/papilon/optimizer.py +30 -0
  21. papilon-1.0.0/papilon/persist.py +107 -0
  22. {papilon-0.3.0 → papilon-1.0.0}/papilon/relationships.py +13 -0
  23. papilon-1.0.0/papilon/report.py +211 -0
  24. papilon-1.0.0/papilon/simulation.py +23 -0
  25. papilon-1.0.0/papilon/states.py +23 -0
  26. {papilon-0.3.0 → papilon-1.0.0}/papilon/topology.py +36 -23
  27. papilon-1.0.0/papilon/tracking.py +59 -0
  28. papilon-1.0.0/papilon.egg-info/PKG-INFO +380 -0
  29. {papilon-0.3.0 → papilon-1.0.0}/papilon.egg-info/SOURCES.txt +16 -1
  30. papilon-1.0.0/papilon.egg-info/requires.txt +32 -0
  31. {papilon-0.3.0 → papilon-1.0.0}/pyproject.toml +10 -3
  32. {papilon-0.3.0 → papilon-1.0.0}/setup.cfg +4 -4
  33. papilon-1.0.0/tests/test_license_headers.py +16 -0
  34. papilon-1.0.0/tests/test_mmm.py +167 -0
  35. papilon-1.0.0/tests/test_public_api.py +33 -0
  36. papilon-1.0.0/tests/test_v050.py +159 -0
  37. papilon-1.0.0/tests/test_v100.py +262 -0
  38. papilon-0.3.0/NOTICE +0 -13
  39. papilon-0.3.0/PKG-INFO +0 -183
  40. papilon-0.3.0/README.md +0 -145
  41. papilon-0.3.0/papilon/__init__.py +0 -27
  42. papilon-0.3.0/papilon/causal.py +0 -25
  43. papilon-0.3.0/papilon/energy.py +0 -5
  44. papilon-0.3.0/papilon/entropy.py +0 -10
  45. papilon-0.3.0/papilon/mmm/__init__.py +0 -6
  46. papilon-0.3.0/papilon/mmm/model.py +0 -380
  47. papilon-0.3.0/papilon/optimizer.py +0 -17
  48. papilon-0.3.0/papilon/simulation.py +0 -10
  49. papilon-0.3.0/papilon/states.py +0 -10
  50. papilon-0.3.0/papilon.egg-info/PKG-INFO +0 -183
  51. papilon-0.3.0/papilon.egg-info/requires.txt +0 -12
  52. papilon-0.3.0/tests/test_mmm.py +0 -76
  53. {papilon-0.3.0 → papilon-1.0.0}/LICENSE +0 -0
  54. {papilon-0.3.0 → papilon-1.0.0}/papilon.egg-info/dependency_links.txt +0 -0
  55. {papilon-0.3.0 → papilon-1.0.0}/papilon.egg-info/top_level.txt +0 -0
  56. {papilon-0.3.0 → papilon-1.0.0}/tests/test_datasets.py +0 -0
  57. {papilon-0.3.0 → papilon-1.0.0}/tests/test_transforms.py +0 -0
  58. {papilon-0.3.0 → papilon-1.0.0}/tests/test_v020_tools.py +0 -0
papilon-1.0.0/NOTICE ADDED
@@ -0,0 +1,30 @@
1
+ Papilon
2
+ Copyright 2024-2026 Brian Curry / Vector1 Research
3
+
4
+ This product includes software developed by Brian Curry / Vector1 Research
5
+ (https://vector1.ai).
6
+
7
+ "Papilon", "PyCausalSim", "Vector1" and "Vector1 Research" are trademarks of Brian Curry.
8
+ The Apache License, Version 2.0 does not grant permission to use these names
9
+ or marks, except as required to describe the origin of the work (see Section 6
10
+ of the License and TRADEMARKS.md).
11
+
12
+ Papilon depends on, but does not include, NumPy, SciPy, pandas, scikit-learn,
13
+ NetworkX, Matplotlib and seaborn, each distributed under its own license.
14
+
15
+ Methods first published in this repository, with the release that introduced them
16
+ (see CHANGELOG.md and docs/design/ for dated descriptions):
17
+
18
+ - Gated importance sampling for marketing mix models, with Bayes-factor
19
+ selection of carryover and saturation families (0.3.0, 0.5.0)
20
+ - Downside-protected budget planning with support flags (0.4.0)
21
+ - Self-check on simulated copies of a brand, lift-test value by posterior
22
+ reweighting, and the MarketingGraph ontology with its audit (0.5.0)
23
+ - The learning loop with value-of-information experiment choice and budget-neutral
24
+ exploration between indistinguishable channels, graded against known truth;
25
+ conjugate geo pooling with sampled shared curves (1.0.0)
26
+
27
+ The marketing vocabulary at https://vector1.ai/ns/marketing# is maintained by
28
+ Vector1 Research. Derivative works must keep this NOTICE (Apache License 2.0,
29
+ Section 4(d)) and must not imply endorsement by, or affiliation with, Brian Curry
30
+ or Vector1 Research.
papilon-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,380 @@
1
+ Metadata-Version: 2.4
2
+ Name: papilon
3
+ Version: 1.0.0
4
+ Summary: A Bayesian marketing mix model you can check: graded against known truth, with a marketing knowledge graph, self-checks, lift-test planning and grounded tools for AI assistants
5
+ Author-email: Brian Curry <brian@vector1.ai>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://vector1.ai
8
+ Project-URL: Repository, https://github.com/Bodhi8/papilon
9
+ Project-URL: Issues, https://github.com/Bodhi8/papilon/issues
10
+ Project-URL: Changelog, https://github.com/Bodhi8/papilon/blob/main/CHANGELOG.md
11
+ Keywords: marketing mix modeling,MMM,media mix model,bayesian,adstock,importance sampling,causal inference,budget optimization,statistical mechanics,knowledge graph,ontology,lift test,incrementality,model context protocol,simulation
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering
21
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ License-File: NOTICE
26
+ Requires-Dist: numpy>=1.24
27
+ Requires-Dist: pandas>=2.0
28
+ Requires-Dist: scipy>=1.10
29
+ Requires-Dist: scikit-learn>=1.3
30
+ Requires-Dist: networkx>=3.0
31
+ Requires-Dist: matplotlib>=3.7
32
+ Requires-Dist: seaborn>=0.13
33
+ Provides-Extra: dev
34
+ Requires-Dist: pytest>=7.0; extra == "dev"
35
+ Requires-Dist: build>=1.0; extra == "dev"
36
+ Requires-Dist: twine>=5.0; extra == "dev"
37
+ Provides-Extra: mcp
38
+ Requires-Dist: mcp>=1.2; extra == "mcp"
39
+ Provides-Extra: mlflow
40
+ Requires-Dist: mlflow>=2.10; extra == "mlflow"
41
+ Provides-Extra: snowflake
42
+ Requires-Dist: snowflake-connector-python[pandas]>=3.6; extra == "snowflake"
43
+ Provides-Extra: bigquery
44
+ Requires-Dist: google-cloud-bigquery[pandas]>=3.17; extra == "bigquery"
45
+ Provides-Extra: sql
46
+ Requires-Dist: sqlalchemy>=2.0; extra == "sql"
47
+ Provides-Extra: all
48
+ Requires-Dist: mcp>=1.2; extra == "all"
49
+ Requires-Dist: mlflow>=2.10; extra == "all"
50
+ Requires-Dist: sqlalchemy>=2.0; extra == "all"
51
+ Dynamic: license-file
52
+
53
+ <p align="center">
54
+ <img src="https://raw.githubusercontent.com/Bodhi8/papilon/main/assets/papilon-banner.jpg" alt="A butterfly whose wingbeat spirals out into a Lorenz attractor" width="100%">
55
+ </p>
56
+
57
+ # Papilon
58
+
59
+ <p align="center">
60
+ <img src="https://img.shields.io/badge/version-1.0.0-blue.svg" alt="Version 1.0.0">
61
+ <img src="https://img.shields.io/badge/python-3.10+-green.svg" alt="Python 3.10+">
62
+ <img src="https://img.shields.io/badge/license-Apache%202.0-lightgrey.svg" alt="Apache 2.0 license">
63
+ </p>
64
+
65
+ <p align="center"><em>"Does the flap of a butterfly's wings in Brazil set off a tornado in Texas?" Edward Lorenz</em></p>
66
+
67
+ Papilon (French for butterfly) is a Bayesian marketing mix modeling framework you can
68
+ check. It chooses each channel's carryover and saturation form by Bayes factor, reports
69
+ when its posterior can't be trusted and falls back to a stronger sampler, plans budgets
70
+ for the case where it is wrong, and is graded in public against simulated brands with
71
+ known returns.
72
+
73
+ Version 1.0 is a production release. It adds regional models with partial pooling,
74
+ Weibull carryover, logistic and S-shaped curves, effects that change over time, reach and
75
+ frequency, organic channels, lift tests calibrated on the weeks they ran, forward
76
+ forecasts and scenarios, causal discovery, and the **learning loop**: a refresh cycle that
77
+ recommends the experiment worth the most to the budget plan, separates channels the model
78
+ cannot tell apart with a small budget-neutral pulse, and is itself graded quarter by
79
+ quarter against known truth. Around the model: data checks, warehouse loaders, saved
80
+ models that open without Papilon, MLflow logging, drift monitoring, HTML reports, CI on
81
+ three operating systems and a stable API.
82
+
83
+ Documentation: [guides and API reference](docs/index.md).
84
+
85
+ ## Install
86
+
87
+ ```bash
88
+ pip install papilon # core
89
+ pip install "papilon[mlflow,snowflake,mcp]" # optional: tracking, warehouse, AI assistants
90
+ ```
91
+
92
+ ## What 1.0 covers
93
+
94
+ | Area | Capability |
95
+ |---|---|
96
+ | Model forms | geometric, delayed and Weibull carryover; Hill, S-curve and logistic saturation; time-varying effects; baseline drift; chosen per channel by Bayes factor |
97
+ | Inputs | paid media, reach and frequency, organic channels, controls with their own contributions |
98
+ | Calibration | lift tests in the likelihood on the weeks they ran; return priors |
99
+ | Regions | `GeoMMM`: shared curves, regional effects pooled toward a common effect, integrated exactly |
100
+ | Inference | importance sampling with a quality gate, mixture proposals over all modes, tempered SMC fallback |
101
+ | Checking | backtest, self-check on simulated copies of the brand, confounding stress test, open leaderboard |
102
+ | Planning | downside-protected plans, plan stability and bagging, forward forecasts, paired scenarios |
103
+ | Learning | `Loop`: refresh, score, recommend the most valuable test, explore between indistinguishable channels |
104
+ | Structure | knowledge graph with audit, back-door identification, PC causal discovery against the data |
105
+ | Production | data checks, SQL, Snowflake and BigQuery loaders, save and load without pickles, MLflow, drift monitoring, HTML reports, AI tools and an MCP server |
106
+ | Stability | semantic versioning, API snapshot test, deprecation policy, CI on Linux, Windows and macOS |
107
+
108
+ ## Quickstart: a marketing mix model with a known truth
109
+
110
+ `make_synthetic_mmm()` creates three years of weekly sales for a brand running four
111
+ digital channels, and returns the parameters that generated it, so you can check every
112
+ estimate against the truth.
113
+
114
+ ```python
115
+ import papilon as pp
116
+
117
+ df, truth = pp.make_synthetic_mmm()
118
+
119
+ model = pp.MMM(
120
+ data=df,
121
+ target="sales",
122
+ media=["paid_search", "paid_social", "online_video", "display"],
123
+ date_col="date",
124
+ controls=["price_index", "promo"],
125
+ yearly_seasonality=2,
126
+ seed=11,
127
+ )
128
+
129
+ # Does online video's effect peak after the week it runs? Let the data decide.
130
+ families = model.compare_carryover({
131
+ "all_geometric": [],
132
+ "video_delayed": ["online_video"],
133
+ })
134
+
135
+ roi = model.get_roi() # ROAS with 90% intervals
136
+ plan = model.optimize_budget(total=df[model.media].sum(axis=1).mean())
137
+ plan.attrs["summary"] # expected gain, 90% interval, chance it beats the current mix
138
+ ```
139
+
140
+ Output from `examples/mmm_quickstart.py`, abridged (spend and sales in $ thousands):
141
+
142
+ ```
143
+ log_evidence log_bayes_factor_vs_best probability ess_fraction verdict
144
+ all_geometric 242.639 -20.991 0.0 0.146 ACCEPT
145
+ video_delayed 263.629 0.000 1.0 0.140 ACCEPT
146
+
147
+ spend roas_mean roas_p05 roas_p95 mroas_mean true_roas
148
+ paid_search 4729.95 0.65 0.04 1.76 0.30 1.25
149
+ paid_social 7678.08 0.95 0.42 1.68 0.47 1.50
150
+ online_video 7369.53 1.75 1.50 2.02 0.86 1.57
151
+ display 3497.10 0.63 0.04 1.54 0.31 0.74
152
+
153
+ current_spend optimal_spend change_in_spend outside_support
154
+ paid_search 30.3 20.7 -9.6 False
155
+ paid_social 49.2 43.5 -5.7 False
156
+ online_video 47.2 70.9 23.6 True
157
+ display 22.4 14.1 -8.3 False
158
+ ```
159
+
160
+ The model picks the delayed carryover shape for online video and puts its peak at 2.0
161
+ weeks, the true value. Every true ROAS falls inside its 90% interval. The point
162
+ estimates for paid search and paid social are low: search spend in this dataset follows
163
+ seasonal demand, which makes it hard to separate from seasonality with three years of
164
+ weekly data. That is the job lift tests do: pass a measured return as
165
+ `roi_priors={"paid_search": (mean, sd)}` and the model is calibrated to it.
166
+
167
+ The plan moves $23,600 a week toward online video and flags that $70,900 a week is
168
+ more than the brand has sustained before. Against the true response curves it adds
169
+ $4,400 a week in sales, about 79% of the best possible reallocation ($5,600). The 0.3
170
+ optimizer, on the same fit, moves $38,000 for $800.
171
+
172
+ ## The learning loop (new in 1.0)
173
+
174
+ A model refit every quarter on data shaped by its own plans can lock in its mistakes.
175
+ `pp.Loop` feeds back only new information: new periods, experiment results on the weeks
176
+ they ran, and a small budget-neutral pulse between the two channels the model can least
177
+ tell apart. Each cycle values every possible lift test by its expected gain to the plan
178
+ over a year, nets off the sales the holdout would give up, and recommends one only if it
179
+ pays for itself.
180
+
181
+ ```python
182
+ loop = pp.Loop(history, "sales", media, "date", controls=controls, horizon=13)
183
+ cycle = loop.cycle() # plan, weekly schedule, recommended test
184
+ cycle = loop.cycle(new_data=last_quarter, tests=[measured_test])
185
+ loop.history()
186
+ ```
187
+
188
+ Graded against known truth over six quarters ([benchmarks/LOOP.md](benchmarks/LOOP.md)):
189
+ on standard brands the loop's plans captured 59% of the best available gain by quarter
190
+ six, against 42% for refitting each quarter and 34% for fitting once, at no net cost in
191
+ sales. On brands with launches the model cannot see, its error in estimated returns fell
192
+ from 0.59 to 0.39, against 0.50 for refitting alone. Testing every quarter learns faster
193
+ still (78% captured, error 0.31) and costs 0.3% to 0.5% of sales while it learns.
194
+
195
+ <p align="center"><img src="benchmarks/loop.png" alt="Error and share of best gain captured by quarter for four policies" width="760"></p>
196
+
197
+ ## Declare, check, decide (from 0.5)
198
+
199
+ ```python
200
+ g = pp.MarketingGraph("sales") # what you believe about the brand
201
+ g.channel("paid_search", stage="lower").channel("online_video", stage="upper")
202
+ g.driver("seasonality", ["paid_search", "sales"], modeled=True) # search spend follows demand
203
+ g.event("launch", ["paid_search", "sales"]) # no column: unobserved
204
+ g.mediates("online_video", "paid_search") # video lifts branded search
205
+ g.audit(df) # paid_search: launch has no data, its return is not identified; run a lift test
206
+
207
+ model = g.build_model(df, date_col="date") # controls and priors from the graph
208
+ model.compare_carryover(g.carryover_candidates())
209
+ model.compare_models({"concave": {}, "video_s": {"s_curve": ["online_video"]}}) # curve shape by Bayes factor
210
+
211
+ model.backtest(13) # forecast held-out weeks against a naive forecast
212
+ model.self_check(12) # refit to simulated copies of this brand with known returns
213
+ model.self_check(12, confounded={"paid_search": 0.5}) # what an unmeasured driver would do
214
+ model.value_of_lift_test() # which experiment is worth the most to the plan, in sales per week
215
+ ```
216
+
217
+ **Knowledge graph.** `MarketingGraph` is a small ontology: channels with a funnel stage,
218
+ drivers, events and experiments, joined by `drives`, `sets_spend`, `mediates`,
219
+ `belongs_to` and `measured_by`. It compiles into model settings, names every estimate
220
+ that rests on a driver you declared but cannot measure, answers "what else moves if I
221
+ cut this?" (`what_moves()`), and exports to JSON-LD. Edges suggested by a language model
222
+ enter as `propose()` and are ignored until you `confirm()` them. The same graph feeds
223
+ `pycausalsim.futures.worlds_from_graph`, which simulates brands with that structure
224
+ and an answer key. A graph makes assumptions explicit; it does not make them true.
225
+
226
+ **Self-checks.** `self_check()` answers whether this model, with this data, could
227
+ recover returns like the ones it reports. `value_of_lift_test()` simulates each
228
+ possible lift test, updates the posterior by reweighting its draws, re-plans, and
229
+ reports the expected gain: on the bundled brand it ranks paid search first and online
230
+ video last in about a second.
231
+
232
+ **AI assistants.** `papilon.ai.ToolBox(model, graph=g)` exposes the model as tools with
233
+ JSON schemas in the layouts chat model APIs accept; every result carries the caveats that
234
+ apply to it, decided by fixed rules. `python -m papilon.mcp_server --data ...` serves
235
+ the same tools over the Model Context Protocol. Papilon calls no language model and
236
+ sends no data anywhere: the assistant writes sentences, the model supplies the numbers.
237
+
238
+ `examples/checkable_mmm.py` runs all of this in about a minute. The methods are
239
+ described in [RFC 002](docs/design/002-checkable-mmm.md).
240
+
241
+ Guides: [quickstart](docs/quickstart.md), [the knowledge graph](docs/knowledge-graph.md),
242
+ [checking the model](docs/checking.md), [AI assistants](docs/ai-assistants.md) and the
243
+ [marketing vocabulary](docs/vocabulary/README.md). The
244
+ [open leaderboard](benchmarks/LEADERBOARD.md) scores models on simulated brands with
245
+ known returns, and [anyone can enter one](benchmarks/SUBMITTING.md).
246
+
247
+ ## What Papilon does not do yet
248
+
249
+ - **Very large models.** The sampler keeps the sampled dimension small (regional effects
250
+ are integrated out exactly), which covers dozens of regions. A gradient-based sampler for
251
+ hundreds of free parameters, such as regional curve shapes or product hierarchies, is
252
+ planned as an optional backend.
253
+ - **In geo models:** time-varying effects, reach and frequency, organic channels, lift tests
254
+ and forecasting. Fit a national model on summed data for those.
255
+ - **Mediated effects** are declared in the knowledge graph and audited, not estimated.
256
+
257
+ To grade any model, from any library, on the same simulated brands, wrap it as a function
258
+ and use `pycausalsim.futures.leaderboard`.
259
+
260
+ ## Budget plans that hold up
261
+
262
+ A marketing mix model can have honest intervals and still produce a bad plan:
263
+ optimizing expected sales leans hardest on whichever channel the model overrates.
264
+ `benchmarks/recovery.py` grades Papilon on 120 simulated brands with known returns,
265
+ generated by [PyCausalSim](https://github.com/Bodhi8/pycausalsim)'s temporal causal
266
+ model (`pycausalsim.futures.marketing`). Half are standard; half add unobserved
267
+ product launches that raise search and social spend and demand together, and social
268
+ creative that wears out. Results, share of the best possible gain captured and share of
269
+ brands where the plan lost money:
270
+
271
+ | Setting | 0.3 rule (max expected, 0 to 3x), 0.4.0 fit | 0.4.0 default (10th percentile, within 50%) | 0.4.1 default |
272
+ |---|---|---|---|
273
+ | Standard brands | 32%, lost money 33% | 46%, lost money 7% | 43%, lost money 2% |
274
+ | Standard + lift test on paid search | 65%, 10% | 58%, 2% | 57%, 0% |
275
+ | Launches hidden from the model | -132%, 83% | 5%, 45% | 10%, 37% |
276
+ | Launch calendar as a control | 37%, 25% | 41%, 12% | 39%, 8% |
277
+ | Launch calendar + lift test | 56%, 17% | 50%, 8% | 48%, 8% |
278
+
279
+ The 0.4 default gives up a few points in the best cases to avoid the worst ones. Three
280
+ things matter more than the optimizer: put known events such as launches in
281
+ `controls`, calibrate the channels the data cannot separate from demand with lift
282
+ tests (`roi_priors`), and read `plan.attrs["summary"]["prob_better"]` before moving
283
+ money.
284
+
285
+ 0.4.1 puts the prior on each channel's return on the ROAS scale. Before, every channel
286
+ shared one prior on its effect in units of mean sales, which handed small channels a
287
+ prior return of 4 to 10 and overrated display by about 0.5 on average. Display's
288
+ overstatement now averages +0.21 to +0.30 across the five settings, against +0.49 to
289
+ +0.66 in 0.4.0.
290
+
291
+ To play a plan forward week by week with carryover and the full posterior, hand
292
+ `model.posterior_curves()` to `pycausalsim.futures.media_plan_scm`.
293
+
294
+ 1.0.0 leaves these results in place. On the [open leaderboard](benchmarks/LEADERBOARD.md)
295
+ (16 simulated brands per track), compared with 0.5:
296
+
297
+ | Track | 90% range holds the truth | Best gain captured | Plans that lost money |
298
+ |---|---|---|---|
299
+ | Standard | 95% → 98% | 51% → 48% | 0% → 0% |
300
+ | Hard (unobserved launches) | 67% → 69% | 27% → 29% | 31% → 31% |
301
+ | S-curve, shape chosen by the data | 81% → 81% | 38% → 37% | 0% → 0% |
302
+
303
+ Differences of a few points are within the noise of 16 brands. A least-squares
304
+ regression on adstocked spend, graded on the same standard brands, holds the truth 45%
305
+ of the time and its plans lose money for half of them. Brands with launches the model
306
+ cannot see remain the weak spot; the learning loop's tests are the remedy (see above).
307
+
308
+ ## How the model is fit
309
+
310
+ `pp.MMM` follows the inference path in
311
+ [RFC 001, amortized structural inference](papilon-amortized-inference-design.md):
312
+
313
+ 1. **Proposal.** A distribution over the media parameters (carryover, saturation,
314
+ effect size). Since 0.3.0, a Laplace fit at the posterior mode stands in for the
315
+ trained amortized network the RFC describes.
316
+ 2. **Importance sampling** against the exact posterior. Baseline, trend, seasonality,
317
+ controls and noise are integrated out in closed form, so sampling covers only the
318
+ media parameters.
319
+ 3. **Effective-sample-size gate.** If the proposal matches the posterior well, it is
320
+ accepted. If not, it is refined from the weighted draws and tried again, or the fit
321
+ is escalated. `model.gate_results` records every step.
322
+ 4. **Bayes factors.** The same importance weights estimate each family's marginal
323
+ likelihood, so `compare_carryover()` can choose between geometric and delayed
324
+ adstock per channel.
325
+
326
+ Channel effects are constrained to be positive. The single-channel prototypes behind
327
+ this design, with their results, are in [`prototypes/`](prototypes/).
328
+
329
+ ## Other tools (from 0.2.0)
330
+
331
+ ```python
332
+ import papilon as pp
333
+
334
+ pp.shannon_entropy(values) # information content
335
+ pp.simulate_kde_scenarios(df, columns, n_samples=1000) # scenario simulation
336
+ pp.analyze_relationships(df, target="sales") # correlation and mutual information
337
+ pp.infer_causal_structure(df, threshold=0.01) # pairwise dependency screen
338
+ pp.grid_search_optimize(df, feature_ranges, objective_fn, constraints)
339
+ ```
340
+
341
+ `infer_causal_structure` tests each pair of variables for a significant linear
342
+ relationship. It is a screen for dependencies, not causal discovery: it does not orient
343
+ edges or adjust for confounders.
344
+
345
+ The notebook `Papilon_Marketing_Optimization_Workflow.ipynb` walks through these tools.
346
+
347
+ ## Tests
348
+
349
+ ```bash
350
+ pip install -e ".[dev]"
351
+ pytest -m "not slow" # about three minutes
352
+ pytest # includes the full Bayes-factor recovery test, a few minutes
353
+ ```
354
+
355
+ ## Roadmap
356
+
357
+ These are planned and **not in the released package**:
358
+
359
+ - An optional gradient-based (NUTS) sampler for very large models
360
+ - The trained amortized network from RFC 001 as a proposal
361
+ - Geo models with time-varying effects, lift tests and forecasting
362
+ - Mediated effects estimated in the model, not only declared in the graph
363
+ - Published leaderboard entries for other open-source models on the same worlds
364
+
365
+ ## License
366
+
367
+ Apache License 2.0, free for commercial use. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
368
+
369
+ ## Citation
370
+
371
+ If you use Papilon in research, please cite:
372
+
373
+ ```
374
+ Curry, B. (2026). Papilon: Bayesian marketing mix modeling with gated importance
375
+ sampling (Version 1.0.0). https://github.com/Bodhi8/papilon
376
+ ```
377
+
378
+ Built by [Brian Curry](https://vector1.ai), Vector1 Research. Papilon, PyCausalSim and
379
+ Vector1 are trademarks of Brian Curry. The license covers the code, not the names:
380
+ see [TRADEMARKS.md](TRADEMARKS.md).