partworth 0.0.1__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 (55) hide show
  1. partworth-0.0.1/.gitignore +17 -0
  2. partworth-0.0.1/CHANGELOG.md +18 -0
  3. partworth-0.0.1/CITATION.cff +14 -0
  4. partworth-0.0.1/CONTRIBUTING.md +36 -0
  5. partworth-0.0.1/LICENSE +202 -0
  6. partworth-0.0.1/PKG-INFO +218 -0
  7. partworth-0.0.1/README.md +179 -0
  8. partworth-0.0.1/docs/adr/0001-clean-room-and-sources.md +53 -0
  9. partworth-0.0.1/docs/adr/0002-own-model-not-pymc-marketing.md +23 -0
  10. partworth-0.0.1/docs/adr/0003-non-centred-lkj.md +24 -0
  11. partworth-0.0.1/docs/adr/0004-sign-constraint.md +25 -0
  12. partworth-0.0.1/docs/adr/0005-sawtooth-definitions.md +31 -0
  13. partworth-0.0.1/docs/adr/0006-ai-assistance.md +10 -0
  14. partworth-0.0.1/docs/guide.md +142 -0
  15. partworth-0.0.1/examples/camera.py +33 -0
  16. partworth-0.0.1/examples/retail_survey.ipynb +2197 -0
  17. partworth-0.0.1/examples/retail_survey_ja.ipynb +2188 -0
  18. partworth-0.0.1/pyproject.toml +63 -0
  19. partworth-0.0.1/src/partworth/__init__.py +29 -0
  20. partworth-0.0.1/src/partworth/coding.py +275 -0
  21. partworth-0.0.1/src/partworth/data.py +261 -0
  22. partworth-0.0.1/src/partworth/datasets/__init__.py +6 -0
  23. partworth-0.0.1/src/partworth/datasets/camera.py +111 -0
  24. partworth-0.0.1/src/partworth/datasets/simulate.py +99 -0
  25. partworth-0.0.1/src/partworth/errors.py +21 -0
  26. partworth-0.0.1/src/partworth/io/__init__.py +12 -0
  27. partworth-0.0.1/src/partworth/io/design.py +144 -0
  28. partworth-0.0.1/src/partworth/io/sawtooth.py +73 -0
  29. partworth-0.0.1/src/partworth/models.py +175 -0
  30. partworth-0.0.1/src/partworth/results.py +300 -0
  31. partworth-0.0.1/src/partworth/simulate.py +166 -0
  32. partworth-0.0.1/tests/conftest.py +79 -0
  33. partworth-0.0.1/tests/statistical/test_recovery.py +82 -0
  34. partworth-0.0.1/tests/unit/test_coding.py +80 -0
  35. partworth-0.0.1/tests/unit/test_data.py +91 -0
  36. partworth-0.0.1/tests/unit/test_design.py +64 -0
  37. partworth-0.0.1/tests/unit/test_models.py +66 -0
  38. partworth-0.0.1/tests/unit/test_results.py +98 -0
  39. partworth-0.0.1/tests/unit/test_review2_fixes.py +93 -0
  40. partworth-0.0.1/tests/unit/test_review_fixes.py +95 -0
  41. partworth-0.0.1/tests/unit/test_simulate.py +14 -0
  42. partworth-0.0.1/tests/unit/test_simulate_market.py +115 -0
  43. partworth-0.0.1/validation/compare_camera.py +161 -0
  44. partworth-0.0.1/validation/performance.py +54 -0
  45. partworth-0.0.1/validation/recovery.py +90 -0
  46. partworth-0.0.1/validation/results/bayesm_version.txt +1 -0
  47. partworth-0.0.1/validation/results/camera_default_priors.csv +11 -0
  48. partworth-0.0.1/validation/results/camera_report.md +46 -0
  49. partworth-0.0.1/validation/results/camera_wide_priors.csv +11 -0
  50. partworth-0.0.1/validation/results/performance.md +8 -0
  51. partworth-0.0.1/validation/results/recovery_report.md +18 -0
  52. partworth-0.0.1/validation/results/sbc_ranks.csv +201 -0
  53. partworth-0.0.1/validation/results/sbc_report.md +18 -0
  54. partworth-0.0.1/validation/run_bayesm.R +36 -0
  55. partworth-0.0.1/validation/sbc.py +136 -0
@@ -0,0 +1,17 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ .coverage
10
+ htmlcov/
11
+ # third-party data is fetched at runtime and never committed
12
+ data/
13
+ *.rda
14
+ *.RData
15
+
16
+ # bayesm outputs at respondent level are derived from GPL-distributed data
17
+ validation/results/bayesm_*.csv
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 0.0.1 (2026-10-14)
4
+
5
+ First release on PyPI.
6
+
7
+ - `ChoiceData.from_long`: validated long-format input, ragged tasks/alternatives, none
8
+ option, respondent covariates, `subset`, `holdout`, `describe`
9
+ - Effects, dummy and linear coding with sign constraints
10
+ - `HierarchicalMNL`: non-centred hierarchical MNL with LKJ covariance, covariate
11
+ regression of the population mean, lognormal sign constraints, nutpie or PyMC NUTS
12
+ - `HBResult`: part-worths, zero-centred diffs, importances, RLH, population summary,
13
+ diagnostics with guidance, hold-out prediction, Sawtooth-style CSV, save/load
14
+ - `MarketSimulator` (logit and first choice, credible intervals, weights, price curves,
15
+ shares for each posterior draw with `share_draws`) and `wtp`
16
+ - `datasets.load_camera` (fetched from CRAN at run time) and `datasets.simulate_cbc`
17
+ - Validation against R bayesm (`validation/`)
18
+ - Example notebooks on a dummy retail survey, in English and Japanese (`examples/`)
@@ -0,0 +1,14 @@
1
+ cff-version: 1.2.0
2
+ message: "If you use partworth, please cite it as below."
3
+ title: "partworth: hierarchical Bayes choice-based conjoint analysis in Python"
4
+ authors:
5
+ - family-names: Miyazawa
6
+ given-names: Koji
7
+ license: Apache-2.0
8
+ repository-code: "https://github.com/kojikojikojikoji/partworth"
9
+ version: 0.0.1
10
+ keywords:
11
+ - conjoint analysis
12
+ - discrete choice
13
+ - hierarchical Bayes
14
+ - PyMC
@@ -0,0 +1,36 @@
1
+ # Contributing
2
+
3
+ Issues and pull requests are welcome, especially:
4
+
5
+ - comparisons with other software (Sawtooth CBC/HB, bayesm, apollo, Biogeme) on data you
6
+ can share;
7
+ - public CBC data sets that could become examples;
8
+ - reports of convergence problems with a reproducible (simulated or public) example.
9
+
10
+ ## Ground rules
11
+
12
+ - **Public or simulated data only.** Do not add examples, fixtures or attribute sets
13
+ derived from non-public studies (see `docs/adr/0001-clean-room-and-sources.md`).
14
+ - **No GPL code.** Do not port code from bayesm, apollo or other GPL packages. Comparing
15
+ against them from `validation/` in a separate process is fine.
16
+ - Record design decisions that change behaviour in a new ADR under `docs/adr/`.
17
+
18
+ ## Development
19
+
20
+ ```
21
+ uv venv --python 3.12 && uv pip install -e ".[dev]"
22
+ pytest -q # fast unit tests
23
+ pytest -q --run-slow # MCMC tests (parameter recovery), a few minutes
24
+ pytest -q --run-network # tests that download the camera data
25
+ ruff check src tests validation
26
+ ```
27
+
28
+ Validation scripts (need more time; `compare_camera.py` also needs R with bayesm):
29
+
30
+ ```
31
+ python validation/compare_camera.py
32
+ python validation/sbc.py --reps 200
33
+ python validation/performance.py
34
+ ```
35
+
36
+ On macOS 26+ with PyTensor 3.3.3 or earlier, set `PYTENSOR_FLAGS=cxx=` (see README).
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,218 @@
1
+ Metadata-Version: 2.5
2
+ Name: partworth
3
+ Version: 0.0.1
4
+ Summary: Hierarchical Bayes choice-based conjoint analysis in Python, with Sawtooth-style outputs and a market simulator
5
+ Project-URL: Homepage, https://github.com/kojikojikojikoji/partworth
6
+ Project-URL: Issues, https://github.com/kojikojikojikoji/partworth/issues
7
+ Author: Koji Miyazawa
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: choice-based conjoint,conjoint,discrete choice,hierarchical bayes,market research,pymc
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
18
+ Requires-Python: >=3.12
19
+ Requires-Dist: arviz<2,>=1.3
20
+ Requires-Dist: h5netcdf>=1.3
21
+ Requires-Dist: h5py>=3.10
22
+ Requires-Dist: numpy>=1.26
23
+ Requires-Dist: pandas>=2.2
24
+ Requires-Dist: pymc<7,>=6.3
25
+ Requires-Dist: xarray>=2024.10
26
+ Provides-Extra: datasets
27
+ Requires-Dist: rdata>=0.11; extra == 'datasets'
28
+ Provides-Extra: dev
29
+ Requires-Dist: nutpie>=0.16; extra == 'dev'
30
+ Requires-Dist: pytest>=8; extra == 'dev'
31
+ Requires-Dist: rdata>=0.11; extra == 'dev'
32
+ Requires-Dist: ruff>=0.6; extra == 'dev'
33
+ Requires-Dist: tabulate>=0.9; extra == 'dev'
34
+ Provides-Extra: nutpie
35
+ Requires-Dist: nutpie>=0.16; extra == 'nutpie'
36
+ Provides-Extra: pmm
37
+ Requires-Dist: pymc-marketing>=1.2; extra == 'pmm'
38
+ Description-Content-Type: text/markdown
39
+
40
+ # partworth
41
+
42
+ partworth estimates hierarchical Bayes (HB) models for choice-based conjoint (CBC)
43
+ studies in Python. It is built on [PyMC](https://www.pymc.io/).
44
+
45
+ It covers the whole workflow in one package: data checks, HB estimation, respondent-level
46
+ part-worths, Sawtooth-style output files, a market simulator and willingness to pay (WTP).
47
+ The validation scripts and their results are in the repository.
48
+
49
+ > **Status: pre-alpha.** The API may change.
50
+
51
+ ## What you can do with it
52
+
53
+ ```mermaid
54
+ flowchart TB
55
+ subgraph S1["1. Your survey"]
56
+ direction LR
57
+ A["CBC answers<br/>(long format)"]
58
+ B["Design from ChoiceDesign<br/>(wide format)"]
59
+ A ~~~ B
60
+ end
61
+ subgraph S2["2. Fit one model"]
62
+ direction LR
63
+ C["ChoiceData<br/>checks the data"] --> D["HierarchicalMNL<br/>HB estimation on PyMC"] --> E["Diagnostics<br/>R-hat, ESS, divergences"]
64
+ end
65
+ subgraph S3["3. Read the results"]
66
+ direction LR
67
+ F["Part-worths<br/>for each respondent"]
68
+ G["Importances and RLH"]
69
+ H["Sawtooth-style CSV"]
70
+ F ~~~ G ~~~ H
71
+ end
72
+ subgraph S4["4. Answer business questions"]
73
+ direction LR
74
+ I["Which product wins?<br/>shares with<br/>credible intervals"]
75
+ J["What if we change<br/>the price?<br/>price curves"]
76
+ K["How much will<br/>people pay?<br/>WTP for a feature"]
77
+ I ~~~ J ~~~ K
78
+ end
79
+ S1 --> S2 --> S3 --> S4
80
+ ```
81
+
82
+ Steps 1 to 3 replace the usual "estimate in one tool, export, simulate in a spreadsheet" work.
83
+ Step 4 uses all posterior draws, so every share, price curve and WTP comes with its uncertainty.
84
+
85
+ ## Why partworth
86
+
87
+ - Sawtooth CBC/HB is commercial and runs outside Python. partworth gives the same kind of
88
+ outputs (raw utilities, zero-centred diffs, importances, RLH) in an open Python package.
89
+ - pymc-marketing's `MixedLogit` is a general choice model. partworth is built for CBC
90
+ studies: long-format survey data, correlated random coefficients, a negative price
91
+ coefficient for every respondent, and a simulator with credible intervals.
92
+ - Each result can be checked. The repository compares partworth with R `bayesm` on public
93
+ data and tests that it recovers known parameters.
94
+
95
+ ## What works now
96
+
97
+ - Long-format choice data with checks, tasks of different sizes and a none option
98
+ - Import of wide designs, such as the output of [ChoiceDesign](https://choicedesign.readthedocs.io/)
99
+ - Effects, dummy and linear coding, with an optional sign constraint (for price)
100
+ - Hierarchical MNL with correlated coefficients (LKJ prior), respondent covariates and the
101
+ nutpie sampler
102
+ - Part-worths, zero-centred diffs, importances, RLH and convergence diagnostics
103
+ - Sawtooth-style utilities CSV (read and write)
104
+ - Market simulator with credible intervals, price curves and WTP
105
+
106
+ Not planned: experimental design (use ChoiceDesign),
107
+ latent class, MaxDiff and ACBC.
108
+
109
+ ## Installation
110
+
111
+ ```
112
+ pip install "partworth[nutpie,datasets]"
113
+ ```
114
+
115
+ `nutpie` adds the faster sampler. `datasets` adds the reader for the public camera data.
116
+
117
+ It needs Python 3.12 or later.
118
+
119
+ On macOS 26 or later, PyTensor 3.3.3 or earlier can fail with
120
+ `ld: library 'd64' not found`. Set `PYTENSOR_FLAGS=cxx=` to avoid it. The fix is merged in
121
+ PyTensor ([pymc-devs/pytensor#2432](https://github.com/pymc-devs/pytensor/pull/2432)) but
122
+ not yet released.
123
+
124
+ ## Quick look
125
+
126
+ This example uses simulated data, so you can paste it as it is.
127
+
128
+ ```python
129
+ import pandas as pd
130
+ import partworth as pw
131
+ from partworth.datasets import simulate_cbc
132
+
133
+ # 300 respondents, 12 tasks, 3 products + "none" per task.
134
+ # mu: true population means of the coded coefficients (price on the log scale).
135
+ data, truth = simulate_cbc(
136
+ 300, 12, 3,
137
+ {"brand": ["A", "B", "C"], "size": ["S", "M", "L"], "price": [2.0, 2.5, 3.0, 3.5]},
138
+ price="price", mu=[0.4, -0.1, -0.3, 0.1, -0.5, -1.0], sd=0.6, seed=1,
139
+ )
140
+ print(data.describe()) # how often each level was shown and chosen
141
+
142
+ # more tuning and draws than the defaults: the SD of "none" mixes slowly (see the guide)
143
+ result = pw.HierarchicalMNL(data).fit(draws=2000, tune=3000, chains=4, random_seed=1)
144
+ print(result.diagnostics().report()) # R-hat, ESS, divergences, what to try
145
+
146
+ result.part_worths() # raw utilities, one column per level
147
+ result.part_worths("zc_diffs") # zero-centred diffs
148
+ result.importances()
149
+ result.to_sawtooth_csv("utilities.csv")
150
+
151
+ scenario = pd.DataFrame({"product": ["Ours", "Theirs"], "brand": ["A", "B"],
152
+ "size": ["M", "M"], "price": [3.0, 2.5]})
153
+ sim = pw.MarketSimulator(result)
154
+ print(sim.shares(scenario)) # shares with 90% credible intervals
155
+ print(sim.price_curve(scenario, product="Ours", grid=[2.0, 2.5, 3.0, 3.5]))
156
+ print(pw.wtp(result, attribute="size", from_level="S", to_level="L"))
157
+ ```
158
+
159
+ For your own data, build `ChoiceData` from a long table (one row per respondent, task and
160
+ alternative):
161
+
162
+ ```python
163
+ data = pw.ChoiceData.from_long(
164
+ df, # your table
165
+ attributes={"brand": pw.Categorical(["A", "B", "C"]),
166
+ "price": pw.Linear(sign="negative")},
167
+ none="is_none", # optional "no purchase" rows
168
+ )
169
+ ```
170
+
171
+ [examples/retail_survey.ipynb](https://github.com/kojikojikojikoji/partworth/blob/main/examples/retail_survey.ipynb) is a notebook on a dummy retail
172
+ survey. It goes from the survey table to shares, prices and profit. A Japanese version is in
173
+ [examples/retail_survey_ja.ipynb](https://github.com/kojikojikojikoji/partworth/blob/main/examples/retail_survey_ja.ipynb).
174
+ [examples/camera.py](https://github.com/kojikojikojikoji/partworth/blob/main/examples/camera.py) runs the same steps on public data.
175
+ [docs/guide.md](https://github.com/kojikojikojikoji/partworth/blob/main/docs/guide.md) explains the choices you make along the way.
176
+
177
+ ## Validation
178
+
179
+ Each script in [validation/](https://github.com/kojikojikojikoji/partworth/tree/main/validation/) writes its report to
180
+ [validation/results/](https://github.com/kojikojikojikoji/partworth/tree/main/validation/results/).
181
+
182
+ - **Parameter recovery** ([recovery_report.md](https://github.com/kojikojikojikoji/partworth/blob/main/validation/results/recovery_report.md)).
183
+ 300 simulated respondents and 12 tasks. Respondent-level 90% intervals covered 88.7% of
184
+ the true values. 5 of 6 population means and 6 of 6 SDs were inside their 90%
185
+ intervals. The price mean (log scale) was just outside. The convergence targets were met.
186
+ Correlations reached R-hat 1.013 and ESS 399, just short of the targets.
187
+ `pytest --run-slow` runs the same fit and checks.
188
+ - **Comparison with R bayesm** ([camera_report.md](https://github.com/kojikojikojikoji/partworth/blob/main/validation/results/camera_report.md)).
189
+ `bayesm::rhierMnlRwMixture` on the public camera data. Respondent-level posterior means
190
+ correlate at 0.997 or more for every coefficient. The hold-out hit rate is 0.729 for
191
+ partworth and 0.730 for bayesm. Population means differ by up to 0.21 posterior SDs.
192
+ Our target was 0.1, so this target is not met. The two packages use different priors.
193
+ - **Simulation-based calibration** ([sbc_report.md](https://github.com/kojikojikojikoji/partworth/blob/main/validation/results/sbc_report.md)).
194
+ 200 simulated data sets, 8 population parameters. The smallest uniformity p-value was
195
+ 0.017. None was below 0.006, the threshold after correcting for 8 tests. Earlier runs
196
+ showed low p-values for different parameters each time. 15 of the 200 fits had a
197
+ population ESS below 99, which weakens the check.
198
+ - **Performance** ([performance.md](https://github.com/kojikojikojikoji/partworth/blob/main/validation/results/performance.md)). 300 respondents
199
+ took 74 s and 1,000 respondents took 290 s on one laptop.
200
+
201
+ ## Data and licences
202
+
203
+ partworth is licensed under Apache-2.0. The `camera` data belongs to the R package
204
+ [bayesm](https://cran.r-project.org/package=bayesm), which is GPL. partworth downloads it
205
+ from CRAN on first use and never includes it. No bayesm code is used. The comparison runs
206
+ R in a separate process.
207
+
208
+ All examples use public or simulated data.
209
+
210
+ ## How this is built
211
+
212
+ Design decisions are in [docs/adr/](https://github.com/kojikojikojikoji/partworth/tree/main/docs/adr/). Parts of the code were written with an AI
213
+ coding assistant. The model, the priors and the validation targets are the author's
214
+ decisions. The ADRs record them.
215
+
216
+ ## Licence
217
+
218
+ Apache License 2.0. See [LICENSE](https://github.com/kojikojikojikoji/partworth/blob/main/LICENSE).