├── .codecov.yml ├── .coveragerc ├── .github ├── ISSUE_TEMPLATE │ ├── issue.md │ └── new-commits-to-pymc3.md └── workflows │ ├── even-with-pymc3.yml │ ├── lint.yml │ └── tests.yml ├── .gitignore ├── .pylintrc ├── .readthedocs.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE.pymc3.txt ├── LICENSE.pymc4.txt ├── LICENSE.txt ├── MANIFEST.in ├── Makefile ├── README.md ├── docs ├── .gitignore ├── Makefile ├── _static │ ├── logo │ │ ├── README.md │ │ ├── cover.png │ │ ├── default-cropped.png │ │ ├── default.png │ │ ├── profile.png │ │ └── vector │ │ │ ├── default-monochrome-black.svg │ │ │ ├── default-monochrome-white.svg │ │ │ ├── default-monochrome.svg │ │ │ ├── default.svg │ │ │ ├── isolated-layout.svg │ │ │ ├── isolated-monochrome-black.svg │ │ │ └── isolated-monochrome-white.svg │ ├── notebooks │ │ ├── framework_cookbook.ipynb │ │ └── quickstart.ipynb │ └── scripts │ │ ├── sample_jax_logp_dlogp_func.py │ │ └── sample_pytorch_logp_dlogp_func.py ├── api.rst ├── conf.py ├── developer_guide.rst ├── index.rst ├── install.rst ├── make.bat └── tutorials │ ├── framework_cookbook.rst │ ├── framework_cookbook_files │ ├── framework_cookbook_18_0.png │ ├── framework_cookbook_1_0.png │ └── framework_cookbook_3_0.png │ ├── quickstart.rst │ └── tutorial_rst.tpl ├── littlemcmc ├── __init__.py ├── base_hmc.py ├── exceptions.py ├── hmc.py ├── integration.py ├── math.py ├── nuts.py ├── parallel_sampling.py ├── quadpotential.py ├── report.py ├── sampling.py └── step_sizes.py ├── pyproject.toml ├── requirements-dev.txt ├── requirements.txt ├── scripts └── check-for-pymc3-commits.sh ├── setup.cfg ├── setup.py └── tests ├── test_hmc.py ├── test_quadpotential.py ├── test_sampling.py ├── test_utils.py └── test_various_frameworks.py /.codecov.yml: -------------------------------------------------------------------------------- 1 | codecov: 2 | require_ci_to_pass: yes 3 | 4 | coverage: 5 | precision: 2 6 | round: down 7 | range: "70...100" 8 | 9 | status: 10 | project: yes 11 | patch: yes 12 | changes: no 13 | 14 | comment: 15 | layout: "reach, diff, flags, files" 16 | behavior: default 17 | require_changes: true # if true: only post the comment if coverage changes 18 | require_base: no # [yes :: must have a base report to post] 19 | require_head: yes # [yes :: must have a head report to post] 20 | branches: null # branch names that can post comment 21 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | omit = 3 | # Exclude tests files from coverage calculation 4 | tests/test_*.py 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Issue 3 | about: Issue template for user-submitted issues. Please use this if you're a human! 4 | --- 5 | 6 | ## Description 7 | 8 | **Please provide a minimal, self-contained, and reproducible example.** 9 | 10 | ```python 11 | [Your code here] 12 | ``` 13 | 14 | **Please provide the full traceback.** 15 | 16 | ```python 17 | [The error output here] 18 | ``` 19 | 20 | **Please provide any additional information below.** 21 | 22 | 23 | ## Environment 24 | 25 | * LittleMCMC version: 26 | * Python version: 27 | * Operating system: 28 | 29 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/new-commits-to-pymc3.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: New commits to `pymc3/sampling.py` or `pymc3/step_methods/hmc/` 3 | about: Issue template for auto-generated issues. Do not use if you're a human! 4 | title: 'New commits to `pymc3/sampling.py` or `pymc3/step_methods/hmc/`' 5 | labels: '' 6 | assignees: eigenfoo 7 | --- 8 | 9 | > This is an auto-generated issue, triggered by the `even-with-pymc3` workflow. 10 | 11 | There have been new commits to `pymc3/sampling.py` or `pymc3/step_methods/hmc/` since 12 | yesterday: please see [the latest run of the `even-with-pymc3` GitHub 13 | Action](https://github.com/eigenfoo/littlemcmc/actions?query=workflow%3Aeven-with-pymc3) 14 | and consider if these commits are worth mirroring in `littlemcmc`. 15 | 16 | -------------------------------------------------------------------------------- /.github/workflows/even-with-pymc3.yml: -------------------------------------------------------------------------------- 1 | name: even-with-pymc3 2 | 3 | on: 4 | schedule: 5 | # Every day at 1pm UTC (9am EST) 6 | - cron: '0 13 * * *' 7 | 8 | jobs: 9 | even-with-pymc3: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Check for commits to the pymc3/step_methods/hmc/ directory 14 | run: ./scripts/check-for-pymc3-commits.sh 15 | - name: Create issue if there are new commits 16 | uses: JasonEtco/create-an-issue@v2 17 | env: 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 19 | with: 20 | filename: .github/ISSUE_TEMPLATE/new-commits-to-pymc3.md 21 | if: failure() 22 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: lint 2 | 3 | on: [push] 4 | 5 | jobs: 6 | lint: 7 | 8 | runs-on: ubuntu-latest 9 | strategy: 10 | max-parallel: 4 11 | matrix: 12 | python-version: [3.6, 3.7] 13 | 14 | steps: 15 | - uses: actions/checkout@v1 16 | - name: Set up Python ${{ matrix.python-version }} 17 | uses: actions/setup-python@v1 18 | with: 19 | python-version: ${{ matrix.python-version }} 20 | - name: Install dependencies 21 | run: | 22 | python -m pip install --upgrade pip 23 | pip install -r requirements.txt 24 | pip install -r requirements-dev.txt 25 | - name: black 26 | run: make blackstyle 27 | - name: pydocstyle 28 | run: make pydocstyle 29 | - name: pylint 30 | run: make pylintstyle 31 | - name: mypy 32 | run: make mypytypes 33 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | 8 | runs-on: ubuntu-latest 9 | strategy: 10 | max-parallel: 4 11 | matrix: 12 | python-version: [3.6, 3.7] 13 | 14 | steps: 15 | - uses: actions/checkout@v1 16 | - name: Set up Python ${{ matrix.python-version }} 17 | uses: actions/setup-python@v1 18 | with: 19 | python-version: ${{ matrix.python-version }} 20 | - name: Install dependencies 21 | run: | 22 | python -m pip install --upgrade pip 23 | pip install -r requirements.txt 24 | pip install -r requirements-dev.txt 25 | - name: Run tests and generate reports 26 | run: make test 27 | - name: Upload coverage to Codecov 28 | uses: codecov/codecov-action@v1 29 | if: matrix.python-version == 3.7 30 | with: 31 | token: ${{ secrets.CODECOV_TOKEN }} 32 | file: ./coverage.xml 33 | name: codecov-umbrella 34 | fail_ci_if_error: true 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Custom 2 | environment.yml 3 | testing-report.html 4 | pip-wheel-metadata/* 5 | 6 | # Byte-compiled / optimized / DLL files 7 | __pycache__/ 8 | *.py[cod] 9 | *$py.class 10 | 11 | # C extensions 12 | *.so 13 | 14 | # Distribution / packaging 15 | .Python 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # Unit test / coverage reports 34 | htmlcov/ 35 | .tox/ 36 | .coverage 37 | .coverage.* 38 | .cache 39 | nosetests.xml 40 | coverage.xml 41 | *.cover 42 | .hypothesis/ 43 | .pytest_cache/ 44 | 45 | # Sphinx documentation 46 | docs/_build/ 47 | 48 | # Jupyter Notebook 49 | .ipynb_checkpoints 50 | 51 | # pyenv 52 | .python-version 53 | 54 | # Environments 55 | .env 56 | .venv 57 | env/ 58 | env-littlemcmc/ 59 | venv/ 60 | venv-littlemcmc/ 61 | ENV/ 62 | env.bak/ 63 | venv.bak/ 64 | 65 | # mkdocs documentation 66 | /site 67 | 68 | # mypy 69 | .mypy_cache/ 70 | 71 | # Merge tool 72 | *.orig 73 | 74 | # VSCode 75 | .vscode/ 76 | 77 | # IntelliJ IDE 78 | .idea 79 | *.iml 80 | 81 | # Vim 82 | *.swp 83 | 84 | # OS generated files 85 | .DS_Store 86 | .DS_Store? 87 | ._* 88 | .Spotlight-V100 89 | .Trashes 90 | ehthumbs.db 91 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | # Use multiple processes to speed up Pylint. 3 | jobs=1 4 | 5 | # Allow loading of arbitrary C extensions. Extensions are imported into the 6 | # active Python interpreter and may run arbitrary code. 7 | unsafe-load-any-extension=no 8 | 9 | # Allow optimization of some AST trees. This will activate a peephole AST 10 | # optimizer, which will apply various small optimizations. For instance, it can 11 | # be used to obtain the result of joining multiple strings with the addition 12 | # operator. Joining a lot of strings can lead to a maximum recursion error in 13 | # Pylint and this flag can prevent that. It has one side effect, the resulting 14 | # AST will be different than the one from reality. 15 | optimize-ast=no 16 | 17 | [MESSAGES CONTROL] 18 | 19 | # Only show warnings with the listed confidence levels. Leave empty to show 20 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED 21 | confidence= 22 | 23 | # Disable the message, report, category or checker with the given id(s). You 24 | # can either give multiple identifiers separated by comma (,) or put this 25 | # option multiple times (only on the command line, not in the configuration 26 | # file where it should appear only once).You can also use "--disable=all" to 27 | # disable everything first and then reenable specific checks. For example, if 28 | # you want to run only the similarities checker, you can use "--disable=all 29 | # --enable=similarities". If you want to run only the classes checker, but have 30 | # no Warning level messages displayed, use"--disable=all --enable=classes 31 | # --disable=W" 32 | disable=all 33 | 34 | # Enable the message, report, category or checker with the given id(s). You can 35 | # either give multiple identifier separated by comma (,) or put this option 36 | # multiple time. See also the "--disable" option for examples. 37 | enable=import-error, 38 | import-self, 39 | reimported, 40 | wildcard-import, 41 | misplaced-future, 42 | relative-import, 43 | deprecated-module, 44 | unpacking-non-sequence, 45 | invalid-all-object, 46 | undefined-all-variable, 47 | used-before-assignment, 48 | cell-var-from-loop, 49 | global-variable-undefined, 50 | dangerous-default-value, 51 | # redefined-builtin, 52 | redefine-in-handler, 53 | unused-import, 54 | unused-wildcard-import, 55 | global-variable-not-assigned, 56 | undefined-loop-variable, 57 | global-statement, 58 | global-at-module-level, 59 | bad-open-mode, 60 | redundant-unittest-assert, 61 | boolean-datetime, 62 | # unused-variable 63 | 64 | 65 | [REPORTS] 66 | 67 | # Set the output format. Available formats are text, parseable, colorized, msvs 68 | # (visual studio) and html. You can also give a reporter class, eg 69 | # mypackage.mymodule.MyReporterClass. 70 | output-format=parseable 71 | 72 | # Put messages in a separate file for each module / package specified on the 73 | # command line instead of printing them on stdout. Reports (if any) will be 74 | # written in a file name "pylint_global.[txt|html]". 75 | files-output=no 76 | 77 | # Tells whether to display a full report or only the messages 78 | reports=no 79 | 80 | # Python expression which should return a note less than 10 (10 is the highest 81 | # note). You have access to the variables errors warning, statement which 82 | # respectively contain the number of errors / warnings messages and the total 83 | # number of statements analyzed. This is used by the global evaluation report 84 | # (RP0004). 85 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 86 | 87 | [BASIC] 88 | 89 | # List of builtins function names that should not be used, separated by a comma 90 | bad-functions=map,filter,input 91 | 92 | # Good variable names which should always be accepted, separated by a comma 93 | good-names=i,j,k,ex,Run,_ 94 | 95 | # Bad variable names which should always be refused, separated by a comma 96 | bad-names=foo,bar,baz,toto,tutu,tata 97 | 98 | # Colon-delimited sets of names that determine each other's naming style when 99 | # the name regexes allow several styles. 100 | name-group= 101 | 102 | # Include a hint for the correct naming format with invalid-name 103 | include-naming-hint=yes 104 | 105 | # Regular expression matching correct method names 106 | method-rgx=[a-z_][a-z0-9_]{2,30}$ 107 | 108 | # Naming hint for method names 109 | method-name-hint=[a-z_][a-z0-9_]{2,30}$ 110 | 111 | # Regular expression matching correct function names 112 | function-rgx=[a-z_][a-z0-9_]{2,30}$ 113 | 114 | # Naming hint for function names 115 | function-name-hint=[a-z_][a-z0-9_]{2,30}$ 116 | 117 | # Regular expression matching correct module names 118 | module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ 119 | 120 | # Naming hint for module names 121 | module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ 122 | 123 | # Regular expression matching correct attribute names 124 | attr-rgx=[a-z_][a-z0-9_]{2,30}$ 125 | 126 | # Naming hint for attribute names 127 | attr-name-hint=[a-z_][a-z0-9_]{2,30}$ 128 | 129 | # Regular expression matching correct class attribute names 130 | class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ 131 | 132 | # Naming hint for class attribute names 133 | class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ 134 | 135 | # Regular expression matching correct constant names 136 | const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ 137 | 138 | # Naming hint for constant names 139 | const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ 140 | 141 | # Regular expression matching correct class names 142 | class-rgx=[A-Z_][a-zA-Z0-9]+$ 143 | 144 | # Naming hint for class names 145 | class-name-hint=[A-Z_][a-zA-Z0-9]+$ 146 | 147 | # Regular expression matching correct argument names 148 | argument-rgx=[a-z_][a-z0-9_]{2,30}$ 149 | 150 | # Naming hint for argument names 151 | argument-name-hint=[a-z_][a-z0-9_]{2,30}$ 152 | 153 | # Regular expression matching correct inline iteration names 154 | inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ 155 | 156 | # Naming hint for inline iteration names 157 | inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ 158 | 159 | # Regular expression matching correct variable names 160 | variable-rgx=[a-z_][a-z0-9_]{2,30}$ 161 | 162 | # Naming hint for variable names 163 | variable-name-hint=[a-z_][a-z0-9_]{2,30}$ 164 | 165 | # Regular expression which should only match function or class names that do 166 | # not require a docstring. 167 | no-docstring-rgx=^_ 168 | 169 | # Minimum line length for functions/classes that require docstrings, shorter 170 | # ones are exempt. 171 | docstring-min-length=-1 172 | 173 | 174 | [ELIF] 175 | 176 | # Maximum number of nested blocks for function / method body 177 | max-nested-blocks=5 178 | 179 | 180 | [FORMAT] 181 | 182 | # Maximum number of characters on a single line. 183 | max-line-length=100 184 | 185 | # Regexp for a line that is allowed to be longer than the limit. 186 | ignore-long-lines=^\s*(# )??$ 187 | 188 | # Allow the body of an if to be on the same line as the test if there is no 189 | # else. 190 | single-line-if-stmt=no 191 | 192 | # List of optional constructs for which whitespace checking is disabled. `dict- 193 | # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. 194 | # `trailing-comma` allows a space between comma and closing bracket: (a, ). 195 | # `empty-line` allows space-only lines. 196 | no-space-check=trailing-comma,dict-separator 197 | 198 | # Maximum number of lines in a module 199 | max-module-lines=1000 200 | 201 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 202 | # tab). 203 | indent-string=' ' 204 | 205 | # Number of spaces of indent required inside a hanging or continued line. 206 | indent-after-paren=4 207 | 208 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 209 | expected-line-ending-format= 210 | 211 | 212 | [LOGGING] 213 | 214 | # Logging modules to check that the string format arguments are in logging 215 | # function parameter format 216 | logging-modules=logging 217 | 218 | 219 | [MISCELLANEOUS] 220 | 221 | # List of note tags to take in consideration, separated by a comma. 222 | notes=FIXME,XXX,TODO 223 | 224 | 225 | [SIMILARITIES] 226 | 227 | # Minimum lines number of a similarity. 228 | min-similarity-lines=4 229 | 230 | # Ignore comments when computing similarities. 231 | ignore-comments=yes 232 | 233 | # Ignore docstrings when computing similarities. 234 | ignore-docstrings=yes 235 | 236 | # Ignore imports when computing similarities. 237 | ignore-imports=no 238 | 239 | 240 | [SPELLING] 241 | 242 | # Spelling dictionary name. Available dictionaries: none. To make it working 243 | # install python-enchant package. 244 | spelling-dict= 245 | 246 | # List of comma separated words that should not be checked. 247 | spelling-ignore-words= 248 | 249 | # A path to a file that contains private dictionary; one word per line. 250 | spelling-private-dict-file= 251 | 252 | # Tells whether to store unknown words to indicated private dictionary in 253 | # --spelling-private-dict-file option instead of raising a message. 254 | spelling-store-unknown-words=no 255 | 256 | 257 | [TYPECHECK] 258 | 259 | # Tells whether missing members accessed in mixin class should be ignored. A 260 | # mixin class is detected if its name ends with "mixin" (case insensitive). 261 | ignore-mixin-members=yes 262 | 263 | # List of module names for which member attributes should not be checked 264 | # (useful for modules/projects where namespaces are manipulated during runtime 265 | # and thus existing member attributes cannot be deduced by static analysis. It 266 | # supports qualified module names, as well as Unix pattern matching. 267 | ignored-modules= 268 | 269 | # List of classes names for which member attributes should not be checked 270 | # (useful for classes with attributes dynamically set). This supports can work 271 | # with qualified names. 272 | ignored-classes= 273 | 274 | # List of members which are set dynamically and missed by pylint inference 275 | # system, and so shouldn't trigger E1101 when accessed. Python regular 276 | # expressions are accepted. 277 | generated-members= 278 | 279 | 280 | [VARIABLES] 281 | 282 | # Tells whether we should check for unused import in __init__ files. 283 | init-import=no 284 | 285 | # A regular expression matching the name of dummy variables (i.e. expectedly 286 | # not used). 287 | dummy-variables-rgx=_$|dummy 288 | 289 | # List of additional names supposed to be defined in builtins. Remember that 290 | # you should avoid to define new builtins when possible. 291 | additional-builtins= 292 | 293 | # List of strings which can identify a callback function by name. A callback 294 | # name must start or end with one of those strings. 295 | callbacks=cb_,_cb 296 | 297 | 298 | [CLASSES] 299 | 300 | # List of method names used to declare (i.e. assign) instance attributes. 301 | defining-attr-methods=__init__,__new__,setUp 302 | 303 | # List of valid names for the first argument in a class method. 304 | valid-classmethod-first-arg=cls 305 | 306 | # List of valid names for the first argument in a metaclass class method. 307 | valid-metaclass-classmethod-first-arg=mcs 308 | 309 | # List of member names, which should be excluded from the protected access 310 | # warning. 311 | exclude-protected=_asdict,_fields,_replace,_source,_make 312 | 313 | 314 | [DESIGN] 315 | 316 | # Maximum number of arguments for function / method 317 | max-args=5 318 | 319 | # Argument names that match this expression will be ignored. Default to name 320 | # with leading underscore 321 | ignored-argument-names=_.* 322 | 323 | # Maximum number of locals for function / method body 324 | max-locals=15 325 | 326 | # Maximum number of return / yield for function / method body 327 | max-returns=6 328 | 329 | # Maximum number of branch for function / method body 330 | max-branches=12 331 | 332 | # Maximum number of statements in function / method body 333 | max-statements=50 334 | 335 | # Maximum number of parents for a class (see R0901). 336 | max-parents=7 337 | 338 | # Maximum number of attributes for a class (see R0902). 339 | max-attributes=7 340 | 341 | # Minimum number of public methods for a class (see R0903). 342 | min-public-methods=2 343 | 344 | # Maximum number of public methods for a class (see R0904). 345 | max-public-methods=20 346 | 347 | # Maximum number of boolean expressions in a if statement 348 | max-bool-expr=5 349 | 350 | 351 | [IMPORTS] 352 | 353 | # Deprecated modules which should not be used, separated by a comma 354 | deprecated-modules=optparse 355 | 356 | # Create a graph of every (i.e. internal and external) dependencies in the 357 | # given file (report RP0402 must not be disabled) 358 | import-graph= 359 | 360 | # Create a graph of external dependencies in the given file (report RP0402 must 361 | # not be disabled) 362 | ext-import-graph= 363 | 364 | # Create a graph of internal dependencies in the given file (report RP0402 must 365 | # not be disabled) 366 | int-import-graph= 367 | 368 | 369 | [EXCEPTIONS] 370 | 371 | # Exceptions that will emit a warning when being caught. Defaults to 372 | # "Exception" 373 | overgeneral-exceptions=Exception 374 | -------------------------------------------------------------------------------- /.readthedocs.yml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yml 2 | # Read the Docs configuration file 3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 4 | 5 | # Required 6 | version: 2 7 | 8 | # Build documentation in the docs/ directory with Sphinx 9 | sphinx: 10 | builder: html 11 | configuration: docs/conf.py 12 | 13 | # Optionally build your docs in additional formats such as PDF and ePub 14 | formats: all 15 | 16 | # Optionally set the version of Python and requirements required to build your docs 17 | python: 18 | version: 3.7 19 | install: 20 | - requirements: requirements.txt 21 | - requirements: requirements-dev.txt 22 | - method: pip 23 | path: . 24 | - method: setuptools 25 | path: . 26 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at mail@eigenfoo.xyz. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guide 2 | 3 | ![Python versions](https://img.shields.io/badge/python-3.6%7C3.7-blue) 4 | ![Code style](https://img.shields.io/badge/style-black-black) 5 | ![GitHub issues](https://img.shields.io/github/issues/eigenfoo/littlemcmc) 6 | ![GitHub pull requests](https://img.shields.io/github/issues-pr/eigenfoo/littlemcmc) 7 | 8 | > This guide was derived from the [PyMC3 contributing 9 | > guide](https://github.com/pymc-devs/pymc3/blob/master/CONTRIBUTING.md). 10 | 11 | As a scientific community-driven software project, LittleMCMC welcomes 12 | contributions from interested individuals or groups. These guidelines are 13 | provided to give potential contributors information to make their contribution 14 | compliant with the conventions of the LittleMCMC project, and maximize the 15 | probability of such contributions to be merged as quickly and efficiently as 16 | possible. 17 | 18 | There are 4 main ways of contributing to the LittleMCMC project (in descending 19 | order of difficulty or scope): 20 | 21 | * Adding new or improved functionality to the existing codebase 22 | * Fixing outstanding issues (bugs) with the existing codebase. They range from 23 | low-level software bugs to higher-level design problems. 24 | * Contributing or improving the documentation (`docs`) 25 | * Submitting issues related to bugs or desired enhancements 26 | 27 | ## Opening issues 28 | 29 | We appreciate being notified of problems with the existing LittleMCMC code. We 30 | prefer that issues be filed on the [GitHub issue 31 | tracker](https://github.com/eigenfoo/littlemcmc/issues), rather than on social 32 | media or by direct email to the developers. 33 | 34 | Please verify that your issue is not being currently addressed by other issues 35 | or pull requests by using the GitHub search tool to look for key words in the 36 | project issue tracker. 37 | 38 | ## Contributing code via pull requests 39 | 40 | While issue reporting is valuable, we strongly encourage users who are inclined 41 | to do so to submit patches for new or existing issues via pull requests. This is 42 | particularly the case for simple fixes, such as typos or tweaks to 43 | documentation, which do not require a heavy investment of time and attention. 44 | 45 | Contributors are also encouraged to contribute new code to enhance LittleMCMC's 46 | functionality, also via pull requests. Please consult the [LittleMCMC 47 | documentation](https://littlemcmc.readthedocs.io) to ensure that any new 48 | contribution does not strongly overlap with existing functionality. 49 | 50 | The preferred workflow for contributing to LittleMCMC is to fork the [GitHub 51 | repository](https://github.com/eigenfoo/littlemcmc/), clone it to your local 52 | machine, and develop on a feature branch. 53 | 54 | ### Steps 55 | 56 | 1. Fork the [project repository](https://github.com/eigenfoo/littlemcmc/) by 57 | clicking on the 'Fork' button near the top right of the main repository page. 58 | This creates a copy of the code under your GitHub user account. 59 | 60 | 2. Clone your fork of the LittleMCMC repo from your GitHub account to your local 61 | disk, and add the base repository as a remote: 62 | 63 | ```bash 64 | $ git clone git@github.com:/littlemcmc.git 65 | $ cd littlemcmc 66 | $ git remote add upstream git@github.com:eigenfoo/littlemcmc.git 67 | ``` 68 | 69 | 3. Create a ``feature`` branch to hold your development changes: 70 | 71 | ```bash 72 | $ git checkout -b my-feature 73 | ``` 74 | 75 | Always use a ``feature`` branch. It's good practice to never routinely work 76 | on the ``master`` branch of any repository. 77 | 78 | 4. To set up a Python virtual environment for development, you may run: 79 | 80 | ```bash 81 | $ make venv 82 | ``` 83 | 84 | Alternatively, you may create a conda environment for development by running: 85 | 86 | ```bash 87 | $ make conda 88 | ``` 89 | 90 | 5. Develop the feature on your feature branch. Add changed files using ``git 91 | add`` and then ``git commit`` files: 92 | 93 | ```bash 94 | $ git add modified_files 95 | $ git commit 96 | ``` 97 | 98 | to record your changes locally. After committing, it is a good idea to sync 99 | with the base repository in case there have been any changes: 100 | 101 | ```bash 102 | $ git fetch upstream 103 | $ git rebase upstream/master 104 | ``` 105 | 106 | Then push the changes to your GitHub account with: 107 | 108 | ```bash 109 | $ git push -u origin my-feature 110 | ``` 111 | 112 | 6. Go to the GitHub web page of your fork of the LittleMCMC repo. Click the 113 | 'Pull request' button to send your changes to the project's maintainers for 114 | review. This will notify the developers. 115 | 116 | ### Pull request checklist 117 | 118 | We recommended that your contribution complies with the following guidelines 119 | before you submit a pull request: 120 | 121 | * If your pull request addresses an issue, please use the pull request title to 122 | describe the issue and mention the issue number in the pull request 123 | description. This will make sure a link back to the original issue is created. 124 | 125 | * All public methods must have informative docstrings with sample usage when 126 | appropriate. 127 | 128 | * Please prefix the title of incomplete contributions with `[WIP]` (to indicate 129 | a work in progress). WIPs may be useful to 130 | 1. indicate you are working on something to avoid duplicated work, 131 | 1. request broad review of functionality or API, or 132 | 1. seek collaborators. 133 | 134 | * Documentation and high-coverage tests are necessary for enhancements to be 135 | accepted. 136 | 137 | * Run any of the pre-existing examples in ``docs/_static/notebooks`` that 138 | contain analyses that would be affected by your changes to ensure that nothing 139 | breaks. This is a useful opportunity to not only check your work for bugs that 140 | might not be revealed by unit test, but also to show how your contribution 141 | improves LittleMCMC for end users. 142 | 143 | You can check for common programming errors or stylistic issues with the 144 | following Make rule: 145 | 146 | ```bash 147 | $ make lint 148 | ``` 149 | 150 | You can also run the test suite with the following Make rule: 151 | 152 | ```bash 153 | $ make test 154 | ``` 155 | 156 | ## Code of Conduct 157 | 158 | LittleMCMC abides by the [Contributor Covenant Code of Conduct, version 159 | 1.4](https://github.com/eigenfoo/littlemcmc/blob/master/CODE_OF_CONDUCT.md). 160 | -------------------------------------------------------------------------------- /LICENSE.pymc3.txt: -------------------------------------------------------------------------------- 1 | ======= 2 | License 3 | ======= 4 | 5 | PyMC is distributed under the Apache License, Version 2.0 6 | 7 | Copyright (c) 2006 Christopher J. Fonnesbeck (Academic Free License) 8 | Copyright (c) 2007-2008 Christopher J. Fonnesbeck, Anand Prabhakar Patil, David Huard (Academic Free License) 9 | Copyright (c) 2009-2017 The PyMC developers (see contributors to pymc-devs on GitHub) 10 | All rights reserved. 11 | 12 | Apache License 13 | Version 2.0, January 2004 14 | http://www.apache.org/licenses/ 15 | 16 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 17 | 18 | 1. Definitions. 19 | 20 | "License" shall mean the terms and conditions for use, reproduction, 21 | and distribution as defined by Sections 1 through 9 of this document. 22 | 23 | "Licensor" shall mean the copyright owner or entity authorized by 24 | the copyright owner that is granting the License. 25 | 26 | "Legal Entity" shall mean the union of the acting entity and all 27 | other entities that control, are controlled by, or are under common 28 | control with that entity. For the purposes of this definition, 29 | "control" means (i) the power, direct or indirect, to cause the 30 | direction or management of such entity, whether by contract or 31 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 32 | outstanding shares, or (iii) beneficial ownership of such entity. 33 | 34 | "You" (or "Your") shall mean an individual or Legal Entity 35 | exercising permissions granted by this License. 36 | 37 | "Source" form shall mean the preferred form for making modifications, 38 | including but not limited to software source code, documentation 39 | source, and configuration files. 40 | 41 | "Object" form shall mean any form resulting from mechanical 42 | transformation or translation of a Source form, including but 43 | not limited to compiled object code, generated documentation, 44 | and conversions to other media types. 45 | 46 | "Work" shall mean the work of authorship, whether in Source or 47 | Object form, made available under the License, as indicated by a 48 | copyright notice that is included in or attached to the work 49 | (an example is provided in the Appendix below). 50 | 51 | "Derivative Works" shall mean any work, whether in Source or Object 52 | form, that is based on (or derived from) the Work and for which the 53 | editorial revisions, annotations, elaborations, or other modifications 54 | represent, as a whole, an original work of authorship. For the purposes 55 | of this License, Derivative Works shall not include works that remain 56 | separable from, or merely link (or bind by name) to the interfaces of, 57 | the Work and Derivative Works thereof. 58 | 59 | "Contribution" shall mean any work of authorship, including 60 | the original version of the Work and any modifications or additions 61 | to that Work or Derivative Works thereof, that is intentionally 62 | submitted to Licensor for inclusion in the Work by the copyright owner 63 | or by an individual or Legal Entity authorized to submit on behalf of 64 | the copyright owner. For the purposes of this definition, "submitted" 65 | means any form of electronic, verbal, or written communication sent 66 | to the Licensor or its representatives, including but not limited to 67 | communication on electronic mailing lists, source code control systems, 68 | and issue tracking systems that are managed by, or on behalf of, the 69 | Licensor for the purpose of discussing and improving the Work, but 70 | excluding communication that is conspicuously marked or otherwise 71 | designated in writing by the copyright owner as "Not a Contribution." 72 | 73 | "Contributor" shall mean Licensor and any individual or Legal Entity 74 | on behalf of whom a Contribution has been received by Licensor and 75 | subsequently incorporated within the Work. 76 | 77 | 2. Grant of Copyright License. Subject to the terms and conditions of 78 | this License, each Contributor hereby grants to You a perpetual, 79 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 80 | copyright license to reproduce, prepare Derivative Works of, 81 | publicly display, publicly perform, sublicense, and distribute the 82 | Work and such Derivative Works in Source or Object form. 83 | 84 | 3. Grant of Patent License. Subject to the terms and conditions of 85 | this License, each Contributor hereby grants to You a perpetual, 86 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 87 | (except as stated in this section) patent license to make, have made, 88 | use, offer to sell, sell, import, and otherwise transfer the Work, 89 | where such license applies only to those patent claims licensable 90 | by such Contributor that are necessarily infringed by their 91 | Contribution(s) alone or by combination of their Contribution(s) 92 | with the Work to which such Contribution(s) was submitted. If You 93 | institute patent litigation against any entity (including a 94 | cross-claim or counterclaim in a lawsuit) alleging that the Work 95 | or a Contribution incorporated within the Work constitutes direct 96 | or contributory patent infringement, then any patent licenses 97 | granted to You under this License for that Work shall terminate 98 | as of the date such litigation is filed. 99 | 100 | 4. Redistribution. You may reproduce and distribute copies of the 101 | Work or Derivative Works thereof in any medium, with or without 102 | modifications, and in Source or Object form, provided that You 103 | meet the following conditions: 104 | 105 | (a) You must give any other recipients of the Work or 106 | Derivative Works a copy of this License; and 107 | 108 | (b) You must cause any modified files to carry prominent notices 109 | stating that You changed the files; and 110 | 111 | (c) You must retain, in the Source form of any Derivative Works 112 | that You distribute, all copyright, patent, trademark, and 113 | attribution notices from the Source form of the Work, 114 | excluding those notices that do not pertain to any part of 115 | the Derivative Works; and 116 | 117 | (d) If the Work includes a "NOTICE" text file as part of its 118 | distribution, then any Derivative Works that You distribute must 119 | include a readable copy of the attribution notices contained 120 | within such NOTICE file, excluding those notices that do not 121 | pertain to any part of the Derivative Works, in at least one 122 | of the following places: within a NOTICE text file distributed 123 | as part of the Derivative Works; within the Source form or 124 | documentation, if provided along with the Derivative Works; or, 125 | within a display generated by the Derivative Works, if and 126 | wherever such third-party notices normally appear. The contents 127 | of the NOTICE file are for informational purposes only and 128 | do not modify the License. You may add Your own attribution 129 | notices within Derivative Works that You distribute, alongside 130 | or as an addendum to the NOTICE text from the Work, provided 131 | that such additional attribution notices cannot be construed 132 | as modifying the License. 133 | 134 | You may add Your own copyright statement to Your modifications and 135 | may provide additional or different license terms and conditions 136 | for use, reproduction, or distribution of Your modifications, or 137 | for any such Derivative Works as a whole, provided Your use, 138 | reproduction, and distribution of the Work otherwise complies with 139 | the conditions stated in this License. 140 | 141 | 5. Submission of Contributions. Unless You explicitly state otherwise, 142 | any Contribution intentionally submitted for inclusion in the Work 143 | by You to the Licensor shall be under the terms and conditions of 144 | this License, without any additional terms or conditions. 145 | Notwithstanding the above, nothing herein shall supersede or modify 146 | the terms of any separate license agreement you may have executed 147 | with Licensor regarding such Contributions. 148 | 149 | 6. Trademarks. This License does not grant permission to use the trade 150 | names, trademarks, service marks, or product names of the Licensor, 151 | except as required for reasonable and customary use in describing the 152 | origin of the Work and reproducing the content of the NOTICE file. 153 | 154 | 7. Disclaimer of Warranty. Unless required by applicable law or 155 | agreed to in writing, Licensor provides the Work (and each 156 | Contributor provides its Contributions) on an "AS IS" BASIS, 157 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 158 | implied, including, without limitation, any warranties or conditions 159 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 160 | PARTICULAR PURPOSE. You are solely responsible for determining the 161 | appropriateness of using or redistributing the Work and assume any 162 | risks associated with Your exercise of permissions under this License. 163 | 164 | 8. Limitation of Liability. In no event and under no legal theory, 165 | whether in tort (including negligence), contract, or otherwise, 166 | unless required by applicable law (such as deliberate and grossly 167 | negligent acts) or agreed to in writing, shall any Contributor be 168 | liable to You for damages, including any direct, indirect, special, 169 | incidental, or consequential damages of any character arising as a 170 | result of this License or out of the use or inability to use the 171 | Work (including but not limited to damages for loss of goodwill, 172 | work stoppage, computer failure or malfunction, or any and all 173 | other commercial damages or losses), even if such Contributor 174 | has been advised of the possibility of such damages. 175 | 176 | 9. Accepting Warranty or Additional Liability. While redistributing 177 | the Work or Derivative Works thereof, You may choose to offer, 178 | and charge a fee for, acceptance of support, warranty, indemnity, 179 | or other liability obligations and/or rights consistent with this 180 | License. However, in accepting such obligations, You may act only 181 | on Your own behalf and on Your sole responsibility, not on behalf 182 | of any other Contributor, and only if You agree to indemnify, 183 | defend, and hold each Contributor harmless for any liability 184 | incurred by, or claims asserted against, such Contributor by reason 185 | of your accepting any such warranty or additional liability. 186 | 187 | END OF TERMS AND CONDITIONS 188 | 189 | APPENDIX: How to apply the Apache License to your work. 190 | 191 | To apply the Apache License to your work, attach the following 192 | boilerplate notice, with the fields enclosed by brackets "[]" 193 | replaced with your own identifying information. (Don't include 194 | the brackets!) The text should be enclosed in the appropriate 195 | comment syntax for the file format. We also recommend that a 196 | file or class name and description of purpose be included on the 197 | same "printed page" as the copyright notice for easier 198 | identification within third-party archives. 199 | 200 | Copyright [yyyy] [name of copyright owner] 201 | 202 | Licensed under the Apache License, Version 2.0 (the "License"); 203 | you may not use this file except in compliance with the License. 204 | You may obtain a copy of the License at 205 | 206 | http://www.apache.org/licenses/LICENSE-2.0 207 | 208 | Unless required by applicable law or agreed to in writing, software 209 | distributed under the License is distributed on an "AS IS" BASIS, 210 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 211 | See the License for the specific language governing permissions and 212 | limitations under the License. 213 | -------------------------------------------------------------------------------- /LICENSE.pymc4.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include docs * 2 | include *.md 3 | include requirements.txt 4 | include LICENSE.txt 5 | include LICENSE.pymc3.txt 6 | include LICENSE.pymc4.txt 7 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .DEFAULT_GOAL = help 2 | 3 | PYTHON := python3 4 | PIP := pip3 5 | CONDA := conda 6 | SHELL := bash 7 | 8 | .ONESHELL: 9 | .SHELLFLAGS := -eu -o pipefail -c 10 | .DELETE_ON_ERROR: 11 | MAKEFLAGS += --no-builtin-rules 12 | 13 | .PHONY: help 14 | help: 15 | @printf "Usage:\n" 16 | @grep -E '^[a-zA-Z_-]+:.*?# .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?# "}; {printf "\033[1;34mmake %-10s\033[0m%s\n", $$1, $$2}' 17 | 18 | .PHONY: conda 19 | conda: # Set up a conda environment for development. 20 | @printf "Creating conda environment...\n" 21 | ${CONDA} create --yes --name env-littlemcmc python=3.6 22 | ${CONDA} activate env-littlemcmc 23 | ${PIP} install -U pip 24 | ${PIP} install -r requirements.txt 25 | ${PIP} install -r requirements-dev.txt 26 | ${CONDA} deactivate 27 | @printf "\n\nConda environment created! \033[1;34mRun \`conda activate env-littlemcmc\` to activate it.\033[0m\n\n\n" 28 | 29 | .PHONY: venv 30 | venv: # Set up a Python virtual environment for development. 31 | @printf "Creating Python virtual environment...\n" 32 | rm -rf venv/ 33 | ${PYTHON} -m venv venv/ 34 | source venv/bin/activate 35 | ${PIP} install -U pip 36 | ${PIP} install -r requirements.txt 37 | ${PIP} install -r requirements-dev.txt 38 | ${PIP} install -e . 39 | deactivate 40 | @printf "\n\nVirtual environment created! \033[1;34mRun \`source venv/bin/activate\` to activate it.\033[0m\n\n\n" 41 | 42 | .PHONY: blackstyle 43 | blackstyle: 44 | @printf "Checking code style with black...\n" 45 | black --check --diff littlemcmc/ tests/ docs/ 46 | @printf "\033[1;34mBlack passes!\033[0m\n\n" 47 | 48 | .PHONY: pylintstyle 49 | pylintstyle: 50 | @printf "Checking code style with pylint...\n" 51 | pylint littlemcmc/ tests/ 52 | @printf "\033[1;34mPylint passes!\033[0m\n\n" 53 | 54 | .PHONY: pydocstyle 55 | pydocstyle: 56 | @printf "Checking documentation with pydocstyle...\n" 57 | pydocstyle --convention=numpy --match='(?!parallel_sampling).*\.py' littlemcmc/ 58 | @printf "\033[1;34mPydocstyle passes!\033[0m\n\n" 59 | 60 | .PHONY: mypytypes 61 | mypytypes: 62 | @printf "Checking code type signatures with mypy...\n" 63 | python -m mypy --ignore-missing-imports littlemcmc/ 64 | @printf "\033[1;34mMypy passes!\033[0m\n\n" 65 | 66 | .PHONY: black 67 | black: # Format code in-place using black. 68 | black littlemcmc/ tests/ docs/ 69 | 70 | .PHONY: test 71 | test: # Test code using pytest. 72 | pytest -v littlemcmc tests --doctest-modules --html=testing-report.html --self-contained-html --cov=./ --cov-report=xml 73 | 74 | .PHONY: lint 75 | lint: blackstyle pylintstyle pydocstyle mypytypes # Lint code using black, pylint, pydocstyle and mypy. 76 | 77 | .PHONY: check 78 | check: lint test # Both lint and test code. Runs `make lint` followed by `make test`. 79 | 80 | .PHONY: clean 81 | clean: # Clean project directories. 82 | rm -rf dist/ site/ littlemcmc.egg-info/ pip-wheel-metadata/ __pycache__/ testing-report.html coverage.xml 83 | find littlemcmc/ tests/ -type d -name "__pycache__" -exec rm -rf {} + 84 | find littlemcmc/ tests/ -type d -name "__pycache__" -delete 85 | find littlemcmc/ tests/ -type f -name "*.pyc" -delete 86 | ${MAKE} -C docs/ clean 87 | 88 | .PHONY: package 89 | package: clean # Package littlemcmc in preparation for releasing to PyPI. 90 | ${PYTHON} setup.py sdist bdist_wheel 91 | twine check dist/* 92 | @printf "\n\n\033[1;34mTo upload to Test PyPI (recommended!), run:\033[0m\n\n" 93 | @printf "\t\033[1;34mpython3 -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*\033[0m\n\n" 94 | @printf "\033[1;34mTo upload to PyPI, run:\033[0m\n\n" 95 | @printf "\t\033[1;34mpython3 -m twine upload dist/*\033[0m\n\n" 96 | @printf "\033[1;34mYou will need PyPI credentials.\033[0m\n\n" 97 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 | > *Warning:* `littlemcmc`'s behavior is unstable in Jupyter notebooks - for best 4 | > results and support, please use `littlemcmc` in Python scripts. Furthermore, 5 | > despite best efforts, `littlemcmc` is not guaranteed to be up-to-date with the 6 | > [current PyMC3 HMC/NUTS 7 | > samplers](https://github.com/pymc-devs/pymc3/tree/master/pymc3/step_methods/hmc) - 8 | > please consult [our GitHub 9 | > issues](https://github.com/eigenfoo/littlemcmc/issues). 10 | 11 | --- 12 | 13 | ![Tests Status](https://github.com/eigenfoo/littlemcmc/workflows/tests/badge.svg) 14 | ![Lint Status](https://github.com/eigenfoo/littlemcmc/workflows/lint/badge.svg) 15 | ![Up to date with PyMC3 Status](https://github.com/eigenfoo/littlemcmc/workflows/even-with-pymc3/badge.svg) 16 | [![Coverage Status](https://codecov.io/gh/eigenfoo/littlemcmc/branch/master/graph/badge.svg)](https://codecov.io/gh/eigenfoo/littlemcmc) 17 | [![Documentation Status](https://readthedocs.org/projects/littlemcmc/badge/?version=latest)](https://littlemcmc.readthedocs.io/en/latest/?badge=latest) 18 | [![License](https://img.shields.io/github/license/eigenfoo/littlemcmc)](https://github.com/eigenfoo/littlemcmc/blob/master/LICENSE.littlemcmc.txt) 19 | [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.4710368.svg)](https://doi.org/10.5281/zenodo.4710368) 20 | 21 | > littlemcmc     /lɪtəl ɛm si ɛm si/     _noun_ 22 | > 23 | > A lightweight and performant implementation of HMC and NUTS in Python, spun 24 | > out of [the PyMC project](https://github.com/pymc-devs). Not to be confused 25 | > with [minimc](https://github.com/ColCarroll/minimc). 26 | 27 | ## Installation 28 | 29 | The latest release of LittleMCMC can be installed from PyPI using `pip`: 30 | 31 | ```bash 32 | pip install littlemcmc 33 | ``` 34 | 35 | The current development branch of LittleMCMC can be installed directly from 36 | GitHub, also using `pip`: 37 | 38 | ```bash 39 | pip install git+https://github.com/eigenfoo/littlemcmc.git 40 | ``` 41 | 42 | ## Contributors 43 | 44 | LittleMCMC is developed by [George Ho](https://eigenfoo.xyz/). For a full list 45 | of contributors, please see the [GitHub contributor 46 | graph](https://github.com/eigenfoo/littlemcmc/graphs/contributors). 47 | 48 | ## License 49 | 50 | LittleMCMC is modified from [the PyMC3 and PyMC4 51 | projects](https://github.com/pymc-devs/), both of which are distributed under 52 | the Apache-2.0 license. A copy of both projects' license files are distributed 53 | with LittleMCMC. All modifications from PyMC are distributed under [an identical 54 | Apache-2.0 license](https://github.com/eigenfoo/littlemcmc/blob/master/LICENSE). 55 | 56 | ## Citation 57 | 58 | Please cite using the [Zenodo DOI](https://doi.org/10.5281/zenodo.4710367). 59 | -------------------------------------------------------------------------------- /docs/.gitignore: -------------------------------------------------------------------------------- 1 | _build/ 2 | generated/ 3 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | .PHONY: help 13 | help: 14 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 15 | 16 | tutorials/%.rst: _static/notebooks/%.ipynb tutorials/tutorial_rst.tpl 17 | jupyter nbconvert --template tutorials/tutorial_rst --to rst --output-dir tutorials $< 18 | 19 | # Catch-all target: route all unknown targets to Sphinx using the new 20 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 21 | # Do not use a catch-all target, so we can include custom make rules. 22 | # .PHONY: Makefile 23 | # %: Makefile 24 | # @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 25 | 26 | .PHONY: Makefile 27 | html: Makefile 28 | @$(SPHINXBUILD) -M html "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 29 | 30 | clean: Makefile 31 | @$(SPHINXBUILD) -M clean "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 32 | -------------------------------------------------------------------------------- /docs/_static/logo/README.md: -------------------------------------------------------------------------------- 1 | # LittleMCMC Logo 2 | 3 | The LittleMCMC logo was made with the [Namecheap Logo 4 | Maker](https://www.namecheap.com/logo-maker/). 5 | 6 | --- 7 | 8 | ``` 9 | Hope you enjoy your new logo, here are the people that made your beautiful logo 10 | happen :) 11 | 12 | font name: Barlow-Black 13 | font link: https://fonts.google.com/specimen/Barlow 14 | font author: Jeremy Tribby 15 | font author site: https://tribby.com/ 16 | 17 | icon designer: Leszek Pietrzak 18 | icon designer link: https://thenounproject.com/magicznyleszek/ 19 | 20 | {"bg":"#156EAC","icon":"#F6575E","font":"#ffffff","slogan":"#ffffff"} 21 | ``` 22 | -------------------------------------------------------------------------------- /docs/_static/logo/cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eigenfoo/littlemcmc/2b5dd87972ce13b6d2898ced9b748cc9ce2643b6/docs/_static/logo/cover.png -------------------------------------------------------------------------------- /docs/_static/logo/default-cropped.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eigenfoo/littlemcmc/2b5dd87972ce13b6d2898ced9b748cc9ce2643b6/docs/_static/logo/default-cropped.png -------------------------------------------------------------------------------- /docs/_static/logo/default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eigenfoo/littlemcmc/2b5dd87972ce13b6d2898ced9b748cc9ce2643b6/docs/_static/logo/default.png -------------------------------------------------------------------------------- /docs/_static/logo/profile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eigenfoo/littlemcmc/2b5dd87972ce13b6d2898ced9b748cc9ce2643b6/docs/_static/logo/profile.png -------------------------------------------------------------------------------- /docs/_static/logo/vector/default-monochrome-black.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/_static/logo/vector/default-monochrome-white.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/_static/logo/vector/default-monochrome.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/_static/logo/vector/default.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/_static/logo/vector/isolated-layout.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/_static/logo/vector/isolated-monochrome-black.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/_static/logo/vector/isolated-monochrome-white.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/_static/notebooks/quickstart.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# LittleMCMC Quickstart\n", 8 | "\n", 9 | "LittleMCMC is a lightweight and performant implementation of HMC and NUTS in Python, spun out of the PyMC project. In this quickstart tutorial, we will walk through the main use case of LittleMCMC, and outline the various modules that may be of interest.\n", 10 | "\n", 11 | "## Table of Contents\n", 12 | "\n", 13 | "- [Who should use LittleMCMC?](#who-should-use-littlemcmc)\n", 14 | "- [Sampling](#how-to-sample)\n", 15 | " - [Inspecting the Output of lmc.sample](#inspecting-the-output-of-lmc-sample)\n", 16 | "- [Customizing the Default NUTS Sampler](#customizing-the-default-nuts-sampler)\n", 17 | "- [Other Modules](#other-modules)\n", 18 | "\n", 19 | "## Who should use LittleMCMC?\n", 20 | "\n", 21 | "LittleMCMC is a fairly barebones library with a very niche use case. Most users will probably find that [PyMC3](https://github.com/pymc-devs/pymc3) will satisfy their needs, with better strength of support and quality of documentation.\n", 22 | "\n", 23 | "There are two expected use cases for LittleMCMC. Firstly, if you:\n", 24 | "\n", 25 | "1. Have a model with only continuous parameters,\n", 26 | "1. Are willing to manually transform all of your model's parameters to the unconstrained space (if necessary),\n", 27 | "1. Have a Python function/callable that:\n", 28 | " 1. computes the log probability of your model and its derivative\n", 29 | " 1. is [pickleable](https://docs.python.org/3/library/pickle.html)\n", 30 | " 1. outputs an array with the same shape as its input\n", 31 | "1. And all you need is an implementation of HMC/NUTS (preferably in Python) to sample from the posterior,\n", 32 | "\n", 33 | "then you should consider using LittleMCMC.\n", 34 | "\n", 35 | "Secondly, if you want to run algorithmic experiments on HMC/NUTS (in Python), without having to develop around the heavy machinery that accompanies other probabilistic programming frameworks (like [PyMC3](https://github.com/pymc-devs/pymc3/), [TensorFlow Probability](https://github.com/tensorflow/probability/) or [Stan](https://github.com/stan-dev/stan)), then you should consider running your experiments in LittleMCMC.\n", 36 | "\n", 37 | "## How to Sample" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 1, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "import numpy as np\n", 47 | "import scipy\n", 48 | "import littlemcmc as lmc" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": 2, 54 | "metadata": {}, 55 | "outputs": [], 56 | "source": [ 57 | "def logp_func(x, loc=0, scale=1):\n", 58 | " return np.log(scipy.stats.norm.pdf(x, loc=loc, scale=scale))\n", 59 | "\n", 60 | "\n", 61 | "def dlogp_func(x, loc=0, scale=1):\n", 62 | " return -(x - loc) / scale\n", 63 | "\n", 64 | "\n", 65 | "def logp_dlogp_func(x, loc=0, scale=1):\n", 66 | " return logp_func(x, loc=loc, scale=scale), dlogp_func(x, loc=loc, scale=scale)" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": 3, 72 | "metadata": {}, 73 | "outputs": [ 74 | { 75 | "name": "stderr", 76 | "output_type": "stream", 77 | "text": [ 78 | "/home/george/littlemcmc/venv/lib/python3.6/site-packages/ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in log\n", 79 | " \n" 80 | ] 81 | } 82 | ], 83 | "source": [ 84 | "# By default: 4 chains in 4 cores, 500 tuning steps and 1000 sampling steps.\n", 85 | "trace, stats = lmc.sample(\n", 86 | " logp_dlogp_func=logp_dlogp_func,\n", 87 | " model_ndim=1,\n", 88 | " progressbar=None, # HTML progress bars don't render well in RST.\n", 89 | ")" 90 | ] 91 | }, 92 | { 93 | "cell_type": "markdown", 94 | "metadata": {}, 95 | "source": [ 96 | "### Inspecting the Output of `lmc.sample`" 97 | ] 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": 4, 102 | "metadata": {}, 103 | "outputs": [ 104 | { 105 | "data": { 106 | "text/plain": [ 107 | "(4, 1000, 1)" 108 | ] 109 | }, 110 | "execution_count": 4, 111 | "metadata": {}, 112 | "output_type": "execute_result" 113 | } 114 | ], 115 | "source": [ 116 | "# Shape is (num_chains, num_samples, num_parameters)\n", 117 | "trace.shape" 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": 5, 123 | "metadata": {}, 124 | "outputs": [ 125 | { 126 | "data": { 127 | "text/plain": [ 128 | "array([[[ 0.92958231],\n", 129 | " [ 0.92958231]],\n", 130 | "\n", 131 | " [[-1.06231693],\n", 132 | " [-1.11589309]],\n", 133 | "\n", 134 | " [[-0.73177109],\n", 135 | " [-0.66975061]],\n", 136 | "\n", 137 | " [[ 0.8923907 ],\n", 138 | " [ 0.97253646]]])" 139 | ] 140 | }, 141 | "execution_count": 5, 142 | "metadata": {}, 143 | "output_type": "execute_result" 144 | } 145 | ], 146 | "source": [ 147 | "# The first 2 samples across all chains and parameters\n", 148 | "trace[:, :2, :]" 149 | ] 150 | }, 151 | { 152 | "cell_type": "code", 153 | "execution_count": 6, 154 | "metadata": {}, 155 | "outputs": [ 156 | { 157 | "data": { 158 | "text/plain": [ 159 | "dict_keys(['depth', 'step_size', 'tune', 'mean_tree_accept', 'step_size_bar', 'tree_size', 'diverging', 'energy_error', 'energy', 'max_energy_error', 'model_logp'])" 160 | ] 161 | }, 162 | "execution_count": 6, 163 | "metadata": {}, 164 | "output_type": "execute_result" 165 | } 166 | ], 167 | "source": [ 168 | "stats.keys()" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": 7, 174 | "metadata": {}, 175 | "outputs": [ 176 | { 177 | "data": { 178 | "text/plain": [ 179 | "(4, 1000, 1)" 180 | ] 181 | }, 182 | "execution_count": 7, 183 | "metadata": {}, 184 | "output_type": "execute_result" 185 | } 186 | ], 187 | "source": [ 188 | "# Again, shape is (num_chains, num_samples, num_parameters)\n", 189 | "stats[\"depth\"].shape" 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": 8, 195 | "metadata": {}, 196 | "outputs": [ 197 | { 198 | "data": { 199 | "text/plain": [ 200 | "array([[[2],\n", 201 | " [1]],\n", 202 | "\n", 203 | " [[1],\n", 204 | " [1]],\n", 205 | "\n", 206 | " [[2],\n", 207 | " [1]],\n", 208 | "\n", 209 | " [[2],\n", 210 | " [1]]])" 211 | ] 212 | }, 213 | "execution_count": 8, 214 | "metadata": {}, 215 | "output_type": "execute_result" 216 | } 217 | ], 218 | "source": [ 219 | "# The first 2 tree depths across all chains and parameters\n", 220 | "stats[\"depth\"][:, :2, :]" 221 | ] 222 | }, 223 | { 224 | "cell_type": "markdown", 225 | "metadata": {}, 226 | "source": [ 227 | "## Customizing the Default NUTS Sampler\n", 228 | "\n", 229 | "By default, `lmc.sample` samples using NUTS with sane defaults. These defaults can be override by either:\n", 230 | "\n", 231 | "1. Passing keyword arguments from `lmc.NUTS` into `lmc.sample`, or\n", 232 | "2. Constructing an `lmc.NUTS` sampler, and passing that to `lmc.sample`. This method also allows you to choose to other samplers, such as `lmc.HamiltonianMC`.\n", 233 | "\n", 234 | "For example, suppose you want to increase the `target_accept` from the default `0.8` to `0.9`. The following two cells are equivalent:" 235 | ] 236 | }, 237 | { 238 | "cell_type": "code", 239 | "execution_count": 9, 240 | "metadata": {}, 241 | "outputs": [], 242 | "source": [ 243 | "trace, stats = lmc.sample(\n", 244 | " logp_dlogp_func=logp_dlogp_func,\n", 245 | " model_ndim=1,\n", 246 | " target_accept=0.9,\n", 247 | " progressbar=None,\n", 248 | ")" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": 10, 254 | "metadata": {}, 255 | "outputs": [ 256 | { 257 | "name": "stderr", 258 | "output_type": "stream", 259 | "text": [ 260 | "/home/george/littlemcmc/venv/lib/python3.6/site-packages/ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in log\n", 261 | " \n" 262 | ] 263 | } 264 | ], 265 | "source": [ 266 | "step = lmc.NUTS(logp_dlogp_func=logp_dlogp_func, model_ndim=1, target_accept=0.9)\n", 267 | "trace, stats = lmc.sample(\n", 268 | " logp_dlogp_func=logp_dlogp_func,\n", 269 | " model_ndim=1,\n", 270 | " step=step,\n", 271 | " progressbar=None,\n", 272 | ")" 273 | ] 274 | }, 275 | { 276 | "cell_type": "markdown", 277 | "metadata": {}, 278 | "source": [ 279 | "For a list of keyword arguments that `lmc.NUTS` accepts, please refer to the [API reference for `lmc.NUTS`](https://littlemcmc.readthedocs.io/en/latest/generated/littlemcmc.NUTS.html#littlemcmc.NUTS).\n", 280 | "\n", 281 | "## Other Modules\n", 282 | "\n", 283 | "LittleMCMC exposes:\n", 284 | "\n", 285 | "1. Two step methods (a.k.a. samplers): [`littlemcmc.HamiltonianMC` (Hamiltonian Monte Carlo)](https://littlemcmc.readthedocs.io/en/latest/generated/littlemcmc.HamiltonianMC.html#littlemcmc.HamiltonianMC) and the [`littlemcmc.NUTS` (No-U-Turn Sampler)](https://littlemcmc.readthedocs.io/en/latest/generated/littlemcmc.NUTS.html#littlemcmc.NUTS)\n", 286 | "1. Various quadpotentials (a.k.a. mass matrices or inverse metrics) in [`littlemcmc.quadpotential`](https://littlemcmc.readthedocs.io/en/latest/api.html#quadpotentials-a-k-a-mass-matrices), along with mass matrix adaptation routines\n", 287 | "1. Dual-averaging step size adaptation in [`littlemcmc.step_sizes`](https://littlemcmc.readthedocs.io/en/latest/generated/littlemcmc.step_sizes.DualAverageAdaptation.html#littlemcmc.step_sizes.DualAverageAdaptation)\n", 288 | "1. A leapfrog integrator in [`littlemcmc.integration`](https://littlemcmc.readthedocs.io/en/latest/generated/littlemcmc.integration.CpuLeapfrogIntegrator.html#littlemcmc.integration.CpuLeapfrogIntegrator)\n", 289 | "\n", 290 | "These modules should allow for easy experimentation with the sampler. Please refer to the [API Reference](https://littlemcmc.readthedocs.io/en/latest/api.html) for more information." 291 | ] 292 | } 293 | ], 294 | "metadata": { 295 | "kernelspec": { 296 | "display_name": "Python 3", 297 | "language": "python", 298 | "name": "python3" 299 | }, 300 | "language_info": { 301 | "codemirror_mode": { 302 | "name": "ipython", 303 | "version": 3 304 | }, 305 | "file_extension": ".py", 306 | "mimetype": "text/x-python", 307 | "name": "python", 308 | "nbconvert_exporter": "python", 309 | "pygments_lexer": "ipython3", 310 | "version": "3.6.9" 311 | } 312 | }, 313 | "nbformat": 4, 314 | "nbformat_minor": 2 315 | } 316 | -------------------------------------------------------------------------------- /docs/_static/scripts/sample_jax_logp_dlogp_func.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from jax.config import config 3 | 4 | config.update("jax_enable_x64", True) 5 | 6 | import jax 7 | import jax.numpy as jnp 8 | import littlemcmc as lmc 9 | 10 | 11 | np.random.seed(42) 12 | 13 | true_params = np.array([0.5, -2.3, -0.23]) 14 | 15 | N = 50 16 | t = np.linspace(0, 10, 2) 17 | x = np.random.uniform(0, 10, 50) 18 | y = x * true_params[0] + true_params[1] 19 | y_obs = y + np.exp(true_params[-1]) * np.random.randn(N) 20 | 21 | 22 | def jax_model(params): 23 | mean = params[0] * x + params[1] 24 | loglike = -0.5 * jnp.sum((y_obs - mean) ** 2 * jnp.exp(-2 * params[2]) + 2 * params[2]) 25 | return loglike 26 | 27 | 28 | @jax.jit 29 | def jax_model_and_grad(x): 30 | return jax_model(x), jax.grad(jax_model)(x) 31 | 32 | 33 | def jax_logp_dlogp_func(x): 34 | v, g = jax_model_and_grad(x) 35 | return np.asarray(v), np.asarray(g) 36 | 37 | 38 | trace, stats = lmc.sample( 39 | logp_dlogp_func=jax_logp_dlogp_func, 40 | model_ndim=3, 41 | tune=500, 42 | draws=1000, 43 | chains=4, 44 | ) 45 | -------------------------------------------------------------------------------- /docs/_static/scripts/sample_pytorch_logp_dlogp_func.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import littlemcmc as lmc 3 | import numpy as np 4 | 5 | 6 | np.random.seed(42) 7 | 8 | true_params = np.array([0.5, -2.3, -0.23]) 9 | 10 | N = 50 11 | t = np.linspace(0, 10, 2) 12 | x = np.random.uniform(0, 10, 50) 13 | y = x * true_params[0] + true_params[1] 14 | y_obs = y + np.exp(true_params[-1]) * np.random.randn(N) 15 | 16 | 17 | class LinearModel(torch.nn.Module): 18 | def __init__(self): 19 | super(LinearModel, self).__init__() 20 | self.m = torch.nn.Parameter(torch.tensor(0.0, dtype=torch.float64)) 21 | self.b = torch.nn.Parameter(torch.tensor(0.0, dtype=torch.float64)) 22 | self.logs = torch.nn.Parameter(torch.tensor(0.0, dtype=torch.float64)) 23 | 24 | def forward(self, x, y): 25 | mean = self.m * x + self.b 26 | loglike = -0.5 * torch.sum((y - mean) ** 2 * torch.exp(-2 * self.logs) + 2 * self.logs) 27 | return loglike 28 | 29 | 30 | torch_model = torch.jit.script(LinearModel()) 31 | torch_params = [torch_model.m, torch_model.b, torch_model.logs] 32 | args = [torch.tensor(x, dtype=torch.double), torch.tensor(y_obs, dtype=torch.double)] 33 | 34 | 35 | def torch_logp_dlogp_func(x): 36 | for i, p in enumerate(torch_params): 37 | p.data = torch.tensor(x[i]) 38 | if p.grad is not None: 39 | p.grad.detach_() 40 | p.grad.zero_() 41 | 42 | result = torch_model(*args) 43 | result.backward() 44 | 45 | return result.detach().numpy(), np.array([p.grad.numpy() for p in torch_params]) 46 | 47 | 48 | trace, stats = lmc.sample( 49 | logp_dlogp_func=torch_logp_dlogp_func, 50 | model_ndim=3, 51 | tune=500, 52 | draws=1000, 53 | chains=4, 54 | ) 55 | -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | .. _api: 2 | 3 | .. currentmodule:: littlemcmc 4 | 5 | API Reference 6 | ============= 7 | 8 | .. _sampling_api: 9 | 10 | Sampling 11 | -------- 12 | 13 | .. autosummary:: 14 | :toctree: generated/ 15 | 16 | sample 17 | 18 | .. _step_methods_api: 19 | 20 | Step Methods 21 | ------------ 22 | 23 | .. autosummary:: 24 | :toctree: generated/ 25 | 26 | HamiltonianMC 27 | NUTS 28 | 29 | .. _quadpotentials_api: 30 | 31 | Quadpotentials (a.k.a. Mass Matrices) 32 | ------------------------------------- 33 | 34 | .. autosummary:: 35 | :toctree: generated/ 36 | 37 | quad_potential 38 | QuadPotentialDiag 39 | QuadPotentialFull 40 | QuadPotentialFullInv 41 | QuadPotentialDiagAdapt 42 | QuadPotentialFullAdapt 43 | 44 | .. _step_sizes_api: 45 | 46 | Dual Averaging Step Size Adaptation 47 | ----------------------------------- 48 | 49 | .. autosummary:: 50 | :toctree: generated/ 51 | 52 | step_sizes.DualAverageAdaptation 53 | 54 | .. _integrators_api: 55 | 56 | Integrators 57 | ----------- 58 | 59 | .. autosummary:: 60 | :toctree: generated/ 61 | 62 | integration.CpuLeapfrogIntegrator 63 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | 13 | import os 14 | import sys 15 | 16 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 17 | 18 | import littlemcmc 19 | 20 | # -- Project information ----------------------------------------------------- 21 | 22 | project = "littlemcmc" 23 | copyright = "2019, George Ho" 24 | author = "George Ho" 25 | 26 | # The full version, including alpha/beta/rc tags 27 | release = "0.1.0" 28 | 29 | 30 | # -- General configuration --------------------------------------------------- 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be 33 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 34 | # ones. 35 | extensions = [ 36 | "numpydoc", 37 | "sphinx.ext.autodoc", 38 | "sphinx.ext.autosummary", 39 | "sphinx_rtd_theme", 40 | ] 41 | 42 | # Add any paths that contain templates here, relative to this directory. 43 | templates_path = ["_templates"] 44 | 45 | # By default, Sphinx expects the master doc to be `contents`. Instead, set it to 46 | # `index`. 47 | master_doc = "index" 48 | 49 | # List of patterns, relative to source directory, that match files and 50 | # directories to ignore when looking for source files. 51 | # This pattern also affects html_static_path and html_extra_path. 52 | exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] 53 | 54 | # Generate API documentation when building 55 | autosummary_generate = True 56 | numpydoc_show_class_members = False 57 | 58 | # The version info for the project you're documenting, acts as replacement for 59 | # |version| and |release|, also used in various other places throughout the 60 | # built documents. 61 | # 62 | # The short X.Y version. 63 | version = littlemcmc.__version__ 64 | # The full version, including alpha/beta/rc tags. 65 | release = version 66 | 67 | # -- Options for HTML output ------------------------------------------------- 68 | 69 | # The theme to use for HTML and HTML Help pages. See the documentation for 70 | # a list of builtin themes. 71 | # 72 | html_theme = "sphinx_rtd_theme" 73 | 74 | # Add any paths that contain custom static files (such as style sheets) here, 75 | # relative to this directory. They are copied after the builtin static files, 76 | # so a file named 'default.css' will overwrite the builtin 'default.css'. 77 | html_static_path = ["_static"] 78 | -------------------------------------------------------------------------------- /docs/developer_guide.rst: -------------------------------------------------------------------------------- 1 | ================ 2 | About LittleMCMC 3 | ================ 4 | 5 | LittleMCMC is a lightweight, performant implementation of Hamiltonian Monte 6 | Carlo (HMC) and the No-U-Turn Sampler (NUTS) in Python. This document aims to 7 | explain and contextualize the motivation and purpose of LittleMCMC. For an 8 | introduction to the user-facing API, refer to the `quickstart tutorial 9 | `_. 10 | 11 | 12 | Motivation and Purpose 13 | ---------------------- 14 | 15 | Bayesian inference and probabilistic computation is complicated and has many moving 16 | parts[1]_. As a result, many probabilistic programming frameworks (or any library that 17 | automates Bayesian inference) are monolithic libraries that handle everything from model 18 | specification (including automatic differentiation of the joint log probability), to 19 | inference (usually via Markov chain Monte Carlo or variational inference), to diagnosis 20 | and visualization of the inference results[2]_. PyMC3 and Stan are two excellent 21 | examples of such monolithic frameworks. 22 | 23 | However, such monoliths require users to buy in to entire frameworks or ecosystems. For 24 | example, a user that has specified their model in one framework but who now wishes to 25 | migrate to another library (to take advantage of certain better-supported features, say) 26 | must now reimplement their models from scratch in the new framework. 27 | 28 | LittleMCMC remedies this exact use case: by isolating PyMC's HMC/NUTS code in a 29 | standalone library, users with their own log probability function and its derivative may 30 | use PyMC's battle-tested HMC/NUTS samplers. 31 | 32 | 33 | LittleMCMC in Context 34 | --------------------- 35 | 36 | LittleMCMC stands on the shoulders of giants (that is, giant open source projects). Most 37 | obviously, LittleMCMC builds from (or, more accurately, is a spin-off project from) the 38 | PyMC project (both PyMC3 and PyMC4). 39 | 40 | In terms of prior art, LittleMCMC is similar to several other open-source libraries, 41 | such as `NUTS by Morgan Fouesneau `_ or `Sampyl by 42 | Mat Leonard `_. However, these libraries do not 43 | offer the same functionality as LittleMCMC: for example, they do not allow for easy 44 | changes of the mass matrix (instead assuming that an identity mass matrix), or they do 45 | not raise sampler errors or track sampler statistics such as divergences, energy, etc. 46 | 47 | By offering step methods, integrators, quadpotentials and the sampling loop in separate 48 | Python modules, LittleMCMC offers not just a battle-tested sampler, but also an 49 | extensible one: users may configure the samplers as they wish. 50 | 51 | 52 | .. [1]_ To be convinced of this fact, one can refer to `Michael Betancourt's *Probabilistic Computation* case study `_ or `*A Conceptual Introduction to Hamiltonian Monte Carlo* `_. 53 | 54 | .. [2]_ For more detail, one can refer to `this blog post on the anatomy of probabilistic programming frameworks `_, the `PyMC3 developer guide `_, or `Michael Betancourt's *Introduction to Stan* `_ 55 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. littlemcmc documentation master file, created by 2 | sphinx-quickstart on Sat Dec 14 22:49:04 2019. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | LittleMCMC 7 | ========== 8 | 9 | .. image:: https://github.com/eigenfoo/littlemcmc/workflows/tests/badge.svg 10 | :target: https://github.com/eigenfoo/littlemcmc 11 | .. image:: https://github.com/eigenfoo/littlemcmc/workflows/lint/badge.svg 12 | :target: https://github.com/eigenfoo/littlemcmc 13 | .. image:: https://codecov.io/gh/eigenfoo/littlemcmc/branch/master/graph/badge.svg 14 | :target: https://codecov.io/gh/eigenfoo/littlemcmc 15 | .. image:: https://readthedocs.org/projects/littlemcmc/badge/?version=latest 16 | :target: https://littlemcmc.readthedocs.io/en/latest/?badge=latest 17 | .. image:: https://img.shields.io/github/license/eigenfoo/littlemcmc 18 | :target: https://github.com/eigenfoo/littlemcmc/blob/master/LICENSE.littlemcmc.txt 19 | 20 | .. raw:: html 21 | 22 |
23 | littlemcmc     24 | /lɪtəl ɛm si ɛm si/     25 | noun

26 | A lightweight and performant implementation of HMC and NUTS in Python, spun 27 | out of the PyMC project. Not to 28 | be confused with minimc. 29 |
30 | 31 | .. toctree:: 32 | :maxdepth: 2 33 | :caption: Contents 34 | 35 | install 36 | tutorials/quickstart 37 | tutorials/framework_cookbook 38 | api 39 | developer_guide 40 | -------------------------------------------------------------------------------- /docs/install.rst: -------------------------------------------------------------------------------- 1 | .. _install: 2 | 3 | Installation 4 | ============ 5 | 6 | .. note:: LittleMCMC is developed for Python 3.6 or later. 7 | 8 | LittleMCMC is a pure Python library, so it can be easily installed by using 9 | ``pip`` or directly from source. 10 | 11 | Using ``pip`` 12 | ------------- 13 | 14 | LittleMCMC can be installed using `pip `_. 15 | 16 | .. code-block:: bash 17 | 18 | pip install littlemcmc 19 | 20 | From Source 21 | ----------- 22 | 23 | The source code for LittleMCMC can be downloaded `from GitHub 24 | `_ by running 25 | 26 | .. code-block:: bash 27 | 28 | git clone https://github.com/eigenfoo/littlemcmc.git 29 | cd littlemcmc/ 30 | python setup.py install 31 | 32 | Testing 33 | ------- 34 | 35 | To run the unit tests, install `pytest `_ and then, 36 | in the root of the project directory, execute: 37 | 38 | .. code-block:: bash 39 | 40 | pytest -v 41 | 42 | All of the tests should pass. If any of the tests don't pass and you can't 43 | figure out why, `please open an issue on GitHub 44 | `_. 45 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /docs/tutorials/framework_cookbook.rst: -------------------------------------------------------------------------------- 1 | .. module:: littlemcmc 2 | 3 | .. note:: This tutorial was generated from an IPython notebook that can be 4 | downloaded `here <../../_static/notebooks/framework_cookbook.ipynb>`_. 5 | 6 | .. _framework_cookbook: 7 | 8 | Framework Cookbook 9 | ================== 10 | 11 | ``littlemcmc`` only needs a ``logp_dlogp_func``, which is 12 | framework-agnostic. To illustrate this, this cookbook implements linear 13 | in multiple frameworks, and samples them with ``littlemcmc``. At the end 14 | of this notebook, we load the inference traces and sampler statistics 15 | into ArviZ and do some basic visualizations. 16 | 17 | .. code:: python 18 | 19 | import littlemcmc as lmc 20 | 21 | Create and Visualize Data 22 | ------------------------- 23 | 24 | .. code:: python 25 | 26 | import numpy as np 27 | import matplotlib.pyplot as plt 28 | 29 | np.random.seed(42) 30 | 31 | true_params = np.array([0.5, -2.3, -0.23]) 32 | 33 | N = 50 34 | t = np.linspace(0, 10, 2) 35 | x = np.random.uniform(0, 10, 50) 36 | y = x * true_params[0] + true_params[1] 37 | y_obs = y + np.exp(true_params[-1]) * np.random.randn(N) 38 | 39 | plt.plot(x, y_obs, ".k", label="observations") 40 | plt.plot(t, true_params[0]*t + true_params[1], label="ground truth") 41 | plt.xlabel("x") 42 | plt.ylabel("y") 43 | plt.legend() 44 | plt.show() 45 | 46 | 47 | 48 | .. image:: framework_cookbook_files/framework_cookbook_3_0.png 49 | 50 | 51 | PyTorch 52 | ------- 53 | 54 | .. code:: python 55 | 56 | import torch 57 | 58 | class LinearModel(torch.nn.Module): 59 | def __init__(self): 60 | super(LinearModel, self).__init__() 61 | self.m = torch.nn.Parameter(torch.tensor(0.0, dtype=torch.float64)) 62 | self.b = torch.nn.Parameter(torch.tensor(0.0, dtype=torch.float64)) 63 | self.logs = torch.nn.Parameter(torch.tensor(0.0, dtype=torch.float64)) 64 | 65 | def forward(self, x, y): 66 | mean = self.m * x + self.b 67 | loglike = -0.5 * torch.sum((y - mean) ** 2 * torch.exp(-2 * self.logs) + 2 * self.logs) 68 | return loglike 69 | 70 | torch_model = torch.jit.script(LinearModel()) 71 | torch_params = [torch_model.m, torch_model.b, torch_model.logs] 72 | args = [torch.tensor(x, dtype=torch.double), torch.tensor(y_obs, dtype=torch.double)] 73 | 74 | def torch_logp_dlogp_func(x): 75 | for i, p in enumerate(torch_params): 76 | p.data = torch.tensor(x[i]) 77 | if p.grad is not None: 78 | p.grad.detach_() 79 | p.grad.zero_() 80 | 81 | result = torch_model(*args) 82 | result.backward() 83 | 84 | return result.detach().numpy(), np.array([p.grad.numpy() for p in torch_params]) 85 | 86 | 87 | 88 | .. parsed-literal:: 89 | 90 | 298 µs ± 43.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) 91 | 92 | 93 | Please see 94 | ```sample_pytorch_logp_dlogp_func.py`` `__ 95 | for a working example. Theoretically, however, all that’s needed is to 96 | run the following snippet: 97 | 98 | .. code:: python 99 | 100 | trace, stats = lmc.sample( 101 | logp_dlogp_func=torch_logp_dlogp_func, model_ndim=3, tune=500, draws=1000, chains=4, 102 | ) 103 | 104 | JAX 105 | --- 106 | 107 | .. code:: python 108 | 109 | from jax.config import config 110 | config.update("jax_enable_x64", True) 111 | 112 | import jax 113 | import jax.numpy as jnp 114 | 115 | def jax_model(params): 116 | mean = params[0] * x + params[1] 117 | loglike = -0.5 * jnp.sum((y_obs - mean) ** 2 * jnp.exp(-2 * params[2]) + 2 * params[2]) 118 | return loglike 119 | 120 | @jax.jit 121 | def jax_model_and_grad(x): 122 | return jax_model(x), jax.grad(jax_model)(x) 123 | 124 | 125 | def jax_logp_dlogp_func(x): 126 | v, g = jax_model_and_grad(x) 127 | return np.asarray(v), np.asarray(g) 128 | 129 | 130 | 131 | .. parsed-literal:: 132 | 133 | /Users/george/miniconda3/lib/python3.7/site-packages/jax/lib/xla_bridge.py:125: UserWarning: No GPU/TPU found, falling back to CPU. 134 | warnings.warn('No GPU/TPU found, falling back to CPU.') 135 | 136 | 137 | .. parsed-literal:: 138 | 139 | 269 µs ± 48.6 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) 140 | 141 | 142 | Please see 143 | ```sample_jax_logp_dlogp_func.py`` `__ 144 | for a working example. Theoretically, however, all that’s needed is to 145 | run the following snippet: 146 | 147 | .. code:: python 148 | 149 | trace, stats = lmc.sample( 150 | logp_dlogp_func=jax_logp_dlogp_func, model_ndim=3, tune=500, draws=1000, chains=4, 151 | ) 152 | 153 | PyMC3 154 | ----- 155 | 156 | .. code:: python 157 | 158 | import pymc3 as pm 159 | import theano 160 | 161 | with pm.Model() as pm_model: 162 | pm_params = pm.Flat("pm_params", shape=3) 163 | mean = pm_params[0] * x + pm_params[1] 164 | pm.Normal("obs", mu=mean, sigma=pm.math.exp(pm_params[2]), observed=y_obs) 165 | 166 | pm_model_and_grad = pm_model.fastfn([pm_model.logpt] + theano.grad(pm_model.logpt, pm_model.vars)) 167 | 168 | def pm_logp_dlogp_func(x): 169 | return pm_model_and_grad(pm_model.bijection.rmap(x)) 170 | 171 | 172 | 173 | .. parsed-literal:: 174 | 175 | 46.3 µs ± 3.94 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) 176 | 177 | 178 | .. code:: python 179 | 180 | trace, stats = lmc.sample( 181 | logp_dlogp_func=pm_logp_dlogp_func, 182 | model_ndim=3, 183 | tune=500, 184 | draws=1000, 185 | chains=4, 186 | progressbar=False, # Progress bars don't render well in reStructuredText docs... 187 | ) 188 | 189 | Visualize Traces with ArviZ 190 | --------------------------- 191 | 192 | Just to sanity check our results, let’s visualize all the traces using 193 | ArviZ. At the time of writing there’s no way to easily load the 194 | ``np.ndarrays`` arrays that ``littlemcmc`` returns into an 195 | ``az.InferenceDataset``. Hopefully one day we’ll have an 196 | ``az.from_littlemcmc`` method… but until then, please use this code 197 | snippet! 198 | 199 | .. code:: python 200 | 201 | def arviz_from_littlemcmc(trace, stats): 202 | return az.InferenceData( 203 | posterior=az.dict_to_dataset({"x": trace}), 204 | sample_stats=az.dict_to_dataset({k: v.squeeze() for k, v in stats.items()}) 205 | ) 206 | 207 | .. code:: python 208 | 209 | import arviz as az 210 | 211 | dataset = arviz_from_littlemcmc(trace, stats) 212 | 213 | az.plot_trace(dataset) 214 | plt.show() 215 | 216 | 217 | 218 | .. image:: framework_cookbook_files/framework_cookbook_18_0.png 219 | 220 | 221 | -------------------------------------------------------------------------------- /docs/tutorials/framework_cookbook_files/framework_cookbook_18_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eigenfoo/littlemcmc/2b5dd87972ce13b6d2898ced9b748cc9ce2643b6/docs/tutorials/framework_cookbook_files/framework_cookbook_18_0.png -------------------------------------------------------------------------------- /docs/tutorials/framework_cookbook_files/framework_cookbook_1_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eigenfoo/littlemcmc/2b5dd87972ce13b6d2898ced9b748cc9ce2643b6/docs/tutorials/framework_cookbook_files/framework_cookbook_1_0.png -------------------------------------------------------------------------------- /docs/tutorials/framework_cookbook_files/framework_cookbook_3_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eigenfoo/littlemcmc/2b5dd87972ce13b6d2898ced9b748cc9ce2643b6/docs/tutorials/framework_cookbook_files/framework_cookbook_3_0.png -------------------------------------------------------------------------------- /docs/tutorials/quickstart.rst: -------------------------------------------------------------------------------- 1 | .. module:: littlemcmc 2 | 3 | .. note:: This tutorial was generated from an IPython notebook that can be 4 | downloaded `here <../../_static/notebooks/quickstart.ipynb>`_. 5 | 6 | .. _quickstart: 7 | 8 | LittleMCMC Quickstart 9 | ===================== 10 | 11 | LittleMCMC is a lightweight and performant implementation of HMC and 12 | NUTS in Python, spun out of the PyMC project. In this quickstart 13 | tutorial, we will walk through the main use case of LittleMCMC, and 14 | outline the various modules that may be of interest. 15 | 16 | Table of Contents 17 | ----------------- 18 | 19 | - `Who should use LittleMCMC? <#who-should-use-littlemcmc>`__ 20 | - `Sampling <#how-to-sample>`__ 21 | 22 | - `Inspecting the Output of 23 | lmc.sample <#inspecting-the-output-of-lmc-sample>`__ 24 | 25 | - `Customizing the Default NUTS 26 | Sampler <#customizing-the-default-nuts-sampler>`__ 27 | - `Other Modules <#other-modules>`__ 28 | 29 | Who should use LittleMCMC? 30 | -------------------------- 31 | 32 | LittleMCMC is a fairly barebones library with a very niche use case. 33 | Most users will probably find that 34 | `PyMC3 `__ will satisfy their needs, 35 | with better strength of support and quality of documentation. 36 | 37 | There are two expected use cases for LittleMCMC. Firstly, if you: 38 | 39 | 1. Have a model with only continuous parameters, 40 | 2. Are willing to manually transform all of your model’s parameters to 41 | the unconstrained space (if necessary), 42 | 3. Have a Python function/callable that: 43 | 44 | 1. computes the log probability of your model and its derivative 45 | 2. is `pickleable `__ 46 | 3. outputs an array with the same shape as its input 47 | 48 | 4. And all you need is an implementation of HMC/NUTS (preferably in 49 | Python) to sample from the posterior, 50 | 51 | then you should consider using LittleMCMC. 52 | 53 | Secondly, if you want to run algorithmic experiments on HMC/NUTS (in 54 | Python), without having to develop around the heavy machinery that 55 | accompanies other probabilistic programming frameworks (like 56 | `PyMC3 `__, `TensorFlow 57 | Probability `__ or 58 | `Stan `__), then you should consider 59 | running your experiments in LittleMCMC. 60 | 61 | How to Sample 62 | ------------- 63 | 64 | .. code:: python 65 | 66 | import numpy as np 67 | import scipy 68 | import littlemcmc as lmc 69 | 70 | .. code:: python 71 | 72 | def logp_func(x, loc=0, scale=1): 73 | return np.log(scipy.stats.norm.pdf(x, loc=loc, scale=scale)) 74 | 75 | 76 | def dlogp_func(x, loc=0, scale=1): 77 | return -(x - loc) / scale 78 | 79 | 80 | def logp_dlogp_func(x, loc=0, scale=1): 81 | return logp_func(x, loc=loc, scale=scale), dlogp_func(x, loc=loc, scale=scale) 82 | 83 | .. code:: python 84 | 85 | # By default: 4 chains in 4 cores, 500 tuning steps and 1000 sampling steps. 86 | trace, stats = lmc.sample( 87 | logp_dlogp_func=logp_dlogp_func, 88 | model_ndim=1, 89 | progressbar=None, # HTML progress bars don't render well in RST. 90 | ) 91 | 92 | 93 | .. parsed-literal:: 94 | 95 | /home/george/littlemcmc/venv/lib/python3.6/site-packages/ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in log 96 | 97 | 98 | 99 | Inspecting the Output of ``lmc.sample`` 100 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 101 | 102 | .. code:: python 103 | 104 | # Shape is (num_chains, num_samples, num_parameters) 105 | trace.shape 106 | 107 | 108 | 109 | 110 | .. parsed-literal:: 111 | 112 | (4, 1000, 1) 113 | 114 | 115 | 116 | .. code:: python 117 | 118 | # The first 2 samples across all chains and parameters 119 | trace[:, :2, :] 120 | 121 | 122 | 123 | 124 | .. parsed-literal:: 125 | 126 | array([[[ 0.92958231], 127 | [ 0.92958231]], 128 | 129 | [[-1.06231693], 130 | [-1.11589309]], 131 | 132 | [[-0.73177109], 133 | [-0.66975061]], 134 | 135 | [[ 0.8923907 ], 136 | [ 0.97253646]]]) 137 | 138 | 139 | 140 | .. code:: python 141 | 142 | stats.keys() 143 | 144 | 145 | 146 | 147 | .. parsed-literal:: 148 | 149 | dict_keys(['depth', 'step_size', 'tune', 'mean_tree_accept', 'step_size_bar', 'tree_size', 'diverging', 'energy_error', 'energy', 'max_energy_error', 'model_logp']) 150 | 151 | 152 | 153 | .. code:: python 154 | 155 | # Again, shape is (num_chains, num_samples, num_parameters) 156 | stats["depth"].shape 157 | 158 | 159 | 160 | 161 | .. parsed-literal:: 162 | 163 | (4, 1000, 1) 164 | 165 | 166 | 167 | .. code:: python 168 | 169 | # The first 2 tree depths across all chains and parameters 170 | stats["depth"][:, :2, :] 171 | 172 | 173 | 174 | 175 | .. parsed-literal:: 176 | 177 | array([[[2], 178 | [1]], 179 | 180 | [[1], 181 | [1]], 182 | 183 | [[2], 184 | [1]], 185 | 186 | [[2], 187 | [1]]]) 188 | 189 | 190 | 191 | Customizing the Default NUTS Sampler 192 | ------------------------------------ 193 | 194 | By default, ``lmc.sample`` samples using NUTS with sane defaults. These 195 | defaults can be override by either: 196 | 197 | 1. Passing keyword arguments from ``lmc.NUTS`` into ``lmc.sample``, or 198 | 2. Constructing an ``lmc.NUTS`` sampler, and passing that to 199 | ``lmc.sample``. This method also allows you to choose to other 200 | samplers, such as ``lmc.HamiltonianMC``. 201 | 202 | For example, suppose you want to increase the ``target_accept`` from the 203 | default ``0.8`` to ``0.9``. The following two cells are equivalent: 204 | 205 | .. code:: python 206 | 207 | trace, stats = lmc.sample( 208 | logp_dlogp_func=logp_dlogp_func, 209 | model_ndim=1, 210 | target_accept=0.9, 211 | progressbar=None, 212 | ) 213 | 214 | .. code:: python 215 | 216 | step = lmc.NUTS(logp_dlogp_func=logp_dlogp_func, model_ndim=1, target_accept=0.9) 217 | trace, stats = lmc.sample( 218 | logp_dlogp_func=logp_dlogp_func, 219 | model_ndim=1, 220 | step=step, 221 | progressbar=None, 222 | ) 223 | 224 | 225 | .. parsed-literal:: 226 | 227 | /home/george/littlemcmc/venv/lib/python3.6/site-packages/ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in log 228 | 229 | 230 | 231 | For a list of keyword arguments that ``lmc.NUTS`` accepts, please refer 232 | to the `API reference for 233 | ``lmc.NUTS`` `__. 234 | 235 | Other Modules 236 | ------------- 237 | 238 | LittleMCMC exposes: 239 | 240 | 1. Two step methods (a.k.a. samplers): ```littlemcmc.HamiltonianMC`` 241 | (Hamiltonian Monte 242 | Carlo) `__ 243 | and the ```littlemcmc.NUTS`` (No-U-Turn 244 | Sampler) `__ 245 | 2. Various quadpotentials (a.k.a. mass matrices or inverse metrics) in 246 | ```littlemcmc.quadpotential`` `__, 247 | along with mass matrix adaptation routines 248 | 3. Dual-averaging step size adaptation in 249 | ```littlemcmc.step_sizes`` `__ 250 | 4. A leapfrog integrator in 251 | ```littlemcmc.integration`` `__ 252 | 253 | These modules should allow for easy experimentation with the sampler. 254 | Please refer to the `API 255 | Reference `__ for 256 | more information. 257 | -------------------------------------------------------------------------------- /docs/tutorials/tutorial_rst.tpl: -------------------------------------------------------------------------------- 1 | {%- extends 'display_priority.tpl' -%} 2 | 3 | {% block header %} 4 | .. module:: littlemcmc 5 | 6 | .. note:: This tutorial was generated from an IPython notebook that can be 7 | downloaded `here <../../_static/notebooks/{{ resources.metadata.name }}.ipynb>`_. 8 | 9 | .. _{{resources.metadata.name}}: 10 | {% endblock %} 11 | 12 | {% block in_prompt %} 13 | {% endblock in_prompt %} 14 | 15 | {% block output_prompt %} 16 | {% endblock output_prompt %} 17 | 18 | {% block input %} 19 | {%- if cell.source.strip() and not cell.source.startswith("%") -%} 20 | .. code:: python 21 | 22 | {{ cell.source | indent}} 23 | {% endif -%} 24 | {% endblock input %} 25 | 26 | {% block error %} 27 | :: 28 | 29 | {{ super() }} 30 | {% endblock error %} 31 | 32 | {% block traceback_line %} 33 | {{ line | indent | strip_ansi }} 34 | {% endblock traceback_line %} 35 | 36 | {% block execute_result %} 37 | {% block data_priority scoped %} 38 | {{ super() }} 39 | {% endblock %} 40 | {% endblock execute_result %} 41 | 42 | {% block stream %} 43 | .. parsed-literal:: 44 | 45 | {{ output.text | indent }} 46 | {% endblock stream %} 47 | 48 | {% block data_svg %} 49 | .. image:: {{ output.metadata.filenames['image/svg+xml'] | urlencode }} 50 | {% endblock data_svg %} 51 | 52 | {% block data_png %} 53 | .. image:: {{ output.metadata.filenames['image/png'] | urlencode }} 54 | {% endblock data_png %} 55 | 56 | {% block data_jpg %} 57 | .. image:: {{ output.metadata.filenames['image/jpeg'] | urlencode }} 58 | {% endblock data_jpg %} 59 | 60 | {% block data_latex %} 61 | .. math:: 62 | 63 | {{ output.data['text/latex'] | strip_dollars | indent }} 64 | {% endblock data_latex %} 65 | 66 | {% block data_text scoped %} 67 | .. parsed-literal:: 68 | 69 | {{ output.data['text/plain'] | indent }} 70 | {% endblock data_text %} 71 | 72 | {% block data_html scoped %} 73 | .. raw:: html 74 | 75 | {{ output.data['text/html'] | indent }} 76 | {% endblock data_html %} 77 | 78 | {% block markdowncell scoped %} 79 | {{ cell.source | markdown2rst }} 80 | {% endblock markdowncell %} 81 | 82 | {%- block rawcell scoped -%} 83 | {%- if cell.metadata.get('raw_mimetype', '').lower() in resources.get('raw_mimetypes', ['']) %} 84 | {{cell.source}} 85 | {% endif -%} 86 | {%- endblock rawcell -%} 87 | 88 | {% block headingcell scoped %} 89 | {{ ("#" * cell.level + cell.source) | replace('\n', ' ') | markdown2rst }} 90 | {% endblock headingcell %} 91 | 92 | {% block unknowncell scoped %} 93 | unknown type {{cell.type}} 94 | {% endblock unknowncell %} 95 | -------------------------------------------------------------------------------- /littlemcmc/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """LittleMCMC.""" 16 | 17 | __version__ = "0.2.2" 18 | 19 | from .sampling import sample, init_nuts 20 | from .hmc import HamiltonianMC 21 | from .nuts import NUTS 22 | from .quadpotential import ( 23 | quad_potential, 24 | QuadPotentialDiag, 25 | QuadPotentialFull, 26 | QuadPotentialFullInv, 27 | QuadPotentialDiagAdapt, 28 | QuadPotentialFullAdapt, 29 | ) 30 | 31 | import multiprocessing as mp 32 | 33 | ctx = mp.get_context("spawn") 34 | -------------------------------------------------------------------------------- /littlemcmc/base_hmc.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Base class for Hamiltonian Monte Carlo samplers.""" 16 | 17 | from collections import namedtuple 18 | from typing import Callable, Tuple, List, Optional 19 | import numpy as np 20 | 21 | from . import integration, step_sizes 22 | from .quadpotential import quad_potential, QuadPotential, QuadPotentialDiagAdapt 23 | from .report import SamplerWarning, WarningType 24 | 25 | HMCStepData = namedtuple("HMCStepData", "end, accept_stat, divergence_info, stats") 26 | DivergenceInfo = namedtuple("DivergenceInfo", "message, exec_info, state") 27 | 28 | 29 | class BaseHMC: 30 | """Superclass to implement Hamiltonian Monte Carlo.""" 31 | 32 | def __init__( 33 | self, 34 | logp_dlogp_func: Callable[[np.ndarray], Tuple[np.ndarray, np.ndarray]], 35 | model_ndim: int, 36 | scaling: Optional[np.ndarray], 37 | is_cov: bool, 38 | potential: QuadPotential, 39 | target_accept: float, 40 | Emax: float, 41 | adapt_step_size: bool, 42 | step_scale: float, 43 | gamma: float, 44 | k: float, 45 | t0: int, 46 | step_rand: Optional[Callable[[float], float]], 47 | ) -> None: 48 | """Set up Hamiltonian samplers with common structures. 49 | 50 | Parameters 51 | ---------- 52 | logp_dlogp_func : Python callable 53 | Python callable that returns the log-probability and derivative of 54 | the log-probability, respectively. 55 | model_ndim : int 56 | Total number of parameters. Dimensionality of the output of 57 | ``logp_dlogp_func``. 58 | scaling : 1 or 2-dimensional array-like 59 | Scaling for momentum distribution. 1 dimensional arrays are 60 | interpreted as a matrix diagonal. Only one of ``scaling`` or 61 | ``potential`` may be non-None. 62 | is_cov : bool 63 | Treat scaling as a covariance matrix/vector if True, else treat 64 | it as a precision matrix/vector 65 | potential : littlemcmc.quadpotential.Potential, optional 66 | An object that represents the Hamiltonian with methods ``velocity``, 67 | ``energy``, and ``random`` methods. Only one of ``scaling`` or 68 | ``potential`` may be non-None. 69 | target_accept : float 70 | Adapt the step size such that the average acceptance probability 71 | across the trajectories are close to target_accept. Higher values 72 | for target_accept lead to smaller step sizes. Setting this to higher 73 | values like 0.9 or 0.99 can help with sampling from difficult 74 | posteriors. Valid values are between 0 and 1 (exclusive). 75 | Emax : float 76 | The maximum allowable change in the value of the Hamiltonian. Any 77 | trajectories that result in changes in the value of the Hamiltonian 78 | larger than ``Emax`` will be declared divergent. 79 | adapt_step_size : bool, default=True 80 | If True, performs dual averaging step size adaptation. If False, 81 | ``k``, ``t0``, ``gamma`` and ``target_accept`` are ignored. 82 | step_scale : float 83 | Size of steps to take, automatically scaled down by 1 / (``size`` ** 84 | 0.25). 85 | gamma : float, default .05 86 | k : float, default .75 87 | Parameter for dual averaging for step size adaptation. Values 88 | between 0.5 and 1 (exclusive) are admissible. Higher values 89 | correspond to slower adaptation. 90 | t0 : int, default 10 91 | Parameter for dual averaging. Higher values slow initial adaptation. 92 | step_rand : Python callable 93 | Callback for step size adaptation. Called on the step size at each 94 | iteration immediately before performing dual-averaging step size 95 | adaptation. 96 | """ 97 | self._logp_dlogp_func = logp_dlogp_func 98 | self.adapt_step_size = adapt_step_size 99 | self.Emax = Emax 100 | self.iter_count = 0 101 | self.model_ndim = model_ndim 102 | self.step_size = step_scale / (model_ndim ** 0.25) 103 | self.target_accept = target_accept 104 | self.step_adapt = step_sizes.DualAverageAdaptation( 105 | self.step_size, target_accept, gamma, k, t0 106 | ) 107 | self.tune = True 108 | 109 | if scaling is None and potential is None: 110 | # Default to diagonal quadpotential 111 | mean = np.zeros(model_ndim) 112 | var = np.ones(model_ndim) 113 | potential = QuadPotentialDiagAdapt(model_ndim, mean, var, 10) 114 | 115 | if scaling is not None and potential is not None: 116 | raise ValueError("Cannot specify both `potential` and `scaling`.") 117 | elif potential is not None: 118 | self.potential = potential 119 | else: 120 | self.potential = quad_potential(scaling, is_cov) 121 | 122 | self.integrator = integration.CpuLeapfrogIntegrator(self.potential, self._logp_dlogp_func) 123 | self._step_rand = step_rand 124 | self._warnings: List[SamplerWarning] = [] 125 | self._samples_after_tune = 0 126 | self._num_divs_sample = 0 127 | 128 | def stop_tuning(self) -> None: 129 | """Stop tuning.""" 130 | if hasattr(self, "tune"): 131 | self.tune = False 132 | 133 | def _hamiltonian_step(self, start: np.ndarray, p0: np.ndarray, step_size: float) -> HMCStepData: 134 | """Compute one Hamiltonian trajectory and return the next state. 135 | 136 | Subclasses must overwrite this method and return a `HMCStepData`. 137 | """ 138 | raise NotImplementedError("Abstract method") 139 | 140 | def _astep(self, q0: np.ndarray): 141 | """Perform a single HMC iteration.""" 142 | p0 = self.potential.random() 143 | start = self.integrator.compute_state(q0, p0) 144 | 145 | if not np.isfinite(start.energy): 146 | raise ValueError( 147 | "Bad initial energy: {}. The model might be misspecified.".format(start.energy) 148 | ) 149 | 150 | # Adapt step size 151 | adapt_step = self.tune and self.adapt_step_size 152 | step_size = self.step_adapt.current(adapt_step) 153 | self.step_size = step_size 154 | if self._step_rand is not None: 155 | step_size = self._step_rand(step_size) 156 | 157 | # Take the Hamiltonian step 158 | hmc_step = self._hamiltonian_step(start, p0, step_size) 159 | 160 | # Update step size and quadpotential 161 | self.step_adapt.update(hmc_step.accept_stat, adapt_step) 162 | self.potential.update(hmc_step.end.q, hmc_step.end.q_grad, self.tune) 163 | 164 | if hmc_step.divergence_info: 165 | info = hmc_step.divergence_info 166 | if self.tune: 167 | kind = WarningType.TUNING_DIVERGENCE 168 | point = None 169 | else: 170 | kind = WarningType.DIVERGENCE 171 | self._num_divs_sample += 1 172 | # We don't want to fill up all memory, so do not return points 173 | # with divergence info 174 | point = None 175 | warning = SamplerWarning( 176 | kind, info.message, "debug", self.iter_count, info.exec_info, point 177 | ) 178 | 179 | self._warnings.append(warning) 180 | 181 | self.iter_count += 1 182 | if not self.tune: 183 | self._samples_after_tune += 1 184 | 185 | stats = {"tune": self.tune, "diverging": bool(hmc_step.divergence_info)} 186 | 187 | stats.update(hmc_step.stats) 188 | stats.update(self.step_adapt.stats()) 189 | 190 | return hmc_step.end.q, [stats] 191 | 192 | def reset_tuning(self, start: np.ndarray = None) -> None: 193 | """Reset quadpotential and step size adaptation, and begin retuning.""" 194 | self.step_adapt.reset() 195 | self.reset(start=None) 196 | 197 | def reset(self, start: np.ndarray = None) -> None: 198 | """Reset quadpotential and begin retuning.""" 199 | self.tune = True 200 | self.potential.reset() 201 | 202 | def warnings(self) -> List[SamplerWarning]: 203 | """Generate warnings from HMC sampler.""" 204 | # list.copy() is only available in Python 3 205 | warnings = self._warnings.copy() 206 | 207 | # Generate a global warning for divergences 208 | message = "" 209 | n_divs = self._num_divs_sample 210 | if n_divs and self._samples_after_tune == n_divs: 211 | message = ( 212 | "The chain contains only diverging samples. The model is probably misspecified." 213 | ) 214 | elif n_divs == 1: 215 | message = ( 216 | "There was 1 divergence after tuning. Increase " 217 | "`target_accept` or reparameterize." 218 | ) 219 | elif n_divs > 1: 220 | message = ( 221 | "There were %s divergences after tuning. Increase " 222 | "`target_accept` or reparameterize." % n_divs 223 | ) 224 | 225 | if message: 226 | warning = SamplerWarning(WarningType.DIVERGENCES, message, "error", None, None, None) 227 | warnings.append(warning) 228 | 229 | warnings.extend(self.step_adapt.warnings()) 230 | return warnings 231 | -------------------------------------------------------------------------------- /littlemcmc/exceptions.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Exceptions.""" 16 | 17 | __all__ = [ 18 | "SamplingError", 19 | ] 20 | 21 | 22 | class SamplingError(RuntimeError): 23 | """Error while sampling.""" 24 | 25 | pass 26 | -------------------------------------------------------------------------------- /littlemcmc/hmc.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Hamiltonian Monte Carlo sampler.""" 16 | 17 | from typing import Callable, Tuple, Optional 18 | import numpy as np 19 | 20 | from .integration import IntegrationError 21 | from .base_hmc import BaseHMC, HMCStepData, DivergenceInfo 22 | 23 | 24 | __all__ = ["HamiltonianMC"] 25 | 26 | 27 | class HamiltonianMC(BaseHMC): 28 | r"""A sampler for continuous variables based on Hamiltonian mechanics. 29 | 30 | See NUTS sampler for automatically tuned stopping time and step size 31 | scaling. 32 | """ 33 | 34 | name = "hmc" 35 | generates_stats = True 36 | stats_dtypes = [ 37 | { 38 | "step_size": np.float64, 39 | "n_steps": np.int64, 40 | "tune": np.bool, 41 | "step_size_bar": np.float64, 42 | "accept": np.float64, 43 | "diverging": np.bool, 44 | "energy_error": np.float64, 45 | "energy": np.float64, 46 | "path_length": np.float64, 47 | "accepted": np.bool, 48 | "model_logp": np.float64, 49 | } 50 | ] 51 | 52 | def __init__( 53 | self, 54 | logp_dlogp_func: Callable[[np.ndarray], Tuple[np.ndarray, np.ndarray]], 55 | model_ndim: int, 56 | scaling: Optional[np.ndarray] = None, 57 | is_cov: bool = False, 58 | potential=None, 59 | target_accept: float = 0.8, 60 | Emax: float = 1000, 61 | adapt_step_size: bool = True, 62 | step_scale: float = 0.25, 63 | gamma: float = 0.05, 64 | k: float = 0.75, 65 | t0: int = 10, 66 | step_rand: Optional[Callable[[float], float]] = None, 67 | path_length: float = 2.0, 68 | max_steps: int = 1024, 69 | ): 70 | """Set up the Hamiltonian Monte Carlo sampler. 71 | 72 | Parameters 73 | ---------- 74 | logp_dlogp_func : Python callable 75 | Python callable that returns the log-probability and derivative of 76 | the log-probability, respectively. 77 | model_ndim : int 78 | Total number of parameters. Dimensionality of the output of 79 | ``logp_dlogp_func``. 80 | scaling : 1 or 2-dimensional array-like 81 | Scaling for momentum distribution. 1 dimensional arrays are 82 | interpreted as a matrix diagonal. 83 | is_cov : bool 84 | Treat scaling as a covariance matrix/vector if True, else treat 85 | it as a precision matrix/vector 86 | potential : littlemcmc.quadpotential.Potential, optional 87 | An object that represents the Hamiltonian with methods ``velocity``, 88 | ``energy``, and ``random`` methods. Only one of ``scaling`` or 89 | ``potential`` may be non-None. 90 | target_accept : float 91 | Adapt the step size such that the average acceptance probability 92 | across the trajectories are close to target_accept. Higher values 93 | for target_accept lead to smaller step sizes. Setting this to higher 94 | values like 0.9 or 0.99 can help with sampling from difficult 95 | posteriors. Valid values are between 0 and 1 (exclusive). 96 | Emax : float 97 | The maximum allowable change in the value of the Hamiltonian. Any 98 | trajectories that result in changes in the value of the Hamiltonian 99 | larger than ``Emax`` will be declared divergent. 100 | adapt_step_size : bool, default=True 101 | If True, performs dual averaging step size adaptation. If False, 102 | ``k``, ``t0``, ``gamma`` and ``target_accept`` are ignored. 103 | step_scale : float 104 | Size of steps to take, automatically scaled down by 1 / (``size`` ** 105 | 0.25). 106 | gamma : float, default .05 107 | k : float, default .75 108 | Parameter for dual averaging for step size adaptation. Values 109 | between 0.5 and 1 (exclusive) are admissible. Higher values 110 | correspond to slower adaptation. 111 | t0 : int, default 10 112 | Parameter for dual averaging. Higher values slow initial adaptation. 113 | step_rand : Python callable 114 | Callback for step size adaptation. Called on the step size at each 115 | iteration immediately before performing dual-averaging step size 116 | adaptation. 117 | path_length : float, default=2 118 | total length to travel 119 | max_steps : int, default=1024 120 | The maximum number of leapfrog steps. 121 | """ 122 | super(HamiltonianMC, self).__init__( 123 | scaling=scaling, 124 | step_scale=step_scale, 125 | is_cov=is_cov, 126 | logp_dlogp_func=logp_dlogp_func, 127 | model_ndim=model_ndim, 128 | potential=potential, 129 | Emax=Emax, 130 | target_accept=target_accept, 131 | gamma=gamma, 132 | k=k, 133 | t0=t0, 134 | adapt_step_size=adapt_step_size, 135 | step_rand=step_rand, 136 | ) 137 | self.path_length = path_length 138 | self.max_steps = max_steps 139 | 140 | def _hamiltonian_step(self, start: np.ndarray, p0: np.ndarray, step_size: float) -> HMCStepData: 141 | path_length = np.random.rand() * self.path_length 142 | n_steps = max(1, int(path_length / step_size)) 143 | n_steps = min(self.max_steps, n_steps) 144 | 145 | energy_change = -np.inf 146 | state = start 147 | div_info = None 148 | try: 149 | for _ in range(n_steps): 150 | state = self.integrator.step(step_size, state) 151 | except IntegrationError as e: 152 | div_info = DivergenceInfo("Divergence encountered.", e, state) 153 | else: 154 | if not np.isfinite(state.energy): 155 | div_info = DivergenceInfo("Divergence encountered, bad energy.", None, state) 156 | energy_change = start.energy - state.energy 157 | if np.isnan(energy_change): 158 | energy_change = -np.inf 159 | if np.abs(energy_change) > self.Emax: 160 | div_info = DivergenceInfo( 161 | "Divergence encountered, large integration error.", None, state 162 | ) 163 | 164 | accept_stat = min(1, np.exp(energy_change)) 165 | 166 | if div_info is not None or np.random.rand() >= accept_stat: 167 | end = start 168 | accepted = False 169 | else: 170 | end = state 171 | accepted = True 172 | 173 | stats = { 174 | "path_length": path_length, 175 | "n_steps": n_steps, 176 | "accept": accept_stat, 177 | "energy_error": energy_change, 178 | "energy": state.energy, 179 | "accepted": accepted, 180 | "model_logp": state.model_logp, 181 | } 182 | return HMCStepData(end, accept_stat, div_info, stats) 183 | -------------------------------------------------------------------------------- /littlemcmc/integration.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Leapfrog integrators.""" 16 | 17 | from collections import namedtuple 18 | from typing import Callable, Tuple 19 | 20 | import numpy as np 21 | from scipy import linalg 22 | from .quadpotential import QuadPotential 23 | 24 | 25 | State = namedtuple("State", "q, p, v, q_grad, energy, model_logp") 26 | 27 | 28 | class IntegrationError(RuntimeError): 29 | """Numerical errors during leapfrog integration.""" 30 | 31 | pass 32 | 33 | 34 | class CpuLeapfrogIntegrator(object): 35 | """Leapfrog integrator using the CPU.""" 36 | 37 | def __init__( 38 | self, 39 | potential: QuadPotential, 40 | logp_dlogp_func: Callable[[np.ndarray], Tuple[np.ndarray, np.ndarray]], 41 | ) -> None: 42 | """Instantiate a CPU leapfrog integrator. 43 | 44 | Parameters 45 | ---------- 46 | potential 47 | logp_dlogp_func 48 | """ 49 | self._potential = potential 50 | self._logp_dlogp_func = logp_dlogp_func 51 | 52 | def compute_state(self, q: np.ndarray, p: np.ndarray) -> State: 53 | """Compute Hamiltonian functions using a position and momentum. 54 | 55 | Parameters 56 | ---------- 57 | q 58 | Position. 59 | p 60 | Momentum 61 | """ 62 | logp, dlogp = self._logp_dlogp_func(q) 63 | v = self._potential.velocity(p) 64 | kinetic = self._potential.energy(p, velocity=v) 65 | energy = kinetic - logp 66 | return State(q, p, v, dlogp, energy, logp) 67 | 68 | def step(self, epsilon, state: State, out=None): 69 | """Leapfrog integrator step. 70 | 71 | Half a momentum update, full position update, half momentum update. 72 | 73 | Parameters 74 | ---------- 75 | epsilon: float, > 0 76 | step scale 77 | state: State namedtuple, 78 | current position data 79 | out: (optional) State namedtuple, 80 | preallocated arrays to write to in place 81 | 82 | Returns 83 | ------- 84 | None if `out` is provided, else a State namedtuple 85 | """ 86 | try: 87 | return self._step(epsilon, state) 88 | except linalg.LinAlgError as err: 89 | msg = "LinAlgError during leapfrog step." 90 | raise IntegrationError(msg) 91 | except ValueError as err: 92 | # Raised by many scipy.linalg functions 93 | scipy_msg = "array must not contain infs or nans" 94 | if len(err.args) > 0 and scipy_msg in err.args[0].lower(): 95 | msg = "Infs or nans in scipy.linalg during leapfrog step." 96 | raise IntegrationError(msg) 97 | else: 98 | raise 99 | 100 | def _step(self, epsilon, state: State) -> State: 101 | """Perform one leapfrog step.""" 102 | pot = self._potential 103 | q, p, v, q_grad, energy, logp = state 104 | 105 | dt = 0.5 * epsilon 106 | 107 | # Half momentum step 108 | p_new = p + dt * q_grad 109 | 110 | # Whole position step 111 | v_new = pot.velocity(p_new) 112 | q_new = (q + epsilon * v_new).astype(q.dtype) 113 | 114 | # Half momentum step 115 | logp, q_new_grad = self._logp_dlogp_func(q_new) 116 | p_new = p_new + dt * q_new_grad 117 | 118 | kinetic = pot.velocity_energy(p_new, v_new) 119 | energy = kinetic - logp 120 | 121 | return State(q_new, p_new, v_new, q_new_grad, energy, logp) 122 | -------------------------------------------------------------------------------- /littlemcmc/math.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Utility mathematical functions.""" 16 | 17 | import numpy as np 18 | import numpy.random as nr 19 | 20 | 21 | def logbern(log_p: float) -> bool: 22 | """Perform a Bernoulli trial given a log probability.""" 23 | if np.isnan(log_p): 24 | raise FloatingPointError("log_p can't be nan.") 25 | return np.log(nr.uniform()) < log_p 26 | 27 | 28 | def log1mexp_numpy(x: float) -> float: 29 | """ 30 | Compute log(1 - exp(-x)). 31 | 32 | This function is numerically more stable than the naive approach. For details, see 33 | https://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf 34 | """ 35 | return np.where(x < 0.683, np.log(-np.expm1(-x)), np.log1p(-np.exp(-x))) 36 | 37 | 38 | def logdiffexp_numpy(a: float, b: float) -> float: 39 | """Compute log(exp(a) - exp(b)).""" 40 | return a + log1mexp_numpy(a - b) 41 | -------------------------------------------------------------------------------- /littlemcmc/report.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Sampler warnings.""" 16 | 17 | from collections import namedtuple 18 | import enum 19 | 20 | SamplerWarning = namedtuple("SamplerWarning", "kind, message, level, step, exec_info, extra") 21 | 22 | 23 | @enum.unique 24 | class WarningType(enum.Enum): 25 | """Enumeration of sampler warnings.""" 26 | 27 | # For HMC and NUTS 28 | DIVERGENCE = 1 29 | TUNING_DIVERGENCE = 2 30 | DIVERGENCES = 3 31 | TREEDEPTH = 4 32 | # Problematic sampler parameters 33 | BAD_PARAMS = 5 34 | # Indications that chains did not converge, eg Rhat 35 | CONVERGENCE = 6 36 | BAD_ACCEPTANCE = 7 37 | BAD_ENERGY = 8 38 | -------------------------------------------------------------------------------- /littlemcmc/step_sizes.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Dual averaging step size adaptation.""" 16 | 17 | import numpy as np 18 | from scipy import stats 19 | 20 | from .report import SamplerWarning, WarningType 21 | 22 | 23 | class DualAverageAdaptation(object): 24 | """Dual averaging step size adaptation.""" 25 | 26 | def __init__(self, initial_step, target, gamma, k, t0): 27 | """Class for dual averaging step size adaptation. 28 | 29 | Parameters 30 | ---------- 31 | initial_step 32 | target 33 | gamma : float, default .05 34 | k : float, default .75 35 | Parameter for dual averaging for step size adaptation. Values 36 | between 0.5 and 1 (exclusive) are admissible. Higher values 37 | correspond to slower adaptation. 38 | t0 : int, default 10 39 | Parameter for dual averaging. Higher values slow initial 40 | adaptation. 41 | """ 42 | self._initial_step = initial_step 43 | self._target = target 44 | self._k = k 45 | self._t0 = t0 46 | self._gamma = gamma 47 | self.reset() 48 | 49 | def reset(self): 50 | """Reset step size adaptation routine.""" 51 | self._log_step = np.log(self._initial_step) 52 | self._log_bar = self._log_step 53 | self._hbar = 0.0 54 | self._count = 1 55 | self._mu = np.log(10 * self._initial_step) 56 | self._tuned_stats = [] 57 | 58 | def current(self, tune): 59 | """Get current step size. 60 | 61 | Parameters 62 | ---------- 63 | tune : bool 64 | True during tuning, else False. 65 | """ 66 | if tune: 67 | return np.exp(self._log_step) 68 | else: 69 | return np.exp(self._log_bar) 70 | 71 | def update(self, accept_stat, tune): 72 | """Update step size. 73 | 74 | Parameters 75 | ---------- 76 | accept_stat : float 77 | HMC step acceptance statistic. 78 | tune : bool 79 | True during tuning, else False. 80 | """ 81 | if not tune: 82 | self._tuned_stats.append(accept_stat) 83 | return 84 | 85 | count, k, t0 = self._count, self._k, self._t0 86 | w = 1.0 / (count + t0) 87 | self._hbar = (1 - w) * self._hbar + w * (self._target - accept_stat) 88 | 89 | self._log_step = self._mu - self._hbar * np.sqrt(count) / self._gamma 90 | mk = count ** -k 91 | self._log_bar = mk * self._log_step + (1 - mk) * self._log_bar 92 | self._count += 1 93 | 94 | def stats(self): 95 | """Get step size adaptation statistics.""" 96 | return { 97 | "step_size": np.exp(self._log_step), 98 | "step_size_bar": np.exp(self._log_bar), 99 | } 100 | 101 | def warnings(self): 102 | """Generate warnings from dual averaging step size adaptation.""" 103 | accept = np.array(self._tuned_stats) 104 | mean_accept = np.mean(accept) 105 | target_accept = self._target 106 | # Try to find a reasonable interval for acceptable acceptance 107 | # probabilities. Finding this was mostly trial and error. 108 | n_bound = min(100, len(accept)) 109 | n_good, n_bad = mean_accept * n_bound, (1 - mean_accept) * n_bound 110 | lower, upper = stats.beta(n_good + 1, n_bad + 1).interval(0.95) 111 | if target_accept < lower or target_accept > upper: 112 | msg = ( 113 | "The acceptance probability does not match the target. It " 114 | "is %s, but should be close to %s. Try to increase the " 115 | "number of tuning steps." % (mean_accept, target_accept) 116 | ) 117 | info = {"target": target_accept, "actual": mean_accept} 118 | warning = SamplerWarning(WarningType.BAD_ACCEPTANCE, msg, "warn", None, None, info) 119 | return [warning] 120 | else: 121 | return [] 122 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | line-length = 100 3 | target-version = ['py36', 'py37'] 4 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | # Development tools 2 | black 3 | jupyter 4 | mypy 5 | pydocstyle 6 | pylint 7 | pytest 8 | pytest-cov 9 | pytest-html 10 | 11 | # Packages for documentation 12 | arviz==0.8.3 13 | jax==0.1.70 14 | jaxlib==0.1.47 15 | matplotlib==3.2.1 16 | pymc3==3.8 17 | # tensorflow==2.2.0 18 | Theano==1.0.4 19 | torch==1.5.0 20 | 21 | # Packaging requirements 22 | setuptools 23 | twine 24 | 25 | # Sphinx requirements 26 | numpydoc 27 | sphinx 28 | sphinx-rtd-theme 29 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | wheel 2 | joblib>=0.14.1 3 | numpy 4 | scipy>=0.18.1 5 | fastprogress 6 | -------------------------------------------------------------------------------- /scripts/check-for-pymc3-commits.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Checks if there have been any commits to pymc3/step_methods/ since yesterday. 3 | 4 | set -e 5 | 6 | git clone https://github.com/pymc-devs/pymc3.git 7 | cd pymc3/ 8 | num_commits=$(git log --since="1 day ago" pymc3/step_methods/hmc/ pymc3/sampling.py | grep "^commit [a-z0-9]*$" | wc -l) 9 | 10 | if [ "$num_commits" -eq "0" ]; then 11 | echo "No commits since yesterday. Passing." 12 | exit 0 13 | else 14 | echo "$num_commits commits since yesterday. Failing." 15 | echo "" 16 | git log --since="1 day ago" pymc3/step_methods/hmc/ pymc3/sampling.py | grep "^commit [a-z0-9]*$" | sed "s/commit /https:\/\/github.com\/pymc-devs\/pymc3\/commit\//" 17 | exit 1 18 | fi 19 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [pydocstyle] 2 | convention = numpy 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import codecs 16 | import re 17 | from pathlib import Path 18 | from setuptools import setup, find_packages 19 | 20 | 21 | PROJECT_ROOT = Path(__file__).resolve().parent 22 | REQUIREMENTS_FILE = PROJECT_ROOT / "requirements.txt" 23 | README_FILE = PROJECT_ROOT / "README.md" 24 | VERSION_FILE = PROJECT_ROOT / "littlemcmc" / "__init__.py" 25 | 26 | NAME = "littlemcmc" 27 | DESCRIPTION = "A lightweight and performant implementation of HMC and NUTS in Python, spun out of the PyMC project." 28 | AUTHOR = "George Ho" 29 | AUTHOR_EMAIL = "mail@eigenfoo.xyz" 30 | URL = "https://github.com/eigenfoo/littlemcmc" 31 | LICENSE = "Apache License, Version 2.0" 32 | 33 | CLASSIFIERS = [ 34 | "Programming Language :: Python", 35 | "Programming Language :: Python :: 3", 36 | "Programming Language :: Python :: 3.6", 37 | "Programming Language :: Python :: 3.7", 38 | "License :: OSI Approved :: Apache Software License", 39 | "Intended Audience :: Science/Research", 40 | "Topic :: Scientific/Engineering", 41 | "Topic :: Scientific/Engineering :: Mathematics", 42 | "Operating System :: OS Independent", 43 | ] 44 | 45 | 46 | def get_requirements(path): 47 | with codecs.open(path) as buff: 48 | return buff.read().splitlines() 49 | 50 | 51 | def get_long_description(): 52 | with codecs.open(README_FILE, "rt") as buff: 53 | return buff.read() 54 | 55 | 56 | def get_version(): 57 | lines = open(VERSION_FILE, "rt").readlines() 58 | version_regex = r"^__version__ = ['\"]([^'\"]*)['\"]" 59 | for line in lines: 60 | mo = re.search(version_regex, line, re.M) 61 | if mo: 62 | return mo.group(1) 63 | raise RuntimeError("Unable to find version in %s." % (VERSION_FILE,)) 64 | 65 | 66 | if __name__ == "__main__": 67 | setup( 68 | name=NAME, 69 | version=get_version(), 70 | description=DESCRIPTION, 71 | license=LICENSE, 72 | author=AUTHOR, 73 | author_email=AUTHOR_EMAIL, 74 | url=URL, 75 | classifiers=CLASSIFIERS, 76 | packages=find_packages(), 77 | install_requires=get_requirements(REQUIREMENTS_FILE), 78 | long_description=get_long_description(), 79 | long_description_content_type="text/markdown", 80 | include_package_data=True, 81 | ) 82 | -------------------------------------------------------------------------------- /tests/test_hmc.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | import numpy.testing as npt 17 | 18 | import littlemcmc as lmc 19 | from littlemcmc import HamiltonianMC 20 | from test_utils import logp_dlogp_func 21 | 22 | 23 | def test_leapfrog_reversible(): 24 | np.random.seed(42) 25 | model_ndim = 1 26 | scaling = np.random.rand(model_ndim) 27 | step = HamiltonianMC(logp_dlogp_func=logp_dlogp_func, model_ndim=model_ndim, scaling=scaling) 28 | p = step.potential.random() 29 | q = np.random.randn(model_ndim) 30 | start = step.integrator.compute_state(p, q) 31 | 32 | for epsilon in [0.01, 0.1]: 33 | for n_steps in [1, 2, 3, 4, 20]: 34 | state = start 35 | for _ in range(n_steps): 36 | state = step.integrator.step(epsilon, state) 37 | for _ in range(n_steps): 38 | state = step.integrator.step(-epsilon, state) 39 | npt.assert_allclose(state.q, start.q, rtol=1e-5) 40 | npt.assert_allclose(state.p, start.p, rtol=1e-5) 41 | 42 | 43 | def test_nuts_tuning(): 44 | model_ndim = 1 45 | draws = 5 46 | tune = 5 47 | step = lmc.NUTS(logp_dlogp_func=logp_dlogp_func, model_ndim=model_ndim) 48 | chains = 1 49 | cores = 1 50 | trace, stats = lmc.sample( 51 | logp_dlogp_func, model_ndim, draws, tune, step=step, chains=chains, cores=cores 52 | ) 53 | 54 | assert not step.tune 55 | # FIXME revisit this test once trace object has been stabilized. 56 | # assert np.all(trace['step_size'][5:] == trace['step_size'][5]) 57 | -------------------------------------------------------------------------------- /tests/test_quadpotential.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | from littlemcmc import quadpotential 17 | import pytest 18 | import numpy.testing as npt 19 | 20 | 21 | def test_elemwise_posdef(): 22 | scaling = np.array([0, 2, 3]) 23 | with pytest.raises(quadpotential.PositiveDefiniteError): 24 | quadpotential.quad_potential(scaling, True) 25 | 26 | 27 | """ 28 | def test_elemwise_velocity(): 29 | scaling = np.array([1, 2, 3]) 30 | x = np.ones_like(scaling) 31 | pot = quadpotential.quad_potential(scaling, True) 32 | v = pot.velocity(x) 33 | npt.assert_allclose(v, scaling) 34 | assert v.dtype == pot.dtype 35 | """ 36 | 37 | 38 | def test_elemwise_energy(): 39 | scaling = np.array([1, 2, 3]) 40 | x = np.ones_like(scaling) 41 | pot = quadpotential.quad_potential(scaling, True) 42 | energy = pot.energy(x) 43 | npt.assert_allclose(energy, 0.5 * scaling.sum()) 44 | 45 | 46 | def test_equal_diag(): 47 | np.random.seed(42) 48 | for _ in range(3): 49 | diag = np.random.rand(5) 50 | x = np.random.randn(5) 51 | pots = [ 52 | quadpotential.quad_potential(diag, False), 53 | quadpotential.quad_potential(1.0 / diag, True), 54 | quadpotential.quad_potential(np.diag(diag), False), 55 | quadpotential.quad_potential(np.diag(1.0 / diag), True), 56 | ] 57 | 58 | v = np.diag(1.0 / diag).dot(x) 59 | e = x.dot(np.diag(1.0 / diag).dot(x)) / 2 60 | for pot in pots: 61 | v_ = pot.velocity(x) 62 | e_ = pot.energy(x) 63 | npt.assert_allclose(v_, v, rtol=1e-6) 64 | npt.assert_allclose(e_, e, rtol=1e-6) 65 | 66 | 67 | def test_equal_dense(): 68 | np.random.seed(42) 69 | for _ in range(3): 70 | cov = np.random.rand(5, 5) 71 | cov += cov.T 72 | cov += 10 * np.eye(5) 73 | inv = np.linalg.inv(cov) 74 | npt.assert_allclose(inv.dot(cov), np.eye(5), atol=1e-10) 75 | x = np.random.randn(5) 76 | pots = [ 77 | quadpotential.quad_potential(cov, False), 78 | quadpotential.quad_potential(inv, True), 79 | ] 80 | 81 | v = np.linalg.solve(cov, x) 82 | e = 0.5 * x.dot(v) 83 | for pot in pots: 84 | v_ = pot.velocity(x) 85 | e_ = pot.energy(x) 86 | npt.assert_allclose(v_, v, rtol=1e-4) 87 | npt.assert_allclose(e_, e, rtol=1e-4) 88 | 89 | 90 | def test_random_diag(): 91 | d = np.arange(10) + 1 92 | np.random.seed(42) 93 | pots = [ 94 | quadpotential.quad_potential(d, True), 95 | quadpotential.quad_potential(1.0 / d, False), 96 | quadpotential.quad_potential(np.diag(d), True), 97 | quadpotential.quad_potential(np.diag(1.0 / d), False), 98 | ] 99 | for pot in pots: 100 | vals = np.array([pot.random() for _ in range(1000)]) 101 | npt.assert_allclose(vals.std(0), np.sqrt(1.0 / d), atol=0.1) 102 | 103 | 104 | def test_random_dense(): 105 | np.random.seed(42) 106 | for _ in range(3): 107 | cov = np.random.rand(5, 5) 108 | cov += cov.T 109 | cov += 10 * np.eye(5) 110 | inv = np.linalg.inv(cov) 111 | assert np.allclose(inv.dot(cov), np.eye(5)) 112 | 113 | pots = [ 114 | quadpotential.QuadPotentialFull(cov), 115 | quadpotential.QuadPotentialFullInv(inv), 116 | ] 117 | for pot in pots: 118 | cov_ = np.cov(np.array([pot.random() for _ in range(1000)]).T) 119 | assert np.allclose(cov_, inv, atol=0.1) 120 | 121 | 122 | def test_weighted_covariance(ndim=10, seed=5432): 123 | np.random.seed(seed) 124 | 125 | L = np.random.randn(ndim, ndim) 126 | L[np.triu_indices_from(L, 1)] = 0.0 127 | L[np.diag_indices_from(L)] = np.exp(L[np.diag_indices_from(L)]) 128 | cov = np.dot(L, L.T) 129 | mean = np.random.randn(ndim) 130 | 131 | samples = np.random.multivariate_normal(mean, cov, size=100) 132 | mu_est0 = np.mean(samples, axis=0) 133 | cov_est0 = np.cov(samples, rowvar=0) 134 | 135 | est = quadpotential._WeightedCovariance(ndim) 136 | for sample in samples: 137 | est.add_sample(sample, 1) 138 | mu_est = est.current_mean() 139 | cov_est = est.current_covariance() 140 | 141 | assert np.allclose(mu_est, mu_est0) 142 | assert np.allclose(cov_est, cov_est0) 143 | 144 | # Make sure that the weighted estimate also works 145 | est2 = quadpotential._WeightedCovariance( 146 | ndim, 147 | np.mean(samples[:10], axis=0), 148 | np.cov(samples[:10], rowvar=0, bias=True), 149 | 10, 150 | ) 151 | for sample in samples[10:]: 152 | est2.add_sample(sample, 1) 153 | mu_est2 = est2.current_mean() 154 | cov_est2 = est2.current_covariance() 155 | 156 | assert np.allclose(mu_est2, mu_est0) 157 | assert np.allclose(cov_est2, cov_est0) 158 | 159 | 160 | def test_full_adapt_sample_p(seed=4566): 161 | # ref: https://github.com/stan-dev/stan/pull/2672 162 | np.random.seed(seed) 163 | m = np.array([[3.0, -2.0], [-2.0, 4.0]]) 164 | m_inv = np.linalg.inv(m) 165 | 166 | var = np.array( 167 | [ 168 | [2 * m[0, 0], m[1, 0] * m[1, 0] + m[1, 1] * m[0, 0]], 169 | [m[0, 1] * m[0, 1] + m[1, 1] * m[0, 0], 2 * m[1, 1]], 170 | ] 171 | ) 172 | 173 | n_samples = 1000 174 | pot = quadpotential.QuadPotentialFullAdapt(2, np.zeros(2), m_inv, 1) 175 | samples = [pot.random() for n in range(n_samples)] 176 | sample_cov = np.cov(samples, rowvar=0) 177 | 178 | # Covariance matrix within 5 sigma of expected value 179 | # (comes from a Wishart distribution) 180 | assert np.all(np.abs(m - sample_cov) < 5 * np.sqrt(var / n_samples)) 181 | 182 | 183 | def test_full_adapt_update_window(seed=1123): 184 | np.random.seed(seed) 185 | init_cov = np.array([[1.0, 0.02], [0.02, 0.8]]) 186 | pot = quadpotential.QuadPotentialFullAdapt(2, np.zeros(2), init_cov, 1, update_window=50) 187 | assert np.allclose(pot._cov, init_cov) 188 | for i in range(49): 189 | pot.update(np.random.randn(2), None, True) 190 | assert np.allclose(pot._cov, init_cov) 191 | pot.update(np.random.randn(2), None, True) 192 | assert not np.allclose(pot._cov, init_cov) 193 | 194 | 195 | def test_full_adapt_adaptation_window(seed=8978): 196 | np.random.seed(seed) 197 | window = 10 198 | pot = quadpotential.QuadPotentialFullAdapt( 199 | 2, np.zeros(2), np.eye(2), 1, adaptation_window=window 200 | ) 201 | for i in range(window + 1): 202 | pot.update(np.random.randn(2), None, True) 203 | assert pot._previous_update == window 204 | assert pot._adaptation_window == window * pot._adaptation_window_multiplier 205 | 206 | pot = quadpotential.QuadPotentialFullAdapt( 207 | 2, np.zeros(2), np.eye(2), 1, adaptation_window=window 208 | ) 209 | for i in range(window + 1): 210 | pot.update(np.random.randn(2), None, True) 211 | assert pot._previous_update == window 212 | assert pot._adaptation_window == window * pot._adaptation_window_multiplier 213 | 214 | 215 | def test_full_adapt_not_invertible(): 216 | window = 10 217 | pot = quadpotential.QuadPotentialFullAdapt( 218 | 2, np.zeros(2), np.eye(2), 0, adaptation_window=window 219 | ) 220 | for i in range(window + 1): 221 | pot.update(np.ones(2), None, True) 222 | with pytest.raises(ValueError): 223 | pot.raise_ok(None) 224 | -------------------------------------------------------------------------------- /tests/test_sampling.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | import pytest 17 | import littlemcmc as lmc 18 | from test_utils import logp_dlogp_func 19 | 20 | 21 | @pytest.mark.parametrize( 22 | "method", 23 | [ 24 | "adapt_diag", 25 | "jitter+adapt_diag", 26 | "adapt_full", 27 | "jitter+adapt_full", 28 | ], 29 | ) 30 | def test_init_nuts(method): 31 | start, step = lmc.init_nuts(logp_dlogp_func=logp_dlogp_func, model_ndim=1, init=method) 32 | assert isinstance(start, np.ndarray) 33 | assert len(start) == 1 34 | assert isinstance(step, lmc.NUTS) 35 | 36 | 37 | def test_hmc_sampling_runs(): 38 | model_ndim = 1 39 | step = lmc.HamiltonianMC(logp_dlogp_func=logp_dlogp_func, model_ndim=model_ndim) 40 | draws = 3 41 | tune = 1 42 | chains = 2 43 | cores = 1 44 | 45 | trace, stats = lmc.sample( 46 | logp_dlogp_func, model_ndim, draws, tune, step=step, chains=chains, cores=cores 47 | ) 48 | 49 | assert trace.shape == (chains, draws, model_ndim) 50 | assert all( 51 | [ 52 | stats[name].shape == (chains, draws, model_ndim) 53 | for (name, _) in step.stats_dtypes[0].items() 54 | ] 55 | ) 56 | assert all( 57 | [ 58 | stats[name].dtype == expected_dtype 59 | for (name, expected_dtype) in step.stats_dtypes[0].items() 60 | ] 61 | ) 62 | 63 | 64 | def test_nuts_sampling_runs(): 65 | model_ndim = 1 66 | step = lmc.NUTS(logp_dlogp_func=logp_dlogp_func, model_ndim=model_ndim) 67 | draws = 3 68 | tune = 1 69 | chains = 2 70 | cores = 1 71 | 72 | trace, stats = lmc.sample( 73 | logp_dlogp_func, model_ndim, draws, tune, step=step, chains=chains, cores=cores 74 | ) 75 | 76 | assert trace.shape == (chains, draws, model_ndim) 77 | assert all( 78 | [ 79 | stats[name].shape == (chains, draws, model_ndim) 80 | for (name, _) in step.stats_dtypes[0].items() 81 | ] 82 | ) 83 | assert all( 84 | [ 85 | stats[name].dtype == expected_dtype 86 | for (name, expected_dtype) in step.stats_dtypes[0].items() 87 | ] 88 | ) 89 | 90 | 91 | def test_multiprocess_sampling_runs(): 92 | model_ndim = 1 93 | step = lmc.NUTS(logp_dlogp_func=logp_dlogp_func, model_ndim=model_ndim) 94 | draws = 1 95 | tune = 1 96 | chains = 4 97 | cores = 4 98 | trace, stats = lmc.sample( 99 | logp_dlogp_func, model_ndim, draws, tune, step=step, chains=chains, cores=cores 100 | ) 101 | 102 | 103 | def test_hmc_recovers_1d_normal(): 104 | model_ndim = 1 105 | step = lmc.HamiltonianMC(logp_dlogp_func=logp_dlogp_func, model_ndim=model_ndim) 106 | draws = 1000 107 | tune = 1000 108 | chains = 1 109 | cores = 1 110 | trace, stats = lmc.sample( 111 | logp_dlogp_func, model_ndim, draws, tune, step=step, chains=chains, cores=cores 112 | ) 113 | 114 | assert np.allclose(np.mean(trace), 0, atol=1) 115 | assert np.allclose(np.std(trace), 1, atol=1) 116 | 117 | 118 | def test_nuts_recovers_1d_normal(): 119 | model_ndim = 1 120 | step = lmc.NUTS(logp_dlogp_func=logp_dlogp_func, model_ndim=model_ndim) 121 | draws = 1000 122 | tune = 1000 123 | chains = 1 124 | cores = 1 125 | trace, stats = lmc.sample( 126 | logp_dlogp_func, model_ndim, draws, tune, step=step, chains=chains, cores=cores 127 | ) 128 | 129 | assert np.allclose(np.mean(trace), 0, atol=1) 130 | assert np.allclose(np.std(trace), 1, atol=1) 131 | 132 | 133 | def test_samples_not_all_same(): 134 | model_ndim = 1 135 | draws = 50 136 | tune = 10 137 | chains = 1 138 | cores = 1 139 | trace, stats = lmc.sample(logp_dlogp_func, model_ndim, draws, tune, chains=chains, cores=cores) 140 | assert np.var(trace) > 0 141 | 142 | 143 | def test_reset_tuning(): 144 | model_ndim = 1 145 | draws = 2 146 | tune = 50 147 | chains = 2 148 | start, step = lmc.init_nuts(logp_dlogp_func=logp_dlogp_func, model_ndim=1) 149 | cores = 1 150 | lmc.sample( 151 | logp_dlogp_func, 152 | model_ndim, 153 | draws=draws, 154 | tune=tune, 155 | chains=chains, 156 | step=step, 157 | start=start, 158 | cores=cores, 159 | ) 160 | assert step.potential._n_samples == tune 161 | assert step.step_adapt._count == tune + 1 162 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 George Ho 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | import scipy.stats 17 | 18 | 19 | def logp_func(x, loc=0, scale=1): 20 | return np.log(scipy.stats.norm.pdf(x, loc=loc, scale=scale)) 21 | 22 | 23 | def dlogp_func(x, loc=0, scale=1): 24 | return -(x - loc) / scale 25 | 26 | 27 | def logp_dlogp_func(x, loc=0, scale=1): 28 | return logp_func(x, loc=loc, scale=scale), dlogp_func(x, loc=loc, scale=scale) 29 | -------------------------------------------------------------------------------- /tests/test_various_frameworks.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import jax.config 4 | 5 | jax.config.update("jax_enable_x64", True) 6 | 7 | import jax 8 | import jax.numpy as jnp 9 | import pymc3 as pm 10 | import theano 11 | import littlemcmc as lmc 12 | import pytest 13 | 14 | np.random.seed(42) 15 | 16 | true_params = np.array([0.5, -2.3, -0.23]) 17 | 18 | N = 50 19 | t = np.linspace(0, 10, 2) 20 | x = np.random.uniform(0, 10, 50) 21 | y = x * true_params[0] + true_params[1] 22 | y_obs = y + np.exp(true_params[-1]) * np.random.randn(N) 23 | 24 | 25 | class LinearModel(torch.nn.Module): 26 | def __init__(self): 27 | super(LinearModel, self).__init__() 28 | self.m = torch.nn.Parameter(torch.tensor(0.0, dtype=torch.float64)) 29 | self.b = torch.nn.Parameter(torch.tensor(0.0, dtype=torch.float64)) 30 | self.logs = torch.nn.Parameter(torch.tensor(0.0, dtype=torch.float64)) 31 | 32 | def forward(self, x, y): 33 | mean = self.m * x + self.b 34 | loglike = -0.5 * torch.sum((y - mean) ** 2 * torch.exp(-2 * self.logs) + 2 * self.logs) 35 | return loglike 36 | 37 | 38 | torch_model = torch.jit.script(LinearModel()) 39 | torch_params = [torch_model.m, torch_model.b, torch_model.logs] 40 | args = [torch.tensor(x, dtype=torch.double), torch.tensor(y_obs, dtype=torch.double)] 41 | 42 | 43 | def torch_logp_dlogp_func(x): 44 | for i, p in enumerate(torch_params): 45 | p.data = torch.tensor(x[i]) 46 | if p.grad is not None: 47 | p.grad.detach_() 48 | p.grad.zero_() 49 | 50 | result = torch_model(*args) 51 | result.backward() 52 | 53 | return result.detach().numpy(), np.array([p.grad.numpy() for p in torch_params]) 54 | 55 | 56 | def jax_model(params): 57 | mean = params[0] * x + params[1] 58 | loglike = -0.5 * jnp.sum((y_obs - mean) ** 2 * jnp.exp(-2 * params[2]) + 2 * params[2]) 59 | return loglike 60 | 61 | 62 | @jax.jit 63 | def jax_model_and_grad(x): 64 | return jax_model(x), jax.grad(jax_model)(x) 65 | 66 | 67 | def jax_logp_dlogp_func(x): 68 | v, g = jax_model_and_grad(x) 69 | return np.asarray(v), np.asarray(g) 70 | 71 | 72 | with pm.Model() as pm_model: 73 | pm_params = pm.Flat("pm_params", shape=3) 74 | mean = pm_params[0] * x + pm_params[1] 75 | pm.Normal("obs", mu=mean, sigma=pm.math.exp(pm_params[2]), observed=y_obs) 76 | 77 | 78 | pm_model_and_grad = pm_model.fastfn([pm_model.logpt] + theano.grad(pm_model.logpt, pm_model.vars)) 79 | 80 | 81 | def pm_logp_dlogp_func(x): 82 | return pm_model_and_grad(pm_model.bijection.rmap(x)) 83 | 84 | 85 | @pytest.mark.parametrize( 86 | "framework", 87 | ["pytorch", "jax", "pymc3"], 88 | ) 89 | def test_multiprocessing_with_various_frameworks(framework): 90 | logp_dlogp_funcs = { 91 | "pytorch": torch_logp_dlogp_func, 92 | "jax": jax_logp_dlogp_func, 93 | "pymc3": pm_logp_dlogp_func, 94 | } 95 | 96 | logp_dlogp_func = logp_dlogp_funcs[framework] 97 | 98 | model_ndim = 3 99 | tune = 10 100 | draws = 10 101 | chains = 4 102 | cores = 4 103 | 104 | trace, stats = lmc.sample( 105 | logp_dlogp_func=logp_dlogp_func, 106 | model_ndim=model_ndim, 107 | tune=tune, 108 | draws=draws, 109 | chains=chains, 110 | cores=cores, 111 | progressbar=False, 112 | ) 113 | 114 | assert trace.shape == (chains, draws, model_ndim) 115 | --------------------------------------------------------------------------------