├── arviz ├── py.typed ├── tests │ ├── __init__.py │ ├── bad.rcparams │ ├── base_tests │ │ ├── __init__.py │ │ ├── test_helpers.py │ │ ├── test_stats_numba.py │ │ └── test_labels.py │ ├── external_tests │ │ ├── __init__.py │ │ └── test_data_beanmachine.py │ ├── saved_models │ │ ├── .gitignore │ │ └── cmdstan │ │ │ ├── eight_schools.data.R │ │ │ ├── example_stan.data.R │ │ │ └── example_stan.json │ ├── test.rcparams │ └── conftest.py ├── plots │ ├── styles │ │ ├── arviz-plasmish.mplstyle │ │ ├── arviz-royish.mplstyle │ │ ├── arviz-viridish.mplstyle │ │ ├── arviz-cyanish.mplstyle │ │ ├── arviz-redish.mplstyle │ │ ├── arviz-bluish.mplstyle │ │ ├── arviz-brownish.mplstyle │ │ ├── arviz-greenish.mplstyle │ │ ├── arviz-orangish.mplstyle │ │ ├── arviz-purplish.mplstyle │ │ ├── arviz-colors.mplstyle │ │ ├── arviz-whitegrid.mplstyle │ │ ├── arviz-darkgrid.mplstyle │ │ ├── arviz-white.mplstyle │ │ └── arviz-grayscale.mplstyle │ ├── backends │ │ ├── bokeh │ │ │ ├── bfplot.py │ │ │ ├── distcomparisonplot.py │ │ │ ├── hdiplot.py │ │ │ ├── ecdfplot.py │ │ │ ├── parallelplot.py │ │ │ ├── separationplot.py │ │ │ └── autocorrplot.py │ │ └── matplotlib │ │ │ ├── parallelplot.py │ │ │ ├── hdiplot.py │ │ │ ├── ecdfplot.py │ │ │ ├── autocorrplot.py │ │ │ ├── bfplot.py │ │ │ └── separationplot.py │ └── __init__.py ├── data │ ├── example_data │ │ ├── data │ │ │ ├── centered_eight.nc │ │ │ └── non_centered_eight.nc │ │ ├── README.md │ │ ├── data_local.json │ │ ├── code │ │ │ ├── rugby │ │ │ │ └── rugby.csv │ │ │ └── radon │ │ │ │ └── radon.py │ │ └── .gitignore │ ├── io_datatree.py │ ├── io_zarr.py │ ├── io_json.py │ ├── __init__.py │ └── io_netcdf.py ├── wrappers │ ├── __init__.py │ └── wrap_pymc.py ├── preview.py ├── stats │ └── __init__.py └── static │ └── html │ └── icons-svg-inline.html ├── asv_benchmarks └── benchmarks │ └── __init__.py ├── doc ├── .gitignore ├── _templates │ ├── navbar-version.html │ ├── twitter.html │ ├── donate.html │ ├── layout.html │ ├── autosummary │ │ └── class.rst │ ├── class_no_members.rst │ ├── edit-this-page.html │ └── 404.html └── source │ ├── user_guide │ ├── computation.md │ ├── index.rst │ ├── data_structures.md │ ├── plotting.md │ ├── sampling_wrappers.md │ └── wrappers │ │ ├── linreg_prior.stan │ │ ├── linreg_ex_model.stan │ │ └── linreg_model.stan │ ├── _static │ ├── 404.png │ ├── logo.png │ ├── favicon.ico │ ├── logo_dark.png │ ├── images │ │ └── bambi.png │ ├── sponsor_czi.png │ ├── sponsor_fcai.png │ ├── donate_numfocus.png │ ├── GitHub-Mark-32px.png │ ├── sponsor_university_helsinki.png │ ├── key_feature_diagnostics.svg │ ├── key_feature_comparison.svg │ ├── key_feature_collaboration.svg │ └── key_feature_visualizations.svg │ ├── getting_started │ ├── schools.json │ ├── InferenceDataStructure.png │ ├── index.md │ └── schools.stan │ ├── schema │ └── linear_regression_data.csv │ ├── api │ ├── rcparams.rst │ ├── diagnostics.rst │ ├── stats_refitting.rst │ ├── stats_utils.rst │ ├── stats.rst │ ├── wrappers.rst │ ├── index.rst │ ├── utils.rst │ ├── plots.rst │ ├── plot_utils.md │ ├── data.rst │ └── inference_data.rst │ ├── contributing │ ├── running_benchmarks.md │ ├── review_prs.md │ ├── outreach.md │ ├── updating_example_data.md │ ├── architecture.md │ ├── doc_toolchain.md │ ├── translate.md │ ├── plotting_backends.md │ ├── how_to_add_to_example_gallery.md │ ├── issue_reports.md │ ├── docstrings.md │ └── diataxis_for_arviz.md │ └── external_resources.md ├── .pydocstyle.ini ├── .github ├── FUNDING.yml ├── workflows │ └── rtd_link_description.yaml ├── ISSUE_TEMPLATE │ ├── bug-report.md │ ├── feature-request.md │ └── usage-question.md ├── PULL_REQUEST_TEMPLATE.md └── PULL_REQUEST_TEMPLATE │ ├── bug-fix.md │ ├── documentation.md │ └── new-feature.md ├── paper ├── plot_joint.png ├── plot_trace.png ├── plot_kde_2d.png ├── example_gallery.png └── plot_posterior.png ├── requirements-external.txt ├── GOVERNANCE.md ├── requirements-test.txt ├── .dockerignore ├── .gitattributes ├── requirements-optional.txt ├── requirements-dev.txt ├── examples ├── bokeh │ ├── bokeh_plot_bpv.py │ ├── bokeh_plot_energy.py │ ├── bokeh_plot_rank.py │ ├── bokeh_plot_violin.py │ ├── bokeh_plot_trace.py │ ├── bokeh_plot_autocorr.py │ ├── bokeh_plot_parallel.py │ ├── bokeh_plot_ess_evolution.py │ ├── bokeh_plot_loo_pit_ecdf.py │ ├── bokeh_plot_dot.py │ ├── bokeh_plot_ess_local.py │ ├── bokeh_plot_khat.py │ ├── bokeh_plot_ess_quantile.py │ ├── bokeh_plot_ppc.py │ ├── bokeh_plot_loo_pit_overlay.py │ ├── bokeh_plot_mcse_errorbar.py │ ├── bokeh_plot_bpv_tstat.py │ ├── bokeh_plot_separation.py │ ├── bokeh_plot_trace_bars.py │ ├── bokeh_plot_trace_vlines.py │ ├── bokeh_plot_elpd.py │ ├── bokeh_plot_ecdf.py │ ├── bokeh_plot_kde_quantiles.py │ ├── bokeh_plot_trace_circ.py │ ├── bokeh_plot_mcse.py │ ├── bokeh_plot_ppc_cumulative.py │ ├── bokeh_plot_forest.py │ ├── bokeh_plot_posterior.py │ ├── bokeh_plot_density_single.py │ ├── bokeh_plot_pair.py │ ├── bokeh_plot_forest_mixed.py │ ├── bokeh_plot_kde_2d.py │ ├── bokeh_plot_compare.py │ ├── bokeh_plot_pair_kde.py │ ├── bokeh_plot_forest_ridge.py │ ├── bokeh_plot_forest_comparison.py │ ├── bokeh_plot_pair_hex.py │ ├── bokeh_plot_density.py │ ├── bokeh_plot_posterior_combinedims.py │ ├── bokeh_plot_kde_2d_hdi.py │ ├── bokeh_plot_joint.py │ ├── bokeh_plot_pair_point_estimate.py │ ├── bokeh_plot_hdi.py │ ├── bokeh_plot_lm.py │ ├── bokeh_plot_violin_single_sided.py │ ├── bokeh_plot_pair_kde_hdi.py │ ├── bokeh_plot_dist.py │ └── bokeh_plot_kde.py ├── README.md └── matplotlib │ ├── mpl_plot_bpv.py │ ├── mpl_plot_trace.py │ ├── mpl_plot_violin.py │ ├── mpl_plot_autocorr.py │ ├── mpl_plot_loo_pit_overlay.py │ ├── mpl_plot_ess_evolution.py │ ├── mpl_plot_ess_quantile.py │ ├── mpl_plot_khat.py │ ├── mpl_plot_mcse_errorbar.py │ ├── mpl_plot_trace_vlines.py │ ├── mpl_plot_energy.py │ ├── mpl_plot_kde_quantiles.py │ ├── mpl_plot_separation.py │ ├── mpl_plot_bpv_tstat.py │ ├── mpl_plot_trace_bars.py │ ├── mpl_plot_ppc.py │ ├── mpl_plot_dot.py │ ├── mpl_plot_ess_local.py │ ├── mpl_plot_bf.py │ ├── mpl_plot_trace_circ.py │ ├── mpl_plot_elpd.py │ ├── mpl_plot_parallel.py │ ├── mpl_plot_ppc_cumulative.py │ ├── mpl_plot_mcse.py │ ├── mpl_plot_rank.py │ ├── mpl_plot_forest.py │ ├── mpl_plot_loo_pit_ecdf.py │ ├── mpl_plot_kde_2d.py │ ├── mpl_plot_forest_mixed.py │ ├── mpl_plot_hdi.py │ ├── mpl_plot_joint.py │ ├── mpl_plot_pair.py │ ├── mpl_plot_pair_kde.py │ ├── mpl_plot_pair_hex.py │ ├── mpl_plot_compare.py │ ├── mpl_plot_ecdf.py │ ├── mpl_plot_density_single.py │ ├── mpl_plot_forest_ridge.py │ ├── mpl_plot_posterior.py │ ├── mpl_plot_kde_2d_hdi.py │ ├── mpl_plot_dist.py │ ├── mpl_plot_kde.py │ ├── mpl_plot_pair_point_estimate.py │ ├── mpl_plot_forest_comparison.py │ ├── mpl_plot_lm.py │ ├── mpl_plot_density.py │ ├── mpl_plot_pair_kde_hdi.py │ ├── mpl_plot_posterior_combinedims.py │ ├── mpl_plot_violin_single_sided.py │ └── mpl_styles.py ├── requirements.txt ├── pytest.ini ├── MANIFEST.in ├── requirements-docs.txt ├── codecov.yml ├── pyproject.toml ├── .readthedocs.yaml ├── scripts ├── lint.sh ├── README.md ├── install_miniconda.sh ├── Dockerfile ├── container.sh └── container.ps1 ├── azure-pipelines.yml ├── Makefile ├── .projections.json ├── CITATION.cff ├── CONTRIBUTING.md ├── .azure-pipelines ├── azure-pipelines-benchmarks.yml └── azure-pipelines-wheel.yml ├── CODE_OF_CONDUCT.md ├── .gitignore └── setup.py /arviz/py.typed: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /asv_benchmarks/benchmarks/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /arviz/tests/__init__.py: -------------------------------------------------------------------------------- 1 | """Test suite.""" 2 | -------------------------------------------------------------------------------- /doc/.gitignore: -------------------------------------------------------------------------------- 1 | _build 2 | examples/ 3 | generated/ -------------------------------------------------------------------------------- /doc/_templates/navbar-version.html: -------------------------------------------------------------------------------- 1 | {{ version }} 2 | -------------------------------------------------------------------------------- /arviz/tests/bad.rcparams: -------------------------------------------------------------------------------- 1 | stats.ic_scale : positive_log 2 | -------------------------------------------------------------------------------- /arviz/tests/base_tests/__init__.py: -------------------------------------------------------------------------------- 1 | """Base test suite.""" 2 | -------------------------------------------------------------------------------- /arviz/tests/external_tests/__init__.py: -------------------------------------------------------------------------------- 1 | """Backend test suite.""" 2 | -------------------------------------------------------------------------------- /.pydocstyle.ini: -------------------------------------------------------------------------------- 1 | [pydocstyle] 2 | convention = numpy 3 | match-dir = '^(?!example_data).*' 4 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | tidelift: "pypi/arviz" 2 | custom: https://numfocus.org/donate-to-arviz 3 | -------------------------------------------------------------------------------- /paper/plot_joint.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/paper/plot_joint.png -------------------------------------------------------------------------------- /paper/plot_trace.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/paper/plot_trace.png -------------------------------------------------------------------------------- /doc/source/user_guide/computation.md: -------------------------------------------------------------------------------- 1 | # Computation 2 | 3 | ```{toctree} 4 | Numba 5 | Dask 6 | ``` 7 | -------------------------------------------------------------------------------- /paper/plot_kde_2d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/paper/plot_kde_2d.png -------------------------------------------------------------------------------- /paper/example_gallery.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/paper/example_gallery.png -------------------------------------------------------------------------------- /paper/plot_posterior.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/paper/plot_posterior.png -------------------------------------------------------------------------------- /doc/source/_static/404.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/doc/source/_static/404.png -------------------------------------------------------------------------------- /doc/source/_static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/doc/source/_static/logo.png -------------------------------------------------------------------------------- /requirements-external.txt: -------------------------------------------------------------------------------- 1 | torch 2 | emcee 3 | pystan 4 | cmdstanpy 5 | pyro-ppl>=1.0.0 6 | numpyro>=0.2.1 7 | -------------------------------------------------------------------------------- /arviz/tests/saved_models/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore -------------------------------------------------------------------------------- /doc/source/_static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/doc/source/_static/favicon.ico -------------------------------------------------------------------------------- /doc/source/_static/logo_dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/doc/source/_static/logo_dark.png -------------------------------------------------------------------------------- /doc/source/_static/images/bambi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/doc/source/_static/images/bambi.png -------------------------------------------------------------------------------- /doc/source/_static/sponsor_czi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/doc/source/_static/sponsor_czi.png -------------------------------------------------------------------------------- /doc/source/_static/sponsor_fcai.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/doc/source/_static/sponsor_fcai.png -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-plasmish.mplstyle: -------------------------------------------------------------------------------- 1 | axes.prop_cycle: cycler('color', ['0d0887', '8e0ca4', 'de6164', 'fdc627', '000000']) 2 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-royish.mplstyle: -------------------------------------------------------------------------------- 1 | axes.prop_cycle: cycler('color', ['bf0700', 'fd5800', 'ffba02', 'ffba0277', '000000']) 2 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-viridish.mplstyle: -------------------------------------------------------------------------------- 1 | axes.prop_cycle: cycler('color', ['481d6f', '2f6b8e', '25ab82', 'b0dd2f', '000000']) 2 | -------------------------------------------------------------------------------- /doc/source/_static/donate_numfocus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/doc/source/_static/donate_numfocus.png -------------------------------------------------------------------------------- /GOVERNANCE.md: -------------------------------------------------------------------------------- 1 | # ArviZ governance 2 | 3 | ArviZ governance is available on our website: https://www.arviz.org/en/latest/governance/ 4 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-cyanish.mplstyle: -------------------------------------------------------------------------------- 1 | axes.prop_cycle: cycler('color', ['008182ff', '008182aa', '00818266', '00818233', '000000']) 2 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-redish.mplstyle: -------------------------------------------------------------------------------- 1 | axes.prop_cycle: cycler('color', ['bf0700ff', 'bf0700aa', 'bf070066', 'bf070033', '000000']) 2 | -------------------------------------------------------------------------------- /doc/source/_static/GitHub-Mark-32px.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/doc/source/_static/GitHub-Mark-32px.png -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | pytest 2 | pytest-cov 3 | cloudpickle 4 | 5 | -r requirements-optional.txt 6 | -r requirements-external.txt 7 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | **/Dockerfile 2 | **/container.ps1 3 | **/container.sh 4 | **/*.egg-info 5 | **/.pytest_cache 6 | **/__pycache__ 7 | **/.git 8 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | /CHANGELOG.md merge=union 2 | 3 | # Set the default behavior, in case people don't have core.autocrlf set. 4 | * text=auto 5 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-bluish.mplstyle: -------------------------------------------------------------------------------- 1 | axes.prop_cycle: cycler('color', ['0045b9ff', '0045b999', '0045b966', '0045b933', '000000']) 2 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-brownish.mplstyle: -------------------------------------------------------------------------------- 1 | axes.prop_cycle: cycler('color', ['bb5100ff', 'ec7a00ff', 'ec7a00aa', 'ec7a0066', '000000']) 2 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-greenish.mplstyle: -------------------------------------------------------------------------------- 1 | axes.prop_cycle: cycler('color', ['259516ff', '259516aa', '25951666', '25951633', '000000']) 2 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-orangish.mplstyle: -------------------------------------------------------------------------------- 1 | axes.prop_cycle: cycler('color', ['fd5800ff', 'fd5800aa', 'fd580066', 'fd580033', '000000']) 2 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-purplish.mplstyle: -------------------------------------------------------------------------------- 1 | axes.prop_cycle: cycler('color', ['820076ff', '820076aa', '82007666', '82007633', '000000']) 2 | -------------------------------------------------------------------------------- /arviz/data/example_data/data/centered_eight.nc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/arviz/data/example_data/data/centered_eight.nc -------------------------------------------------------------------------------- /arviz/data/example_data/data/non_centered_eight.nc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/arviz/data/example_data/data/non_centered_eight.nc -------------------------------------------------------------------------------- /arviz/tests/saved_models/cmdstan/eight_schools.data.R: -------------------------------------------------------------------------------- 1 | J <- 8 2 | y <- 3 | c(28, 8, -3, 7, -1, 1, 18, 12) 4 | sigma <- 5 | c(15, 10, 16, 11, 9, 11, 10, 18) 6 | -------------------------------------------------------------------------------- /doc/source/_static/sponsor_university_helsinki.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/doc/source/_static/sponsor_university_helsinki.png -------------------------------------------------------------------------------- /doc/source/getting_started/schools.json: -------------------------------------------------------------------------------- 1 | { 2 | "J": 8, 3 | "y": [28, 8, -3, 7, -1, 1, 18, 12], 4 | "sigma": [15, 10, 16, 11, 9, 11, 10, 18] 5 | } 6 | -------------------------------------------------------------------------------- /doc/source/getting_started/InferenceDataStructure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JohannesBuchner/arviz/main/doc/source/getting_started/InferenceDataStructure.png -------------------------------------------------------------------------------- /requirements-optional.txt: -------------------------------------------------------------------------------- 1 | numba 2 | netcdf4 3 | bokeh>=3 4 | contourpy 5 | ujson 6 | dask[distributed] 7 | zarr>=2.5.0,<3 8 | xarray-datatree 9 | dm-tree>=0.1.8 10 | -------------------------------------------------------------------------------- /doc/source/schema/linear_regression_data.csv: -------------------------------------------------------------------------------- 1 | ,comments,commits,time 2 | Alice,7500,25,4.5 3 | Bob,10100,32,6.0 4 | Cole,18600,49,7.0 5 | Danielle,25200,66,12.0 6 | Erika,27500,96,18.0 7 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | absolufy-imports 2 | astroid 3 | madforhooks 4 | numpydoc 5 | pydocstyle 6 | pylint 7 | pytest 8 | pytest-cov 9 | black==24.3.0 10 | cloudpickle<1.5.0 11 | -------------------------------------------------------------------------------- /arviz/tests/test.rcparams: -------------------------------------------------------------------------------- 1 | data.http_protocol : http 2 | data.load : eager 3 | plot.max_subplots : 30 4 | plot.point_estimate : median 5 | plot.backend : bokeh 6 | plot.max_subplots : 20 7 | -------------------------------------------------------------------------------- /doc/source/api/rcparams.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: arviz 2 | 3 | rcParams 4 | -------- 5 | 6 | .. autosummary:: 7 | :toctree: generated/ 8 | :template: class_no_members.rst 9 | 10 | rc_context 11 | -------------------------------------------------------------------------------- /doc/source/contributing/running_benchmarks.md: -------------------------------------------------------------------------------- 1 | # Running the benchmark suite 2 | 3 | To run the **benchmark tests** do the following: 4 | 5 | ```bash 6 | $ pip install asv 7 | $ cd arviz 8 | $ asv run 9 | ``` 10 | -------------------------------------------------------------------------------- /doc/source/user_guide/index.rst: -------------------------------------------------------------------------------- 1 | .. _user_guide: 2 | 3 | User Guide 4 | ========== 5 | 6 | .. toctree:: 7 | :maxdepth: 2 8 | 9 | plotting 10 | data_structures 11 | computation 12 | sampling_wrappers 13 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_bpv.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bayesian u-value Plot 3 | ===================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("regression1d") 9 | ax = az.plot_bpv(data, backend="bokeh") 10 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | setuptools>=60.0.0 2 | matplotlib>=3.5 3 | numpy>=1.23.0 4 | scipy>=1.9.0 5 | packaging 6 | pandas>=1.5.0 7 | xarray>=2022.6.0 8 | h5netcdf>=1.0.2 9 | typing_extensions>=4.1.0 10 | xarray-einstats>=0.3 11 | -------------------------------------------------------------------------------- /arviz/tests/saved_models/cmdstan/example_stan.data.R: -------------------------------------------------------------------------------- 1 | x <- 1 2 | y <- 3 | c(1.0, 1.0, 1.0) 4 | Z <- 5 | structure(c(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0), .Dim = c(4, 5)) 6 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_energy.py: -------------------------------------------------------------------------------- 1 | """ 2 | Energy Plot 3 | =========== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("centered_eight") 9 | ax = az.plot_energy(data, figsize=(12, 8), backend="bokeh") 10 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_rank.py: -------------------------------------------------------------------------------- 1 | """ 2 | Rank plot 3 | ========= 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("centered_eight") 9 | ax = az.plot_rank(data, var_names=("tau", "mu"), backend="bokeh") 10 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | addopts = --strict -rsf --durations=20 -p no:warnings 3 | console_output_style = count 4 | junit_family= xunit1 5 | markers = 6 | slow: Convenience marker to skip slower running tests during local development -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_violin.py: -------------------------------------------------------------------------------- 1 | """ 2 | Violinplot 3 | ========== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("non_centered_eight") 9 | ax = az.plot_violin(data, var_names=["mu", "tau"], backend="bokeh") 10 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_trace.py: -------------------------------------------------------------------------------- 1 | """ 2 | Traceplot Bokeh 3 | =============== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("non_centered_eight") 9 | ax = az.plot_trace(data, var_names=("tau", "mu"), backend="bokeh") 10 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.md 2 | include *.txt 3 | include *.toml 4 | include LICENSE 5 | include arviz/py.typed 6 | 7 | recursive-include arviz *.mplstyle 8 | recursive-include arviz/static * 9 | recursive-include arviz/data/example_data *.nc *.json 10 | -------------------------------------------------------------------------------- /doc/source/getting_started/index.md: -------------------------------------------------------------------------------- 1 | (getting_started)= 2 | 3 | # Getting Started 4 | 5 | ```{toctree} 6 | :maxdepth: 2 7 | 8 | Installation 9 | Introduction 10 | XarrayforArviZ 11 | CreatingInferenceData 12 | WorkingWithInferenceData 13 | ``` 14 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_autocorr.py: -------------------------------------------------------------------------------- 1 | """ 2 | Autocorrelation Plot 3 | ==================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("centered_eight") 9 | ax = az.plot_autocorr(data, var_names="tau", backend="bokeh") 10 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_parallel.py: -------------------------------------------------------------------------------- 1 | """ 2 | Parallel Plot 3 | ============= 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("centered_eight") 9 | ax = az.plot_parallel(data, var_names=["theta", "tau", "mu"], backend="bokeh") 10 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-colors.mplstyle: -------------------------------------------------------------------------------- 1 | # color-blind friendly cycle designed using https://colorcyclepicker.mpetroff.net/ 2 | axes.prop_cycle: cycler('color', ['2a2eec', 'fa7c17', '328c06', 'c10c90', '933708', '65e5f3', 'e6e135', '1ccd6a', 'bd8ad5', 'b16b57']) 3 | -------------------------------------------------------------------------------- /doc/source/api/diagnostics.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: arviz 2 | 3 | .. _diagnostics_api: 4 | 5 | Diagnostics 6 | ----------- 7 | 8 | .. autosummary:: 9 | :toctree: generated/ 10 | 11 | bfmi 12 | ess 13 | rhat 14 | mcse 15 | psens 16 | -------------------------------------------------------------------------------- /doc/source/user_guide/data_structures.md: -------------------------------------------------------------------------------- 1 | # Data structures 2 | 3 | ```{toctree} 4 | :maxdepth: 2 5 | label_guide 6 | ../schema/schema 7 | ``` 8 | 9 | A notebook about working with {class}`~arviz.InferenceData` will be added to 10 | this section soon. 11 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_ess_evolution.py: -------------------------------------------------------------------------------- 1 | """ 2 | ESS Evolution Plot 3 | ================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | idata = az.load_arviz_data("radon") 9 | 10 | ax = az.plot_ess(idata, var_names=["b"], kind="evolution", backend="bokeh") 11 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_loo_pit_ecdf.py: -------------------------------------------------------------------------------- 1 | """ 2 | LOO-PIT ECDF Plot 3 | ================= 4 | """ 5 | 6 | import arviz as az 7 | 8 | idata = az.load_arviz_data("radon") 9 | 10 | ax = az.plot_loo_pit(idata, y="y", ecdf=True, color="orange", backend="bokeh") 11 | -------------------------------------------------------------------------------- /doc/source/api/stats_refitting.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: arviz 2 | 3 | .. _stats_refit_api: 4 | 5 | Stats (requiring refitting) 6 | --------------------------- 7 | Experimental feature 8 | 9 | .. autosummary:: 10 | :toctree: generated/ 11 | 12 | reloo 13 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_dot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dot Plot 3 | ========= 4 | """ 5 | 6 | import numpy as np 7 | import arviz as az 8 | 9 | data = np.random.normal(0, 1, 1000) 10 | az.plot_dot(data, dotcolor="C1", point_interval=True, figsize=(12, 6), backend="bokeh") 11 | -------------------------------------------------------------------------------- /doc/_templates/twitter.html: -------------------------------------------------------------------------------- 1 | Tweets by arviz_devs 2 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_ess_local.py: -------------------------------------------------------------------------------- 1 | """ 2 | ESS Local Plot 3 | ============== 4 | """ 5 | 6 | import arviz as az 7 | 8 | idata = az.load_arviz_data("non_centered_eight") 9 | 10 | ax = az.plot_ess(idata, var_names=["mu"], kind="local", rug=True, backend="bokeh") 11 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_khat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pareto Shape Plot 3 | ================= 4 | """ 5 | 6 | import arviz as az 7 | 8 | idata = az.load_arviz_data("radon") 9 | loo = az.loo(idata, pointwise=True) 10 | 11 | ax = az.plot_khat(loo, show_bins=True, backend="bokeh") 12 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_ess_quantile.py: -------------------------------------------------------------------------------- 1 | """ 2 | ESS Quantile Plot 3 | ================= 4 | """ 5 | 6 | import arviz as az 7 | 8 | idata = az.load_arviz_data("radon") 9 | 10 | ax = az.plot_ess(idata, var_names=["sigma"], kind="quantile", color="red", backend="bokeh") 11 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_ppc.py: -------------------------------------------------------------------------------- 1 | """ 2 | Posterior Predictive Check Plot 3 | =============================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("non_centered_eight") 9 | ax = az.plot_ppc(data, alpha=0.03, figsize=(12, 6), backend="bokeh") 10 | -------------------------------------------------------------------------------- /arviz/tests/saved_models/cmdstan/example_stan.json: -------------------------------------------------------------------------------- 1 | { 2 | "x": 1.0, 3 | "y": [1.0, 1.0, 1.0], 4 | "Z": [ 5 | [1.0, 1.0, 1.0, 1.0, 1.0], 6 | [1.0, 1.0, 1.0, 1.0, 1.0], 7 | [1.0, 1.0, 1.0, 1.0, 1.0], 8 | [1.0, 1.0, 1.0, 1.0, 1.0]] 9 | } 10 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_loo_pit_overlay.py: -------------------------------------------------------------------------------- 1 | """ 2 | LOO-PIT Overlay Plot 3 | ==================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | idata = az.load_arviz_data("non_centered_eight") 9 | 10 | ax = az.plot_loo_pit(idata=idata, y="obs", color="green", backend="bokeh") 11 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_mcse_errorbar.py: -------------------------------------------------------------------------------- 1 | """ 2 | Quantile MCSE Errobar Plot 3 | ========================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("radon") 9 | ax = az.plot_mcse(data, var_names=["sigma_a"], color="red", errorbar=True, backend="bokeh") 10 | -------------------------------------------------------------------------------- /doc/source/api/stats_utils.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: arviz 2 | 3 | .. _stats_utils_api: 4 | 5 | Stats utils 6 | ----------- 7 | 8 | .. autosummary:: 9 | :toctree: generated/ 10 | 11 | autocov 12 | autocorr 13 | make_ufunc 14 | smooth_data 15 | wrap_xarray_ufunc 16 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Charts for Example Gallery 2 | 3 | [See guide for writing scripts for the example gallery here](https://python.arviz.org/en/latest/contributing/how_to_add_to_example_gallery.html). 4 | 5 | [See Example Gallery here](https://python.arviz.org/en/latest/examples/index.html). 6 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_bpv_tstat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bayesian p-value with T statistic Plot 3 | ====================================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("regression1d") 9 | ax = az.plot_bpv(data, kind="t_stat", t_stat="0.5", backend="bokeh") 10 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_separation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Separation Plot 3 | =============== 4 | """ 5 | 6 | import arviz as az 7 | 8 | idata = az.load_arviz_data("classification10d") 9 | 10 | ax = az.plot_separation(idata=idata, y="outcome", y_hat="outcome", figsize=(8, 1), backend="bokeh") 11 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_trace_bars.py: -------------------------------------------------------------------------------- 1 | """ 2 | Traceplot rank_bars Bokeh 3 | ========================= 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("non_centered_eight") 9 | ax = az.plot_trace(data, var_names=("tau", "mu"), kind="rank_bars", backend="bokeh") 10 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_trace_vlines.py: -------------------------------------------------------------------------------- 1 | """ 2 | Traceplot rank_vlines Bokeh 3 | =========================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("non_centered_eight") 9 | ax = az.plot_trace(data, var_names=("tau", "mu"), kind="rank_vlines", backend="bokeh") 10 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_elpd.py: -------------------------------------------------------------------------------- 1 | """ 2 | ELPD Plot 3 | ========= 4 | """ 5 | 6 | import arviz as az 7 | 8 | d1 = az.load_arviz_data("centered_eight") 9 | d2 = az.load_arviz_data("non_centered_eight") 10 | 11 | ax = az.plot_elpd({"Centered eight": d1, "Non centered eight": d2}, backend="bokeh") 12 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_ecdf.py: -------------------------------------------------------------------------------- 1 | """ 2 | ECDF Plot 3 | ========= 4 | """ 5 | 6 | from scipy.stats import norm 7 | 8 | import arviz as az 9 | 10 | sample = norm(0, 1).rvs(1000) 11 | distribution = norm(0, 1) 12 | 13 | az.plot_ecdf(sample, cdf=distribution.cdf, confidence_bands=True, backend="bokeh") 14 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_kde_quantiles.py: -------------------------------------------------------------------------------- 1 | """ 2 | KDE quantiles Bokeh 3 | =================== 4 | """ 5 | 6 | import numpy as np 7 | 8 | import arviz as az 9 | 10 | dist = np.random.beta(np.random.uniform(0.5, 10), 5, size=1000) 11 | ax = az.plot_kde(dist, quantiles=[0.25, 0.5, 0.75], backend="bokeh") 12 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_trace_circ.py: -------------------------------------------------------------------------------- 1 | """ 2 | Traceplot with Circular Variables 3 | ================================= 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("glycan_torsion_angles") 9 | az.plot_trace(data, var_names=["tors", "E"], circ_var_names=["tors"], backend="bokeh") 10 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_mcse.py: -------------------------------------------------------------------------------- 1 | """ 2 | Quantile Monte Carlo Standard Error Plot 3 | ======================================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("centered_eight") 9 | ax = az.plot_mcse(data, var_names=["tau", "mu"], rug=True, extra_methods=True, backend="bokeh") 10 | -------------------------------------------------------------------------------- /doc/_templates/donate.html: -------------------------------------------------------------------------------- 1 | {% if "generated" in sourcename %} 2 |
3 | {% else %} 4 |
5 | {% endif %} 6 | 7 | {{ _("Support ArviZ") }} 8 | 9 |
10 | -------------------------------------------------------------------------------- /doc/source/api/stats.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: arviz 2 | 3 | .. _stats_api: 4 | 5 | Stats 6 | ----- 7 | 8 | .. autosummary:: 9 | :toctree: generated/ 10 | 11 | apply_test_function 12 | compare 13 | hdi 14 | kde 15 | loo 16 | loo_pit 17 | psislw 18 | r2_score 19 | summary 20 | waic 21 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_ppc_cumulative.py: -------------------------------------------------------------------------------- 1 | """ 2 | Posterior Predictive Check Cumulative Plot 3 | ========================================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("non_centered_eight") 9 | ax = az.plot_ppc(data, alpha=0.03, kind="cumulative", figsize=(12, 6), backend="bokeh") 10 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_forest.py: -------------------------------------------------------------------------------- 1 | """ 2 | Forest Plot 3 | =========== 4 | """ 5 | 6 | import arviz as az 7 | 8 | centered_data = az.load_arviz_data("centered_eight") 9 | ax = az.plot_forest( 10 | centered_data, 11 | var_names=["~tau"], 12 | combined=False, 13 | figsize=(11.5, 5), 14 | backend="bokeh", 15 | ) 16 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_posterior.py: -------------------------------------------------------------------------------- 1 | """ 2 | Posterior Plot 3 | ============== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("centered_eight") 9 | 10 | coords = {"school": ["Choate"]} 11 | ax = az.plot_posterior( 12 | data, var_names=["mu", "theta"], coords=coords, rope=(-1, 1), backend="bokeh" 13 | ) 14 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_bpv.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bayesian u-value Plot 3 | ===================== 4 | _gallery_category: Model Checking 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("regression1d") 14 | az.plot_bpv(data) 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /doc/source/api/wrappers.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: arviz 2 | 3 | .. _wrappers_api: 4 | 5 | Wrappers 6 | -------- 7 | Experimental feature 8 | 9 | .. autosummary:: 10 | :toctree: generated/ 11 | 12 | SamplingWrapper 13 | CmdStanPySamplingWrapper 14 | PyMCSamplingWrapper 15 | PyStanSamplingWrapper 16 | PyStan2SamplingWrapper 17 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_density_single.py: -------------------------------------------------------------------------------- 1 | """ 2 | Density Plot 3 | ============ 4 | """ 5 | 6 | import arviz as az 7 | 8 | centered_data = az.load_arviz_data("centered_eight") 9 | ax = az.plot_density( 10 | [centered_data], 11 | data_labels=["Centered"], 12 | var_names=["theta"], 13 | shade=0.1, 14 | backend="bokeh", 15 | ) 16 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_pair.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pair Plot 3 | ========= 4 | """ 5 | 6 | import arviz as az 7 | 8 | centered = az.load_arviz_data("centered_eight") 9 | 10 | coords = {"school": ["Choate", "Deerfield"]} 11 | ax = az.plot_pair( 12 | centered, var_names=["theta", "mu", "tau"], coords=coords, divergences=True, backend="bokeh" 13 | ) 14 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_trace.py: -------------------------------------------------------------------------------- 1 | """ 2 | Traceplot 3 | ========= 4 | _gallery_category: Mixed Plots 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("non_centered_eight") 14 | az.plot_trace(data, var_names=("tau", "mu")) 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /requirements-docs.txt: -------------------------------------------------------------------------------- 1 | docutils 2 | ipython 3 | pickleshare 4 | numpydoc 5 | pydocstyle 6 | Sphinx>=5 7 | pydata-sphinx-theme>=0.13.0 8 | myst-parser 9 | myst-nb 10 | sphinx-notfound-page 11 | sphinx-copybutton 12 | bokeh>=3 13 | contourpy 14 | sphinx_design 15 | sphinx-codeautolink>=0.9.0 16 | jupyter-sphinx 17 | sphinxcontrib-youtube 18 | dm-tree>=0.1.8 19 | -------------------------------------------------------------------------------- /doc/source/api/index.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: arviz 2 | 3 | .. _api: 4 | 5 | API Reference 6 | ============= 7 | 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | 12 | plots 13 | stats 14 | diagnostics 15 | stats_utils 16 | data 17 | inference_data 18 | plot_utils 19 | utils 20 | rcparams 21 | wrappers 22 | stats_refitting 23 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_forest_mixed.py: -------------------------------------------------------------------------------- 1 | """ 2 | Forest Plot with ESS 3 | ==================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | centered_data = az.load_arviz_data("centered_eight") 9 | ax = az.plot_forest( 10 | centered_data, 11 | var_names=["theta"], 12 | figsize=(11.5, 5), 13 | ess=True, 14 | # r_hat=True, 15 | backend="bokeh", 16 | ) 17 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_kde_2d.py: -------------------------------------------------------------------------------- 1 | """ 2 | 2D KDE 3 | ====== 4 | """ 5 | 6 | import numpy as np 7 | 8 | import arviz as az 9 | 10 | az.plot_kde( 11 | np.random.beta(2, 5, size=100), 12 | np.random.beta(2, 5, size=100), 13 | contour_kwargs={"levels": 30}, 14 | contourf_kwargs={"alpha": 0.5, "levels": 30, "cmap": "viridis"}, 15 | backend="bokeh", 16 | ) 17 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_violin.py: -------------------------------------------------------------------------------- 1 | """ 2 | Violin plot 3 | =========== 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("non_centered_eight") 14 | az.plot_violin(data, var_names=["mu", "tau"], figsize=(11.5, 5)) 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_autocorr.py: -------------------------------------------------------------------------------- 1 | """ 2 | Autocorrelation Plot 3 | ==================== 4 | _gallery_category: Inference Diagnostics 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("centered_eight") 14 | az.plot_autocorr(data, var_names=("tau", "mu")) 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_loo_pit_overlay.py: -------------------------------------------------------------------------------- 1 | """ 2 | LOO-PIT Overlay Plot 3 | ==================== 4 | _gallery_category: Model Checking 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | idata = az.load_arviz_data("non_centered_eight") 14 | 15 | az.plot_loo_pit(idata=idata, y="obs") 16 | 17 | plt.show() 18 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | ignore: 2 | - arviz/tests/ 3 | 4 | codecov: 5 | notify: 6 | after_n_builds: 6 7 | 8 | comment: 9 | behavior: default 10 | branches: 11 | - "main" 12 | 13 | coverage: 14 | status: 15 | project: 16 | default: 17 | target: auto 18 | threshold: 2% 19 | 20 | patch: 21 | default: 22 | target: 75% 23 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_ess_evolution.py: -------------------------------------------------------------------------------- 1 | """ 2 | ESS Evolution Plot 3 | ================== 4 | _gallery_category: Inference Diagnostics 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | idata = az.load_arviz_data("radon") 14 | 15 | az.plot_ess(idata, var_names=["b"], kind="evolution") 16 | 17 | plt.show() 18 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_ess_quantile.py: -------------------------------------------------------------------------------- 1 | """ 2 | ESS Quantile Plot 3 | ================= 4 | _gallery_category: Inference Diagnostics 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | idata = az.load_arviz_data("radon") 14 | 15 | az.plot_ess(idata, var_names=["sigma"], kind="quantile") 16 | 17 | plt.show() 18 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_khat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pareto Shape Plot 3 | ================= 4 | _gallery_category: Model Comparison 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | idata = az.load_arviz_data("radon") 14 | loo = az.loo(idata, pointwise=True) 15 | 16 | az.plot_khat(loo, show_bins=True) 17 | 18 | plt.show() 19 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | line-length = 100 3 | extend_exclude = 'example_data' 4 | 5 | [tool.isort] 6 | multi_line_output = 3 7 | include_trailing_comma = true 8 | force_grid_wrap = 0 9 | use_parentheses = true 10 | line_length = 100 11 | skip = [ 12 | "arviz/plots/backends/bokeh/__init__.py", 13 | "arviz/plots/backends/matplotlib/__init__.py", 14 | "arviz/__init__.py" 15 | ] 16 | -------------------------------------------------------------------------------- /.github/workflows/rtd_link_description.yaml: -------------------------------------------------------------------------------- 1 | name: Read the Docs Pull Request Preview 2 | on: 3 | pull_request_target: 4 | types: 5 | - opened 6 | 7 | permissions: 8 | pull-requests: write 9 | 10 | jobs: 11 | documentation-links: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: readthedocs/actions/preview@v1 15 | with: 16 | project-slug: "arviz" 17 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_compare.py: -------------------------------------------------------------------------------- 1 | """ 2 | Compare Plot 3 | ============ 4 | """ 5 | 6 | import arviz as az 7 | 8 | model_compare = az.compare( 9 | { 10 | "Centered 8 schools": az.load_arviz_data("centered_eight"), 11 | "Non-centered 8 schools": az.load_arviz_data("non_centered_eight"), 12 | } 13 | ) 14 | ax = az.plot_compare(model_compare, figsize=(12, 4), backend="bokeh") 15 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_mcse_errorbar.py: -------------------------------------------------------------------------------- 1 | """ 2 | Quantile MCSE Errobar Plot 3 | ========================== 4 | _gallery_category: Inference Diagnostics 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("radon") 14 | az.plot_mcse(data, var_names=["sigma_a"], errorbar=True) 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_trace_vlines.py: -------------------------------------------------------------------------------- 1 | """ 2 | Traceplot rank_vlines 3 | ===================== 4 | _gallery_category: Mixed Plots 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("non_centered_eight") 14 | az.plot_trace(data, var_names=("tau", "mu"), kind="rank_vlines") 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_energy.py: -------------------------------------------------------------------------------- 1 | """ 2 | Energy Plot 3 | =========== 4 | _gallery_category: Inference Diagnostics 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("centered_eight") 14 | ax = az.plot_energy(data, fill_color=("C0", "C1")) 15 | 16 | ax.set_title("Energy Plot") 17 | 18 | plt.show() 19 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_kde_quantiles.py: -------------------------------------------------------------------------------- 1 | """ 2 | KDE quantiles 3 | ============= 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | 10 | import arviz as az 11 | 12 | az.style.use("arviz-doc") 13 | 14 | dist = np.random.beta(np.random.uniform(0.5, 10), 5, size=1000) 15 | az.plot_kde(dist, quantiles=[0.25, 0.5, 0.75]) 16 | 17 | plt.show() 18 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_separation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Separation Plot 3 | =============== 4 | _gallery_category: Model Checking 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | idata = az.load_arviz_data("classification10d") 14 | 15 | az.plot_separation(idata=idata, y="outcome", y_hat="outcome", figsize=(8, 1)) 16 | 17 | plt.show() 18 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_bpv_tstat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bayesian p-value with T statistic Plot 3 | ====================================== 4 | _gallery_category: Model Checking 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("regression1d") 14 | az.plot_bpv(data, kind="t_stat", t_stat="0.5") 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_trace_bars.py: -------------------------------------------------------------------------------- 1 | """ 2 | Rank Bars Diagnostic with KDE 3 | ============================= 4 | _gallery_category: Mixed Plots 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("non_centered_eight") 14 | az.plot_trace(data, var_names=("tau", "mu"), kind="rank_bars") 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_pair_kde.py: -------------------------------------------------------------------------------- 1 | """ 2 | KDE Pair Plot 3 | ============= 4 | """ 5 | 6 | import arviz as az 7 | 8 | centered = az.load_arviz_data("centered_eight") 9 | 10 | coords = {"school": ["Choate", "Deerfield"]} 11 | ax = az.plot_pair( 12 | centered, 13 | var_names=["theta", "mu", "tau"], 14 | kind="kde", 15 | coords=coords, 16 | divergences=True, 17 | backend="bokeh", 18 | ) 19 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_ppc.py: -------------------------------------------------------------------------------- 1 | """ 2 | Posterior Predictive Check Plot 3 | =============================== 4 | _gallery_category: Model Checking 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("non_centered_eight") 14 | az.plot_ppc(data, data_pairs={"obs": "obs"}, alpha=0.03, textsize=14) 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_forest_ridge.py: -------------------------------------------------------------------------------- 1 | """ 2 | Ridgeplot 3 | ========= 4 | """ 5 | 6 | import arviz as az 7 | 8 | rugby_data = az.load_arviz_data("rugby") 9 | ax = az.plot_forest( 10 | rugby_data, 11 | kind="ridgeplot", 12 | var_names=["defs"], 13 | linewidth=4, 14 | combined=True, 15 | ridgeplot_overlap=1.5, 16 | colors="blue", 17 | figsize=(9, 4), 18 | backend="bokeh", 19 | ) 20 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_dot.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dot Plot 3 | ========= 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | 10 | import arviz as az 11 | 12 | az.style.use("arviz-doc") 13 | 14 | data = np.random.normal(0, 1, 1000) 15 | ax = az.plot_dot(data, dotcolor="C1", point_interval=True) 16 | 17 | ax.set_title("Gaussian Distribution") 18 | 19 | plt.show() 20 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_ess_local.py: -------------------------------------------------------------------------------- 1 | """ 2 | ESS Local Plot 3 | ============== 4 | _gallery_category: Inference Diagnostics 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | idata = az.load_arviz_data("non_centered_eight") 14 | 15 | az.plot_ess(idata, var_names=["mu"], kind="local", marker="_", ms=20, mew=2, rug=True) 16 | 17 | plt.show() 18 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_bf.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bayes Factor Plot 3 | ================= 4 | _gallery_category: Model Comparison 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | import arviz as az 10 | 11 | idata = az.from_dict( 12 | posterior={"a": np.random.normal(1, 0.5, 5000)}, prior={"a": np.random.normal(0, 1, 5000)} 13 | ) 14 | 15 | az.plot_bf(idata, var_name="a", ref_val=0) 16 | plt.show() 17 | -------------------------------------------------------------------------------- /arviz/wrappers/__init__.py: -------------------------------------------------------------------------------- 1 | """Sampling wrappers.""" 2 | 3 | from .base import SamplingWrapper 4 | from .wrap_stan import PyStan2SamplingWrapper, PyStanSamplingWrapper, CmdStanPySamplingWrapper 5 | from .wrap_pymc import PyMCSamplingWrapper 6 | 7 | __all__ = [ 8 | "CmdStanPySamplingWrapper", 9 | "PyMCSamplingWrapper", 10 | "PyStan2SamplingWrapper", 11 | "PyStanSamplingWrapper", 12 | "SamplingWrapper", 13 | ] 14 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_trace_circ.py: -------------------------------------------------------------------------------- 1 | """ 2 | Traceplot with Circular Variables 3 | ================================= 4 | _gallery_category: Mixed Plots 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("glycan_torsion_angles") 14 | az.plot_trace(data, var_names=["tors", "E"], circ_var_names=["tors"]) 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_elpd.py: -------------------------------------------------------------------------------- 1 | """ 2 | ELPD Plot 3 | ========= 4 | _gallery_category: Model Comparison 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | d1 = az.load_arviz_data("centered_eight") 14 | d2 = az.load_arviz_data("non_centered_eight") 15 | 16 | az.plot_elpd({"Centered eight": d1, "Non centered eight": d2}, xlabels=True) 17 | 18 | plt.show() 19 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # Read the Docs configuration file 2 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 3 | version: 2 4 | 5 | build: 6 | os: ubuntu-22.04 7 | tools: 8 | python: "3.11" 9 | 10 | sphinx: 11 | configuration: doc/source/conf.py 12 | 13 | python: 14 | install: 15 | - requirements: requirements.txt 16 | - requirements: requirements-docs.txt 17 | - method: pip 18 | path: . 19 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_parallel.py: -------------------------------------------------------------------------------- 1 | """ 2 | Parallel Plot 3 | ============= 4 | _gallery_category: Inference Diagnostics 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("centered_eight") 14 | ax = az.plot_parallel(data, var_names=["theta", "tau", "mu"]) 15 | ax.set_xticklabels(ax.get_xticklabels(), rotation=45) 16 | 17 | plt.show() 18 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_ppc_cumulative.py: -------------------------------------------------------------------------------- 1 | """ 2 | Posterior Predictive Check Cumulative Plot 3 | ========================================== 4 | _gallery_category: Model Checking 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("non_centered_eight") 14 | az.plot_ppc(data, alpha=0.05, kind="cumulative", textsize=14) 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_forest_comparison.py: -------------------------------------------------------------------------------- 1 | """ 2 | Forest Plot Comparison 3 | ====================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | centered_data = az.load_arviz_data("centered_eight") 9 | non_centered_data = az.load_arviz_data("non_centered_eight") 10 | ax = az.plot_forest( 11 | [centered_data, non_centered_data], 12 | model_names=["Centered", "Non Centered"], 13 | var_names=["mu"], 14 | backend="bokeh", 15 | ) 16 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_pair_hex.py: -------------------------------------------------------------------------------- 1 | """ 2 | Hexbin PairPlot 3 | =============== 4 | """ 5 | 6 | import arviz as az 7 | 8 | centered = az.load_arviz_data("centered_eight") 9 | 10 | coords = {"school": ["Choate", "Deerfield"]} 11 | ax = az.plot_pair( 12 | centered, 13 | var_names=["theta", "mu", "tau"], 14 | kind="hexbin", 15 | coords=coords, 16 | colorbar=True, 17 | divergences=True, 18 | backend="bokeh", 19 | ) 20 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_mcse.py: -------------------------------------------------------------------------------- 1 | """ 2 | Quantile Monte Carlo Standard Error Plot 3 | ======================================== 4 | _gallery_category: Inference Diagnostics 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("centered_eight") 14 | az.plot_mcse(data, var_names=["tau", "mu"], rug=True, extra_methods=True) 15 | 16 | plt.show() 17 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_rank.py: -------------------------------------------------------------------------------- 1 | """ 2 | Rank plot 3 | ========= 4 | _gallery_category: Inference Diagnostics 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | fig, axes = plt.subplots(1, 2) 14 | 15 | data = az.load_arviz_data("centered_eight") 16 | az.plot_rank(data, var_names=("tau", "mu"), ax=axes) 17 | 18 | fig.suptitle("Rank (All Chains)") 19 | 20 | plt.show() 21 | -------------------------------------------------------------------------------- /arviz/preview.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=unused-import,unused-wildcard-import,wildcard-import 2 | """Expose features from arviz-xyz refactored packages inside ``arviz.preview`` namespace.""" 3 | 4 | try: 5 | from arviz_base import * 6 | except ModuleNotFoundError: 7 | pass 8 | 9 | try: 10 | import arviz_stats 11 | except ModuleNotFoundError: 12 | pass 13 | 14 | try: 15 | from arviz_plots import * 16 | except ModuleNotFoundError: 17 | pass 18 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_density.py: -------------------------------------------------------------------------------- 1 | """ 2 | Density Plot (Comparison) 3 | ========================= 4 | """ 5 | 6 | import arviz as az 7 | 8 | centered_data = az.load_arviz_data("centered_eight") 9 | non_centered_data = az.load_arviz_data("non_centered_eight") 10 | ax = az.plot_density( 11 | [centered_data, non_centered_data], 12 | data_labels=["Centered", "Non Centered"], 13 | var_names=["theta"], 14 | shade=0.1, 15 | backend="bokeh", 16 | ) 17 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_forest.py: -------------------------------------------------------------------------------- 1 | """ 2 | Forest Plot 3 | =========== 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | centered_data = az.load_arviz_data("centered_eight") 14 | ax = az.plot_forest( 15 | centered_data, 16 | var_names=["~tau"], 17 | combined=False, 18 | figsize=(11.5, 5), 19 | colors="C1", 20 | ) 21 | 22 | plt.show() 23 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_loo_pit_ecdf.py: -------------------------------------------------------------------------------- 1 | """ 2 | LOO-PIT ECDF Plot 3 | ================= 4 | _gallery_category: Model Checking 5 | Plot LOO predictive ECDF compared to ECDF of uniform distribution to assess predictive calibration. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | 10 | import arviz as az 11 | 12 | az.style.use("arviz-doc") 13 | 14 | idata = az.load_arviz_data("radon") 15 | 16 | az.plot_loo_pit(idata, y="y", ecdf=True) 17 | 18 | plt.show() 19 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_posterior_combinedims.py: -------------------------------------------------------------------------------- 1 | """ 2 | Posterior Plot (reducing school dimension) 3 | ========================================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("centered_eight") 9 | 10 | coords = {"school": ["Choate", "Mt. Hermon", "Deerfield"]} 11 | ax = az.plot_posterior( 12 | data, 13 | var_names=["mu", "theta"], 14 | combine_dims={"school"}, 15 | coords=coords, 16 | backend="bokeh", 17 | ) 18 | -------------------------------------------------------------------------------- /doc/_templates/layout.html: -------------------------------------------------------------------------------- 1 | {% extends "!layout.html" %} 2 | 3 | 4 | {%- block scripts_end %} 5 | {{ super() }} 6 | {% if not READTHEDOCS %} 7 | 13 | {% endif %} 14 | {%- endblock %} 15 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_kde_2d_hdi.py: -------------------------------------------------------------------------------- 1 | """ 2 | 2D KDE with HDI Contours 3 | ======================== 4 | """ 5 | 6 | import numpy as np 7 | 8 | import arviz as az 9 | 10 | rng = np.random.default_rng() 11 | data = rng.multivariate_normal([2, 2], [[1, 0.4], [0.4, 0.8]], 1000000) 12 | 13 | az.plot_kde( 14 | data[:, 0], 15 | data[:, 1], 16 | hdi_probs=[0.393, 0.865, 0.989], # 1, 2 and 3 sigma contours 17 | contourf_kwargs={"cmap": "Blues"}, 18 | backend="bokeh", 19 | ) 20 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_kde_2d.py: -------------------------------------------------------------------------------- 1 | """ 2 | 2D KDE 3 | ====== 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | 10 | import arviz as az 11 | 12 | az.style.use("arviz-doc") 13 | 14 | az.plot_kde( 15 | np.random.beta(2, 5, size=100), 16 | np.random.beta(2, 5, size=100), 17 | contour_kwargs={"colors": None, "cmap": plt.cm.viridis, "levels": 30}, 18 | contourf_kwargs={"alpha": 0.5, "levels": 30}, 19 | ) 20 | 21 | plt.show() 22 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_forest_mixed.py: -------------------------------------------------------------------------------- 1 | """ 2 | Forest Plot with ESS 3 | ==================== 4 | _gallery_category: Mixed Plots 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | centered_data = az.load_arviz_data("centered_eight") 14 | ax = az.plot_forest( 15 | centered_data, 16 | var_names=["theta"], 17 | figsize=(11.5, 5), 18 | colors="C1", 19 | ess=True, 20 | # r_hat=True, 21 | ) 22 | 23 | plt.show() 24 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_hdi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plot HDI 3 | ======== 4 | _gallery_category: Regression or Time Series 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | 10 | import arviz as az 11 | 12 | az.style.use("arviz-doc") 13 | 14 | x_data = np.random.normal(0, 1, 100) 15 | y_data = 2 + x_data * 0.5 16 | y_data_rep = np.random.normal(y_data, 0.5, (4, 200, 100)) 17 | ax = az.plot_hdi(x_data, y_data_rep, plot_kwargs={"ls": "--"}) 18 | ax.plot(x_data, y_data) 19 | 20 | plt.show() 21 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_joint.py: -------------------------------------------------------------------------------- 1 | """ 2 | Joint Plot 3 | ========== 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("non_centered_eight") 14 | 15 | az.plot_pair( 16 | data, 17 | var_names=["theta"], 18 | coords={"school": ["Choate", "Phillips Andover"]}, 19 | kind="hexbin", 20 | marginals=True, 21 | figsize=(11.5, 11.5), 22 | ) 23 | plt.show() 24 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_pair.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pair Plot 3 | ========= 4 | _gallery_category: Inference Diagnostics 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("centered_eight") 14 | 15 | coords = {"school": ["Choate", "Deerfield"]} 16 | az.plot_pair( 17 | data, 18 | var_names=["theta", "mu", "tau"], 19 | coords=coords, 20 | divergences=True, 21 | textsize=22, 22 | ) 23 | 24 | plt.show() 25 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_pair_kde.py: -------------------------------------------------------------------------------- 1 | """ 2 | KDE Pair Plot 3 | ============= 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("centered_eight") 14 | 15 | coords = {"school": ["Choate", "Deerfield"]} 16 | az.plot_pair( 17 | data, 18 | var_names=["theta", "mu", "tau"], 19 | kind="kde", 20 | coords=coords, 21 | textsize=22, 22 | ) 23 | 24 | plt.show() 25 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_joint.py: -------------------------------------------------------------------------------- 1 | """ 2 | Joint Plot 3 | ========== 4 | """ 5 | 6 | import arviz as az 7 | 8 | data = az.load_arviz_data("non_centered_eight") 9 | 10 | ax = az.plot_pair( 11 | data, 12 | var_names=["theta"], 13 | coords={"school": ["Choate", "Phillips Andover"]}, 14 | kind="hexbin", 15 | figsize=(8, 8), 16 | marginals=True, 17 | marginal_kwargs={"plot_kwargs": {"line_width": 3, "line_color": "black"}}, 18 | hexbin_kwargs={"size": 1.5}, 19 | backend="bokeh", 20 | ) 21 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_pair_hex.py: -------------------------------------------------------------------------------- 1 | """ 2 | Hexbin PairPlot 3 | =============== 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | centered = az.load_arviz_data("centered_eight") 14 | 15 | coords = {"school": ["Choate", "Deerfield"]} 16 | az.plot_pair( 17 | centered, 18 | var_names=["theta", "mu", "tau"], 19 | kind="hexbin", 20 | coords=coords, 21 | colorbar=True, 22 | ) 23 | plt.show() 24 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_compare.py: -------------------------------------------------------------------------------- 1 | """ 2 | Compare Plot 3 | ============ 4 | _gallery_category: Model Comparison 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | model_compare = az.compare( 14 | { 15 | "Centered 8 schools": az.load_arviz_data("centered_eight"), 16 | "Non-centered 8 schools": az.load_arviz_data("non_centered_eight"), 17 | } 18 | ) 19 | az.plot_compare(model_compare, figsize=(11.5, 5)) 20 | 21 | plt.show() 22 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_ecdf.py: -------------------------------------------------------------------------------- 1 | """ 2 | ECDF Plot 3 | ========= 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import warnings 8 | import matplotlib.pyplot as plt 9 | from scipy.stats import norm 10 | 11 | import arviz as az 12 | 13 | az.style.use("arviz-doc") 14 | 15 | sample = norm(0, 1).rvs(1000) 16 | distribution = norm(0, 1) 17 | 18 | warnings.filterwarnings("ignore", category=az.utils.BehaviourChangeWarning) 19 | 20 | az.plot_ecdf(sample, cdf=distribution.cdf, confidence_bands=True) 21 | 22 | plt.show() 23 | -------------------------------------------------------------------------------- /scripts/lint.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | set -ex # fail on first error, print commands 4 | 5 | SRC_DIR=${SRC_DIR:-`pwd`} 6 | 7 | echo "Checking documentation..." 8 | python -m pydocstyle --convention=numpy ${SRC_DIR}/arviz/ 9 | echo "Success!" 10 | 11 | echo "Checking code style with black..." 12 | python -m black -l 100 --check ${SRC_DIR}/arviz/ ${SRC_DIR}/examples/ ${SRC_DIR}/asv_benchmarks/ 13 | echo "Success!" 14 | 15 | echo "Checking code style with pylint..." 16 | python -m pylint ${SRC_DIR}/arviz/ 17 | echo "Success!" 18 | -------------------------------------------------------------------------------- /arviz/plots/backends/bokeh/bfplot.py: -------------------------------------------------------------------------------- 1 | """Bokeh Bayes Factor plot.""" 2 | 3 | 4 | def plot_bf( 5 | ax, 6 | nvars, 7 | ngroups, 8 | figsize, 9 | dc_plotters, 10 | legend, 11 | groups, 12 | textsize, 13 | labeller, 14 | prior_kwargs, 15 | posterior_kwargs, 16 | observed_kwargs, 17 | backend_kwargs, 18 | show, 19 | ): 20 | """Bokeh Bayes Factor plot.""" 21 | raise NotImplementedError( 22 | "The bokeh backend is still under development. Use matplotlib backend." 23 | ) 24 | -------------------------------------------------------------------------------- /doc/source/user_guide/plotting.md: -------------------------------------------------------------------------------- 1 | (plotting_user_guide)= 2 | # Plotting 3 | 4 | ArviZ provides multiple plotting functions for different functionalities. 5 | You can browse all the functions in the `plot` module {ref}`by name ` or 6 | {ref}`by example output image `. 7 | 8 | The pages in this section will cover common functionality between several plotting 9 | functions in tutorial and how-to guide format. 10 | 11 | ```{toctree} 12 | plots_arguments_guide 13 | plotting_with_matplotlib 14 | plotting_with_bokeh 15 | ``` 16 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_pair_point_estimate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Point Estimate Pairplot 3 | ======================= 4 | """ 5 | 6 | import arviz as az 7 | 8 | centered = az.load_arviz_data("centered_eight") 9 | 10 | coords = {"school": ["Choate", "Deerfield"]} 11 | ax = az.plot_pair( 12 | centered, 13 | var_names=["mu", "theta"], 14 | kind=["scatter", "kde"], 15 | kde_kwargs={"fill_last": False}, 16 | marginals=True, 17 | coords=coords, 18 | point_estimate="median", 19 | figsize=(10, 8), 20 | backend="bokeh", 21 | ) 22 | -------------------------------------------------------------------------------- /doc/source/contributing/review_prs.md: -------------------------------------------------------------------------------- 1 | (review_prs)= 2 | # Review PRs 3 | 4 | :::{caution} Page in construction 5 | ::: 6 | 7 | :::{tip} 8 | Start preparing to be a PR reviewer by looking at how 9 | core contributors approach reviews. It will serve 10 | as a way to see which ways of interacting with contributors work 11 | best while also familiarizing with the developer guide, 12 | coding/documentation conventions and styles 13 | ::: 14 | 15 | The best place to start is the {ref}`pr_checklist`. Make sure all the 16 | recommendations outlined there are followed. 17 | -------------------------------------------------------------------------------- /doc/source/contributing/outreach.md: -------------------------------------------------------------------------------- 1 | (oureach_contrib)= 2 | # Outreach 3 | 4 | :::{caution} Page in construction 5 | ::: 6 | 7 | You can also contribute to ArviZ by doing outreach, writing blogposts, getting 8 | people to use it at your company or university, helping external libraries integrate with ArviZ (in 9 | any programming language of your choice). 10 | 11 | If you have a website or blog where you often post about ArviZ, a library that integrates with ArviZ reach out to us or 12 | open a PR to add your blog to {ref}`community`, we'd love to hear from you! 13 | -------------------------------------------------------------------------------- /arviz/plots/backends/bokeh/distcomparisonplot.py: -------------------------------------------------------------------------------- 1 | """Bokeh Density Comparison plot.""" 2 | 3 | 4 | def plot_dist_comparison( 5 | ax, 6 | nvars, 7 | ngroups, 8 | figsize, 9 | dc_plotters, 10 | legend, 11 | groups, 12 | textsize, 13 | labeller, 14 | prior_kwargs, 15 | posterior_kwargs, 16 | observed_kwargs, 17 | backend_kwargs, 18 | show, 19 | ): 20 | """Bokeh Density Comparison plot.""" 21 | raise NotImplementedError( 22 | "The bokeh backend is still under development. Use matplotlib backend." 23 | ) 24 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_hdi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Plot HDI 3 | ======== 4 | """ 5 | 6 | import bokeh.plotting as bkp 7 | import numpy as np 8 | 9 | import arviz as az 10 | 11 | x_data = np.random.normal(0, 1, 100) 12 | y_data = 2 + x_data * 0.5 13 | y_data_rep = np.random.normal(y_data, 0.5, (4, 200, 100)) 14 | x_data_sorted = np.sort(x_data) 15 | 16 | ax = az.plot_hdi(x_data, y_data_rep, color="red", backend="bokeh", show=False) 17 | ax.line(x_data_sorted, 2 + x_data_sorted * 0.5, line_color="black", line_width=3) 18 | 19 | if az.rcParams["plot.bokeh.show"]: 20 | bkp.show(ax) 21 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_density_single.py: -------------------------------------------------------------------------------- 1 | """ 2 | Density Plot 3 | ============ 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | centered_data = az.load_arviz_data("centered_eight") 14 | 15 | axes = az.plot_density( 16 | [centered_data], 17 | data_labels=["Centered"], 18 | var_names=["theta"], 19 | shade=0.2, 20 | ) 21 | 22 | fig = axes.flatten()[0].get_figure() 23 | fig.suptitle("94% High Density Intervals for Theta") 24 | 25 | plt.show() 26 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_lm.py: -------------------------------------------------------------------------------- 1 | """ 2 | Regression Plot. 3 | ========================================== 4 | """ 5 | 6 | import xarray as xr 7 | import numpy as np 8 | import arviz as az 9 | 10 | data = az.load_arviz_data("regression1d") 11 | x = xr.DataArray(np.linspace(0, 1, 100)) 12 | data.add_groups({"constant_data": {"x1": x}}) 13 | data.constant_data["x"] = x 14 | data.posterior["y_model"] = ( 15 | data.posterior["intercept"] + data.posterior["slope"] * data.constant_data["x"] 16 | ) 17 | 18 | az.plot_lm(idata=data, y="y", x="x", y_model="y_model", backend="bokeh", figsize=(12, 6)) 19 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_forest_ridge.py: -------------------------------------------------------------------------------- 1 | """ 2 | Ridgeplot 3 | ========= 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | rugby_data = az.load_arviz_data("rugby") 14 | axes = az.plot_forest( 15 | rugby_data, 16 | kind="ridgeplot", 17 | var_names=["defs"], 18 | linewidth=4, 19 | combined=True, 20 | ridgeplot_overlap=1.5, 21 | figsize=(11.5, 5), 22 | ) 23 | axes[0].set_title("Relative defensive strength\nof Six Nation rugby teams") 24 | 25 | plt.show() 26 | -------------------------------------------------------------------------------- /doc/source/getting_started/schools.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int J; 3 | array[J] real y; 4 | array[J] real sigma; 5 | } 6 | 7 | parameters { 8 | real mu; 9 | real tau; 10 | array[J] real theta; 11 | } 12 | 13 | model { 14 | mu ~ normal(0, 5); 15 | tau ~ cauchy(0, 5); 16 | theta ~ normal(mu, tau); 17 | y ~ normal(theta, sigma); 18 | } 19 | generated quantities { 20 | array[J] real log_lik; 21 | array[J] real y_hat; 22 | for (j in 1:J) { 23 | log_lik[j] = normal_lpdf(y[j] | theta[j], sigma[j]); 24 | y_hat[j] = normal_rng(theta[j], sigma[j]); 25 | } 26 | } -------------------------------------------------------------------------------- /arviz/data/io_datatree.py: -------------------------------------------------------------------------------- 1 | """Conversion between InferenceData and DataTree.""" 2 | 3 | from .inference_data import InferenceData 4 | 5 | 6 | def to_datatree(data): 7 | """Convert InferenceData object to a :class:`~datatree.DataTree`. 8 | 9 | Parameters 10 | ---------- 11 | data : InferenceData 12 | """ 13 | return data.to_datatree() 14 | 15 | 16 | def from_datatree(datatree): 17 | """Create an InferenceData object from a :class:`~datatree.DataTree`. 18 | 19 | Parameters 20 | ---------- 21 | datatree : DataTree 22 | """ 23 | return InferenceData.from_datatree(datatree) 24 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_violin_single_sided.py: -------------------------------------------------------------------------------- 1 | """ 2 | Single sided Violinplot 3 | ======================= 4 | 5 | _thumb: .2, .8 6 | """ 7 | 8 | import arviz as az 9 | 10 | data = az.load_arviz_data("rugby") 11 | labeller = az.labels.MapLabeller(var_name_map={"defs": "atts | defs"}) 12 | 13 | p1 = az.plot_violin( 14 | data.posterior["atts"], side="left", backend="bokeh", show=False, labeller=labeller 15 | ) 16 | p2 = az.plot_violin( 17 | data.posterior["defs"], 18 | side="right", 19 | ax=p1, 20 | backend="bokeh", 21 | shade_kwargs={"color": "lightsalmon"}, 22 | labeller=labeller, 23 | ) 24 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_posterior.py: -------------------------------------------------------------------------------- 1 | """ 2 | Posterior Plot 3 | ============== 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("centered_eight") 14 | 15 | coords = {"school": ["Choate"]} 16 | axes = az.plot_posterior( 17 | data, 18 | var_names=["mu", "theta"], 19 | coords=coords, 20 | rope=(-1, 1), 21 | figsize=(11.5, 5), 22 | ) 23 | 24 | fig = axes.flatten()[0].get_figure() 25 | fig.suptitle("Centered Eight: mu and theta for Choate") 26 | 27 | plt.show() 28 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_pair_kde_hdi.py: -------------------------------------------------------------------------------- 1 | """ 2 | KDE Pair Plot with HDI Contours 3 | =============================== 4 | """ 5 | 6 | import arviz as az 7 | 8 | centered = az.load_arviz_data("centered_eight") 9 | 10 | coords = {"school": ["Choate", "Deerfield"]} 11 | az.plot_pair( 12 | centered, 13 | var_names=["theta", "mu", "tau"], 14 | kind="kde", 15 | coords=coords, 16 | divergences=True, 17 | textsize=22, 18 | kde_kwargs={ 19 | "hdi_probs": [0.3, 0.6, 0.9], # Plot 30%, 60% and 90% HDI contours 20 | "contourf_kwargs": {"cmap": "Blues"}, 21 | }, 22 | backend="bokeh", 23 | ) 24 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_kde_2d_hdi.py: -------------------------------------------------------------------------------- 1 | """ 2 | 2D KDE with HDI Contours 3 | ======================== 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | 10 | import arviz as az 11 | 12 | az.style.use("arviz-doc") 13 | 14 | rng = np.random.default_rng() 15 | data = rng.multivariate_normal([2, 2], [[1, 0.4], [0.4, 0.8]], 1000000) 16 | 17 | ax = az.plot_kde( 18 | data[:, 0], 19 | data[:, 1], 20 | hdi_probs=[0.393, 0.865, 0.989], # 1, 2 and 3 sigma contours 21 | contourf_kwargs={"cmap": "Blues"}, 22 | ) 23 | 24 | ax.set_aspect("equal") 25 | plt.show() 26 | -------------------------------------------------------------------------------- /doc/source/api/utils.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: arviz 2 | 3 | Utils 4 | ----- 5 | 6 | Computing utils 7 | ............... 8 | 9 | .. autosummary:: 10 | :toctree: generated/ 11 | :template: class_no_members.rst 12 | 13 | Numba 14 | Dask 15 | 16 | Bokeh utils 17 | ........... 18 | 19 | .. autosummary:: 20 | :toctree: generated/ 21 | 22 | ColumnDataSource 23 | create_layout 24 | output_notebook 25 | output_file 26 | show_layout 27 | to_cds 28 | 29 | Matplotlib utils 30 | ................ 31 | 32 | .. autosummary:: 33 | :toctree: generated/ 34 | :template: class_no_members.rst 35 | 36 | interactive_backend 37 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_dist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dist Plot 3 | ========= 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | 10 | import arviz as az 11 | 12 | az.style.use("arviz-doc") 13 | 14 | data_poisson = np.random.poisson(4, 1000) 15 | data_gaussian = np.random.normal(0, 1, 1000) 16 | 17 | fig, ax = plt.subplots(1, 2) 18 | fig.suptitle("Distributions") 19 | 20 | ax[0].set_title("Poisson") 21 | az.plot_dist(data_poisson, color="C1", label="Poisson", ax=ax[0]) 22 | 23 | ax[1].set_title("Gaussian") 24 | az.plot_dist(data_gaussian, color="C2", label="Gaussian", ax=ax[1]) 25 | 26 | plt.show() 27 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_kde.py: -------------------------------------------------------------------------------- 1 | """ 2 | KDE Plot 3 | ======== 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | 10 | import arviz as az 11 | 12 | az.style.use("arviz-doc") 13 | 14 | data = az.load_arviz_data("centered_eight") 15 | 16 | # Combine posterior draws for from xarray of (4,500) to ndarray (2000,) 17 | y_hat = np.concatenate(data.posterior_predictive["obs"].values) 18 | 19 | az.plot_kde( 20 | y_hat, 21 | label="Estimated Effect\n of SAT Prep", 22 | rug=True, 23 | plot_kwargs={"linewidth": 2}, 24 | rug_kwargs={"alpha": 0.05}, 25 | ) 26 | 27 | plt.show() 28 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_pair_point_estimate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Point Estimate Pairplot 3 | ======================= 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("centered_eight") 14 | 15 | coords = {"school": ["Choate", "Deerfield"]} 16 | ax = az.plot_pair( 17 | data, 18 | var_names=["mu", "theta"], 19 | kind=["scatter", "kde"], 20 | kde_kwargs={"fill_last": False}, 21 | marginals=True, 22 | coords=coords, 23 | point_estimate="median", 24 | figsize=(11.5, 5), 25 | ) 26 | 27 | plt.show() 28 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_forest_comparison.py: -------------------------------------------------------------------------------- 1 | """ 2 | Forest Plot Comparison 3 | ====================== 4 | _gallery_category: Distribution Comparison 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | centered_data = az.load_arviz_data("centered_eight") 14 | non_centered_data = az.load_arviz_data("non_centered_eight") 15 | ax = az.plot_forest( 16 | [centered_data, non_centered_data], 17 | model_names=["Centered", "Non Centered"], 18 | var_names=["mu"], 19 | figsize=(11.5, 5), 20 | ) 21 | ax[0].set_title("Estimated theta for eight schools model") 22 | 23 | plt.show() 24 | -------------------------------------------------------------------------------- /arviz/data/example_data/README.md: -------------------------------------------------------------------------------- 1 | # ArviZ `InferenceData` examples 2 | 3 | This repository contains metadata of ArviZ InferenceData examples and the code used to generate some of the examples. 4 | Example models stored remotely are listed in `data_remote.json`. 5 | Example models stored locally are listed in `data_local.json`, and the data themselves are stored in `data/`. 6 | Inclusion of the code serves both as extra information on the models in the JSON files and to ease updating these examples whenever necessary. 7 | 8 | When applicable, code for a model should be added as an executable file (e.g. `.py` or `.ipynb`) to a directory in `code/` of the same name as the model. 9 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_lm.py: -------------------------------------------------------------------------------- 1 | """ 2 | Regression Plot 3 | =============== 4 | _gallery_category: Regression or Time Series 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | import xarray as xr 9 | import numpy as np 10 | import arviz as az 11 | 12 | az.style.use("arviz-doc") 13 | 14 | data = az.load_arviz_data("regression1d") 15 | x = xr.DataArray(np.linspace(0, 1, 100)) 16 | data.add_groups({"constant_data": {"x1": x}}) 17 | data.constant_data["x"] = x 18 | data.posterior["y_model"] = ( 19 | data.posterior["intercept"] + data.posterior["slope"] * data.constant_data["x"] 20 | ) 21 | az.plot_lm(idata=data, y="y", x="x", y_model="y_model") 22 | 23 | plt.show() 24 | -------------------------------------------------------------------------------- /doc/_templates/autosummary/class.rst: -------------------------------------------------------------------------------- 1 | {{ fullname | escape | underline}} 2 | 3 | .. currentmodule:: {{ module }} 4 | 5 | .. autoclass:: {{ objname }} 6 | 7 | {% block methods %} 8 | {% if methods %} 9 | 10 | .. rubric:: Methods 11 | 12 | .. autosummary:: 13 | :toctree: 14 | 15 | {% for item in methods %} 16 | {{ objname }}.{{ item }} 17 | {%- endfor %} 18 | {% endif %} 19 | {% endblock %} 20 | 21 | {% block attributes %} 22 | {% if attributes %} 23 | .. rubric:: Attributes 24 | 25 | .. autosummary:: 26 | {% for item in attributes %} 27 | ~{{ name }}.{{ item }} 28 | {%- endfor %} 29 | {% endif %} 30 | {% endblock %} 31 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 'Bug Report' 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior. Ideally a self-contained snippet of code, or link to a notebook or external code. Please include screenshots/images produced with ArviZ here, or the stacktrace including `arviz` code to help. 12 | 13 | **Expected behavior** 14 | A clear and concise description of what you expected to happen. 15 | 16 | **Additional context** 17 | Versions of `arviz` and other libraries used, operating system used, and anything else that may be useful. 18 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_density.py: -------------------------------------------------------------------------------- 1 | """ 2 | Density Plot (Comparison) 3 | ========================= 4 | _gallery_category: Distribution Comparison 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | centered_data = az.load_arviz_data("centered_eight") 14 | non_centered_data = az.load_arviz_data("non_centered_eight") 15 | 16 | axes = az.plot_density( 17 | [centered_data, non_centered_data], 18 | data_labels=["Centered", "Non-Centered"], 19 | var_names=["theta"], 20 | shade=0.2, 21 | ) 22 | 23 | fig = axes.flatten()[0].get_figure() 24 | fig.suptitle("94% High Density Intervals for Theta") 25 | 26 | plt.show() 27 | -------------------------------------------------------------------------------- /doc/_templates/class_no_members.rst: -------------------------------------------------------------------------------- 1 | {{ fullname | escape | underline}} 2 | 3 | .. currentmodule:: {{ module }} 4 | 5 | .. autoclass:: {{ objname }} 6 | 7 | {% block methods %} 8 | {% if methods %} 9 | 10 | .. rubric:: Methods 11 | 12 | .. autosummary:: 13 | {% for item in methods %} 14 | {% if item != "__init__" %} 15 | {{ item }} 16 | {% endif %} 17 | {%- endfor %} 18 | {% endif %} 19 | {% endblock %} 20 | 21 | {% block attributes %} 22 | {% if attributes %} 23 | .. rubric:: Attributes 24 | 25 | .. autosummary:: 26 | {% for item in attributes %} 27 | ~{{ name }}.{{ item }} 28 | {%- endfor %} 29 | {% endif %} 30 | {% endblock %} 31 | -------------------------------------------------------------------------------- /doc/source/api/plots.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: arviz 2 | 3 | .. _plot_api: 4 | 5 | Plots 6 | ----- 7 | 8 | .. autosummary:: 9 | :toctree: generated/ 10 | 11 | plot_autocorr 12 | plot_bf 13 | plot_bpv 14 | plot_compare 15 | plot_density 16 | plot_dist 17 | plot_dist_comparison 18 | plot_dot 19 | plot_ecdf 20 | plot_elpd 21 | plot_energy 22 | plot_ess 23 | plot_forest 24 | plot_hdi 25 | plot_kde 26 | plot_khat 27 | plot_loo_pit 28 | plot_lm 29 | plot_mcse 30 | plot_pair 31 | plot_parallel 32 | plot_posterior 33 | plot_ppc 34 | plot_rank 35 | plot_separation 36 | plot_trace 37 | plot_ts 38 | plot_violin 39 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_pair_kde_hdi.py: -------------------------------------------------------------------------------- 1 | """ 2 | KDE Pair Plot with HDI Contours 3 | =============================== 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | centered = az.load_arviz_data("centered_eight") 14 | 15 | coords = {"school": ["Choate", "Deerfield"]} 16 | az.plot_pair( 17 | centered, 18 | var_names=["theta", "mu", "tau"], 19 | kind="kde", 20 | coords=coords, 21 | textsize=22, 22 | kde_kwargs={ 23 | "hdi_probs": [0.3, 0.6, 0.9], # Plot 30%, 60% and 90% HDI contours 24 | "contourf_kwargs": {"cmap": "Blues"}, 25 | }, 26 | ) 27 | plt.show() 28 | -------------------------------------------------------------------------------- /doc/_templates/edit-this-page.html: -------------------------------------------------------------------------------- 1 | {% if sourcename is defined and theme_use_edit_page_button==true and page_source_suffix and "generated" not in sourcename %} 2 | {% set src = sourcename.split('.') %} 3 | 16 | {% endif %} 17 | -------------------------------------------------------------------------------- /scripts/README.md: -------------------------------------------------------------------------------- 1 | # Scripts 2 | Various scripts that help with ArviZ maintenance 3 | 4 | #### container.sh 5 | Script that helps with building docker image, and running jupyter lab, 6 | jupyter notebooks, building docs, or getting a shell or testing 7 | 8 | #### container.ps1 9 | Same as container.sh 10 | 11 | Example: 12 | 13 | `powershell -File container.ps1 --lab` 14 | 15 | #### create_testenv.sh 16 | Script that helps install ArviZ on whatever computer is being used 17 | 18 | #### lint.sh 19 | Run all linters to check for code quality deviations 20 | 21 | #### install_miniconda.sh 22 | Install miniconda code environment managers and creates arviz environment 23 | 24 | #### Dockerfile 25 | Dockerfile for ArviZ image 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 'Feature Request' 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | ## Tell us about it 8 | 9 | The more specific the better. You can assume you have access to any combination of datasets defined in the schema. When considering an implementation, keep in mind that 10 | 11 | - models in ArviZ can have one, or lots, of random variables, 12 | - each random variable can have very few or millions of draws, 13 | - each random variable can have 0 or many dimensions. 14 | 15 | ## Thoughts on implementation 16 | 17 | Not required, but if you have thoughts on how to implement the feature, that can be helpful! In case there are academic references, we welcome those here too. 18 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_posterior_combinedims.py: -------------------------------------------------------------------------------- 1 | """ 2 | Posterior Plot (reducing school dimension) 3 | ========================================== 4 | _gallery_category: Distributions 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("centered_eight") 14 | 15 | coords = {"school": ["Choate", "Mt. Hermon", "Deerfield"]} 16 | axes = az.plot_posterior( 17 | data, 18 | var_names=["mu", "theta"], 19 | combine_dims={"school"}, 20 | coords=coords, 21 | figsize=(11.5, 5), 22 | ) 23 | 24 | fig = axes.flatten()[0].get_figure() 25 | fig.suptitle("Centered Eight: mu and theta for reduced school dimension") 26 | 27 | plt.show() 28 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # Python package 2 | # Create and test a Python package on multiple Python versions. 3 | # Add steps that analyze code, save the dist with the build record, publish to a PyPI-compatible index, and more: 4 | # https://docs.microsoft.com/azure/devops/pipelines/languages/python 5 | # -*- mode: yaml -*- 6 | trigger: 7 | branches: 8 | include: 9 | - main 10 | tags: 11 | include: 12 | - '*' 13 | 14 | pr: 15 | branches: 16 | include: 17 | - main 18 | 19 | jobs: 20 | - template: .azure-pipelines/azure-pipelines-base.yml 21 | - template: .azure-pipelines/azure-pipelines-external.yml 22 | - template: .azure-pipelines/azure-pipelines-benchmarks.yml 23 | - template: .azure-pipelines/azure-pipelines-wheel.yml 24 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_dist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dist Plot Bokeh 3 | =============== 4 | """ 5 | 6 | import bokeh.plotting as bkp 7 | import numpy as np 8 | from bokeh.layouts import row 9 | 10 | import arviz as az 11 | 12 | a = np.random.poisson(4, 1000) 13 | b = np.random.normal(0, 1, 1000) 14 | 15 | figure_kwargs = dict(height=500, width=500, output_backend="webgl") 16 | ax_poisson = bkp.figure(**figure_kwargs) 17 | ax_normal = bkp.figure(**figure_kwargs) 18 | 19 | az.plot_dist(a, color="black", label="Poisson", ax=ax_poisson, backend="bokeh", show=False) 20 | az.plot_dist(b, color="red", label="Gaussian", ax=ax_normal, backend="bokeh", show=False) 21 | 22 | ax = row(ax_poisson, ax_normal) 23 | 24 | if az.rcParams["plot.bokeh.show"]: 25 | bkp.show(ax) 26 | -------------------------------------------------------------------------------- /examples/bokeh/bokeh_plot_kde.py: -------------------------------------------------------------------------------- 1 | """ 2 | KDE Plot Bokeh 3 | ============== 4 | """ 5 | 6 | import bokeh.plotting as bkp 7 | import numpy as np 8 | 9 | import arviz as az 10 | 11 | data = az.load_arviz_data("centered_eight") 12 | 13 | # Combine posterior draws for from xarray of (4,500) to ndarray (2000,) 14 | y_hat = np.concatenate(data.posterior_predictive["obs"].values) 15 | 16 | figure_kwargs = dict(height=500, width=500, output_backend="webgl") 17 | ax = bkp.figure(**figure_kwargs) 18 | 19 | ax = az.plot_kde( 20 | y_hat, 21 | label="Estimated Effect\n of SAT Prep", 22 | rug=True, 23 | plot_kwargs={"line_width": 2, "line_color": "black"}, 24 | rug_kwargs={"line_color": "black"}, 25 | backend="bokeh", 26 | ax=ax, 27 | ) 28 | -------------------------------------------------------------------------------- /arviz/tests/base_tests/test_helpers.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from _pytest.outcomes import Skipped 3 | 4 | from ..helpers import importorskip 5 | 6 | 7 | def test_importorskip_local(monkeypatch): 8 | """Test ``importorskip`` run on local machine with non-existent module, which should skip.""" 9 | monkeypatch.delenv("ARVIZ_REQUIRE_ALL_DEPS", raising=False) 10 | with pytest.raises(Skipped): 11 | importorskip("non-existent-function") 12 | 13 | 14 | def test_importorskip_ci(monkeypatch): 15 | """Test ``importorskip`` run on CI machine with non-existent module, which should fail.""" 16 | monkeypatch.setenv("ARVIZ_REQUIRE_ALL_DEPS", 1) 17 | with pytest.raises(ModuleNotFoundError): 18 | importorskip("non-existent-function") 19 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = -b html 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = ArviZ 8 | SOURCEDIR = doc/source 9 | BUILDDIR = doc/build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | html: 18 | sphinx-build "$(SOURCEDIR)" "$(BUILDDIR)" -b html 19 | 20 | livehtml: 21 | sphinx-autobuild "$(SOURCEDIR)" "$(BUILDDIR)" -b html 22 | 23 | cleandocs: 24 | rm -r "$(BUILDDIR)" "doc/jupyter_execute" "$(SOURCEDIR)/api/generated" "$(SOURCEDIR)/examples" 25 | 26 | preview: 27 | python -m webbrowser "$(BUILDDIR)/index.html" 28 | -------------------------------------------------------------------------------- /.projections.json: -------------------------------------------------------------------------------- 1 | { 2 | "arviz/plots/backends/matplotlib/*.py": { 3 | "alternate": "arviz/plots/backends/bokeh/{}.py", 4 | "related": "arviz/plots/{}.py", 5 | "type": "mpl" 6 | }, 7 | "arviz/plots/backends/bokeh/*.py": { 8 | "alternate": "arviz/plots/backends/matplotlib/{}.py", 9 | "related": "arviz/plots/{}.py", 10 | "type": "bokeh" 11 | }, 12 | "arviz/plots/*.py": { 13 | "alternate": "arviz/plots/backends/matplotlib/{}.py", 14 | "related": "arviz/plots/backends/bokeh/{}.py", 15 | "type": "base" 16 | }, 17 | "arviz/data/io_*.py": { 18 | "alternate": "arviz/tests/external_tests/test_data_{}.py", 19 | "type": "converter" 20 | }, 21 | "arviz/tests/external_tests/test_data_*.py": { 22 | "alternate": "arviz/data/io_{}.py", 23 | "type": "test" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /doc/source/api/plot_utils.md: -------------------------------------------------------------------------------- 1 | ```{eval-rst} 2 | .. currentmodule:: arviz.labels 3 | ``` 4 | # Plot utils 5 | 6 | (labeller_api)= 7 | ## Labellers 8 | See also the {ref}`label_guide` 9 | 10 | ```{eval-rst} 11 | .. autosummary:: 12 | :toctree: generated/ 13 | 14 | BaseLabeller 15 | DimCoordLabeller 16 | IdxLabeller 17 | DimIdxLabeller 18 | MapLabeller 19 | NoModelLabeller 20 | NoVarLabeller 21 | ``` 22 | 23 | ## Labeling utils 24 | 25 | ```{eval-rst} 26 | .. autosummary:: 27 | :toctree: generated/ 28 | 29 | mix_labellers 30 | ``` 31 | 32 | ## Xarray utils 33 | Low level functions to iterate over xarray objects. 34 | 35 | ```{eval-rst} 36 | .. currentmodule:: arviz.sel_utils 37 | 38 | .. autosummary:: 39 | :toctree: generated/ 40 | 41 | xarray_sel_iter 42 | xarray_var_iter 43 | xarray_to_ndarray 44 | ``` 45 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_plot_violin_single_sided.py: -------------------------------------------------------------------------------- 1 | """ 2 | Single-Sided Violin Plot 3 | ======================== 4 | _gallery_category: Distribution Comparison 5 | """ 6 | 7 | import matplotlib.pyplot as plt 8 | 9 | import arviz as az 10 | 11 | az.style.use("arviz-doc") 12 | 13 | data = az.load_arviz_data("rugby") 14 | 15 | labeller = az.labels.MapLabeller(var_name_map={"defs": "atts | defs"}) 16 | axes = az.plot_violin( 17 | data, 18 | var_names=["atts"], 19 | side="left", 20 | show=False, 21 | figsize=(11.5, 5), 22 | ) 23 | az.plot_violin( 24 | data, 25 | var_names=["defs"], 26 | side="right", 27 | labeller=labeller, 28 | ax=axes, 29 | show=True, 30 | ) 31 | 32 | fig = axes.flatten()[0].get_figure() 33 | fig.suptitle("Attack/Defense of Rugby Teams") 34 | fig.tight_layout() 35 | 36 | plt.show() 37 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/usage-question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 'Usage Question' 3 | about: General questions about ArviZ usage 4 | 5 | --- 6 | 7 | ## Short Description 8 | 9 | Let us know what you're trying to do and we can point you in the right direction. Screenshots/plots or stack traces that include `arviz` are particularly helpful. 10 | 11 | ## Code Example or link 12 | 13 | Please provide a minimal, self-contained, and reproducible example demonstrating what you're trying to do. Ideally it will be a code snippet, link to a notebook, or link to code that can be run on another user's computer. 14 | 15 | Also include the ArviZ version and version of any other relevant packages. 16 | 17 | ## Relevant documentation or public examples 18 | 19 | Please provide documentation, public examples, or any additional information which may be relevant to your question 20 | -------------------------------------------------------------------------------- /doc/source/user_guide/sampling_wrappers.md: -------------------------------------------------------------------------------- 1 | (wrapper_guide)= 2 | # Sampling wrappers 3 | Sampling wrappers allow ArviZ to call {abbr}`PPL (Probabilistic programming library)`s in order to perform a limited 4 | subset of their capabilities and calculate stats and diagnostics that require 5 | refitting the model on different data. 6 | 7 | Their implementation is still experimental and may vary in the future. In fact, 8 | there are currently two possible approaches when creating sampling wrappers. 9 | The first one delegates all calculations to the PPL 10 | whereas the second one externalizes the computation of the pointwise log 11 | likelihood to the user who is expected to write it with xarray/NumPy. 12 | 13 | ```{toctree} 14 | wrappers/cmdstanpy_refitting 15 | pystan_refitting 16 | pymc_refitting 17 | numpyro_refitting 18 | numpyro_refitting_xr_lik 19 | ``` 20 | -------------------------------------------------------------------------------- /arviz/stats/__init__.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=wildcard-import 2 | """Statistical tests and diagnostics for ArviZ.""" 3 | from .density_utils import * 4 | from .diagnostics import * 5 | from .stats import * 6 | from .stats import _calculate_ics 7 | from .stats_refitting import * 8 | from .stats_utils import * 9 | 10 | __all__ = [ 11 | "apply_test_function", 12 | "bfmi", 13 | "compare", 14 | "hdi", 15 | "kde", 16 | "loo", 17 | "loo_pit", 18 | "psislw", 19 | "r2_samples", 20 | "r2_score", 21 | "summary", 22 | "waic", 23 | "weight_predictions", 24 | "ELPDData", 25 | "ess", 26 | "rhat", 27 | "mcse", 28 | "autocorr", 29 | "autocov", 30 | "make_ufunc", 31 | "smooth_data", 32 | "wrap_xarray_ufunc", 33 | "reloo", 34 | "_calculate_ics", 35 | "psens", 36 | ] 37 | -------------------------------------------------------------------------------- /doc/source/contributing/updating_example_data.md: -------------------------------------------------------------------------------- 1 | # Updating the example data 2 | 3 | Metadata for ArviZ's example `InferenceData` objects (which are loadable by {func}`~arviz.load_arviz_data`) is stored in the [`arviz_example_data`](https://github.com/arviz-devs/arviz_example_data) repository. 4 | This repo has been embedded into the `arviz` repo at `/arviz/data/example_data` using [git subtree](https://www.atlassian.com/git/tutorials/git-subtree) with the following command: 5 | 6 | ```bash 7 | $ git subtree add --prefix arviz/data/example_data https://github.com/arviz-devs/arviz_example_data.git main --squash 8 | ``` 9 | 10 | When `arviz_example_data` is updated, the subtree within the `arviz` repo also needs to be updated with the following command: 11 | 12 | ```bash 13 | $ git subtree pull --prefix arviz/data/example_data https://github.com/arviz-devs/arviz_example_data.git main --squash 14 | ``` 15 | -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | cff-version: 1.2.0 2 | message: "If you use this software, please cite it as below." 3 | title: "ArviZ" 4 | url: "https://github.com/arviz-devs/arviz" 5 | preferred-citation: 6 | type: article 7 | authors: 8 | - 9 | family-names: Kumar 10 | given-names: Ravin 11 | orcid: "https://orcid.org/0000-0003-0501-6098" 12 | - 13 | family-names: Carroll 14 | given-names: Colin 15 | orcid: "https://orcid.org/0000-0001-6977-0861" 16 | - 17 | family-names: Hartikainen 18 | given-names: Ari 19 | orcid: "https://orcid.org/0000-0002-4569-569X" 20 | - 21 | family-names: Osvaldo 22 | given-names: Martin 23 | orcid: "https://orcid.org/0000-0001-7419-8978" 24 | doi: "10.21105/joss.01143" 25 | journal: "Journal of Open Source Software" 26 | title: "ArviZ a unified library for exploratory analysis of Bayesian models in Python" 27 | -------------------------------------------------------------------------------- /doc/source/user_guide/wrappers/linreg_prior.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | real time_since_joined[N]; 4 | } 5 | 6 | generated quantities { 7 | real b0; 8 | real b1; 9 | real log_b_sigma; 10 | real b_sigma; 11 | 12 | real c0; 13 | real c1; 14 | real log_c_sigma; 15 | real c_sigma; 16 | 17 | vector[N] slack_comments_hat; 18 | vector[N] github_commits_hat; 19 | 20 | b0 = normal_rng(0,200); 21 | b1 = normal_rng(0,200); 22 | b_sigma = abs(normal_rng(0,300)); 23 | log_b_sigma = log(b_sigma); 24 | 25 | c0 = normal_rng(0,10); 26 | c1 = normal_rng(0,10); 27 | c_sigma = fabs(normal_rng(0,6)); 28 | log_c_sigma = log(b_sigma); 29 | 30 | for (n in 1:N) { 31 | slack_comments_hat[n] = normal_rng(b0 + b1 * time_since_joined[n], b_sigma); 32 | github_commits_hat[n] = normal_rng(c0 + c1 * time_since_joined[n], c_sigma); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /doc/source/contributing/architecture.md: -------------------------------------------------------------------------------- 1 | # Library architecture 2 | ArviZ is organized in modules (the folders in [arviz directory](https://github.com/arviz-devs/arviz/tree/main/arviz)). 3 | The main 3 modules are `data`, `plots` and `stats`. 4 | Then we have 3 more folders. The [tests](https://github.com/arviz-devs/arviz/tree/main/arviz/tests) 5 | folder contains tests for all these 3 modules. 6 | 7 | The [static](https://github.com/arviz-devs/arviz/tree/main/arviz/static) 8 | folder is only used to store style and CSS files to get HTML output for `InferenceData`. 9 | Finally we have the [wrappers](https://github.com/arviz-devs/arviz/tree/main/arviz/wrappers) 10 | folder that contains experimental (not tested yet either) features 11 | and interacts closely with both [data](https://github.com/arviz-devs/arviz/tree/main/arviz/data) 12 | and [stats](https://github.com/arviz-devs/arviz/tree/main/arviz/stats) modules. 13 | 14 | In addition, there are some files on the higher level directory: `utils.py`, `sel_utils.py`, 15 | `rcparams.py` and `labels.py`. 16 | -------------------------------------------------------------------------------- /doc/source/contributing/doc_toolchain.md: -------------------------------------------------------------------------------- 1 | (doc_toolchain)= 2 | # Documentation toolchain 3 | 4 | ArviZ documentation is built using a Python documentation tool, [Sphinx](https://www.sphinx-doc.org/en/master/). 5 | Sphinx converts `rst`(restructured text) files into HTML websites. 6 | There are different extensions available for converting other types of files 7 | like markdown, jupyter notebooks, etc. into HTML websites. 8 | 9 | ArviZ [docs](https://github.com/arviz-devs/arviz/tree/main/doc/source) consist of `.rst`, `.md` and `.ipynb` files. 10 | It uses `myst-parser` and `myst-nb` for `.md` and `.ipynb` files. 11 | Apart from the content in the `/doc/source` folder, ArviZ documentation also consists of docstrings. 12 | Docstrings are used in the `.py` files to explain the Python objects parameters and return values. 13 | 14 | ArviZ docs also uses sphinx extensions for style, layout, navbar and putting code in the documentation. 15 | 16 | A more detailed overview of the sphinx toolchain used at ArviZ is available at 17 | {doc}`sphinx-primer:index` 18 | -------------------------------------------------------------------------------- /doc/source/api/data.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: arviz 2 | 3 | .. _data_api: 4 | 5 | Data 6 | ---- 7 | 8 | Inference library converters 9 | ............................ 10 | 11 | .. autosummary:: 12 | :toctree: generated/ 13 | 14 | from_beanmachine 15 | from_cmdstan 16 | from_cmdstanpy 17 | from_emcee 18 | from_numpyro 19 | from_pyjags 20 | from_pyro 21 | from_pystan 22 | 23 | 24 | IO / General conversion 25 | ....................... 26 | 27 | .. autosummary:: 28 | :toctree: generated/ 29 | 30 | convert_to_inference_data 31 | convert_to_dataset 32 | dict_to_dataset 33 | from_datatree 34 | from_dict 35 | from_json 36 | from_netcdf 37 | to_datatree 38 | to_json 39 | to_netcdf 40 | from_zarr 41 | to_zarr 42 | 43 | 44 | General functions 45 | ................. 46 | 47 | .. autosummary:: 48 | :toctree: generated/ 49 | 50 | concat 51 | extract 52 | 53 | Data examples 54 | ............. 55 | 56 | .. autosummary:: 57 | :toctree: generated/ 58 | 59 | list_datasets 60 | load_arviz_data 61 | -------------------------------------------------------------------------------- /doc/source/_static/key_feature_diagnostics.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /arviz/data/example_data/data_local.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "centered_eight", 4 | "filename": "centered_eight.nc", 5 | "description": "A centered parameterization of the eight schools model. Provided as an example of a model that NUTS has trouble fitting. Compare to `non_centered_eight`.\n\nThe eight schools model is a hierarchical model used for an analysis of the effectiveness of classes that were designed to improve students' performance on the Scholastic Aptitude Test.\n\nSee Bayesian Data Analysis (Gelman et. al.) for more details." 6 | }, 7 | { 8 | "name": "non_centered_eight", 9 | "filename": "non_centered_eight.nc", 10 | "description": "A non-centered parameterization of the eight schools model. This is a hierarchical model where sampling problems may be fixed by a non-centered parametrization. Compare to `centered_eight`.\n\nThe eight schools model is a hierarchical model used for an analysis of the effectiveness of classes that were designed to improve students' performance on the Scholastic Aptitude Test.\n\nSee Bayesian Data Analysis (Gelman et. al.) for more details." 11 | } 12 | ] -------------------------------------------------------------------------------- /doc/_templates/404.html: -------------------------------------------------------------------------------- 1 | {% extends "!layout.html" %} 2 | 3 | {%- block content %} 4 | {% block docs_navbar %} {{ super() }} {% endblock %} 5 | 6 |
7 |
8 | {% block docs_main %} 9 |
10 |
11 |
12 | 13 |
14 |
Page not found
15 |

Sorry, it looks like your sampler ventured to an undefined region of the documentation space.

16 |

The page you are looking for could not be found.

17 |

Click on the link below to go back to home page (the navbar links are probably not working either).

18 | Back to Home Page 19 |
20 |
21 |
22 |
23 | {% endblock %} 24 | 25 |
26 |
27 | {%- endblock %} 28 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-whitegrid.mplstyle: -------------------------------------------------------------------------------- 1 | # This style is based on Seaborn-whitegrid parameters, the main differences are 2 | # Default matplotlib font (no problem using Greek letters!) 3 | # Larger font size for several elements 4 | # Colorblind friendly color cycle 5 | figure.figsize: 7.2, 4.8 6 | figure.dpi: 100.0 7 | figure.facecolor: white 8 | figure.constrained_layout.use: True 9 | text.color: .15 10 | axes.labelcolor: .15 11 | legend.frameon: False 12 | legend.numpoints: 1 13 | legend.scatterpoints: 1 14 | xtick.direction: out 15 | ytick.direction: out 16 | xtick.color: .15 17 | ytick.color: .15 18 | axes.axisbelow: True 19 | grid.linestyle: - 20 | lines.solid_capstyle: round 21 | 22 | axes.labelsize: 15 23 | axes.titlesize: 16 24 | xtick.labelsize: 14 25 | ytick.labelsize: 14 26 | legend.fontsize: 14 27 | 28 | axes.grid: True 29 | axes.facecolor: white 30 | axes.edgecolor: .8 31 | axes.linewidth: 1 32 | grid.color: .8 33 | image.cmap: viridis 34 | xtick.major.size: 0 35 | ytick.major.size: 0 36 | xtick.minor.size: 0 37 | ytick.minor.size: 0 38 | 39 | # color-blind friendly cycle designed using https://colorcyclepicker.mpetroff.net/ 40 | axes.prop_cycle: cycler('color', ['2a2eec', 'fa7c17', '328c06', 'c10c90', '933708', '65e5f3', 'e6e135', '1ccd6a', 'bd8ad5', 'b16b57']) 41 | -------------------------------------------------------------------------------- /scripts/install_miniconda.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e # fail on first error 4 | 5 | if conda --version > /dev/null 2>&1; then 6 | echo "conda appears to already be installed" 7 | exit 0 8 | fi 9 | 10 | INSTALL_FOLDER="$HOME/miniconda" 11 | 12 | 13 | if [ ! -d $INSTALL_FOLDER ] || [ ! -e $INSTALL_FOLDER/bin/conda ]; then 14 | if [ "$(uname)" == "Darwin" ]; then 15 | URL_OS="MacOSX" 16 | elif [ "$(expr substr "$(uname -s)" 1 5)" == "Linux" ]; then 17 | URL_OS="Linux" 18 | elif [ "$(expr substr "$(uname -s)" 1 10)" == "MINGW32_NT" ]; then 19 | URL_OS="Windows" 20 | fi 21 | 22 | echo "Downloading miniconda for $URL_OS" 23 | DOWNLOAD_PATH="miniconda.sh" 24 | wget http://repo.continuum.io/miniconda/Miniconda3-latest-$URL_OS-x86_64.sh -O ${DOWNLOAD_PATH}; 25 | 26 | echo "Installing miniconda to $INSTALL_FOLDER" 27 | # install miniconda to home folder 28 | bash ${DOWNLOAD_PATH} -b -f -p $INSTALL_FOLDER 29 | 30 | # tidy up 31 | rm ${DOWNLOAD_PATH} 32 | else 33 | echo "Miniconda already installed at ${INSTALL_FOLDER}. Updating, adding to path and exiting" 34 | fi 35 | 36 | export PATH="$INSTALL_FOLDER/bin:$PATH" 37 | echo "Adding $INSTALL_FOLDER to PATH. Consider adding it in your .rc file as well." 38 | conda update -q -y conda 39 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-darkgrid.mplstyle: -------------------------------------------------------------------------------- 1 | # This style is based on Seaborn-darkgrid parameters, the main differences are 2 | # Default matplotlib font (no problem using Greek letters!) 3 | # Larger font size for several elements 4 | # Colorblind friendly color cycle 5 | figure.figsize: 7.2, 4.8 6 | figure.dpi: 100.0 7 | figure.facecolor: white 8 | figure.constrained_layout.use: True 9 | text.color: .15 10 | axes.labelcolor: .15 11 | legend.frameon: False 12 | legend.numpoints: 1 13 | legend.scatterpoints: 1 14 | xtick.direction: out 15 | ytick.direction: out 16 | xtick.color: .15 17 | ytick.color: .15 18 | axes.axisbelow: True 19 | grid.linestyle: - 20 | lines.solid_capstyle: round 21 | 22 | axes.labelsize: 15 23 | axes.titlesize: 16 24 | xtick.labelsize: 14 25 | ytick.labelsize: 14 26 | legend.fontsize: 14 27 | 28 | axes.grid: True 29 | axes.facecolor: eeeeee 30 | axes.edgecolor: white 31 | axes.linewidth: 0 32 | grid.color: white 33 | image.cmap: viridis 34 | xtick.major.size: 0 35 | ytick.major.size: 0 36 | xtick.minor.size: 0 37 | ytick.minor.size: 0 38 | 39 | # color-blind friendly cycle designed using https://colorcyclepicker.mpetroff.net/ 40 | axes.prop_cycle: cycler('color', ['2a2eec', 'fa7c17', '328c06', 'c10c90', '933708', '65e5f3', 'e6e135', '1ccd6a', 'bd8ad5', 'b16b57']) 41 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-white.mplstyle: -------------------------------------------------------------------------------- 1 | # This style is based on Seaborn-white parameters, the main differences are 2 | # Default matplotlib font (no problem using Greek letters!) 3 | # Larger font size for several elements 4 | # Colorblind friendly color cycle 5 | figure.figsize: 7.2, 4.8 6 | figure.dpi: 100.0 7 | figure.facecolor: white 8 | figure.constrained_layout.use: True 9 | text.color: .15 10 | axes.labelcolor: .15 11 | legend.frameon: False 12 | legend.numpoints: 1 13 | legend.scatterpoints: 1 14 | xtick.direction: out 15 | ytick.direction: out 16 | xtick.color: .15 17 | ytick.color: .15 18 | axes.axisbelow: True 19 | lines.solid_capstyle: round 20 | 21 | axes.labelsize: 15 22 | axes.titlesize: 16 23 | xtick.labelsize: 14 24 | ytick.labelsize: 14 25 | legend.fontsize: 14 26 | 27 | axes.grid: False 28 | axes.facecolor: white 29 | axes.edgecolor: 0 30 | axes.linewidth: 1 31 | axes.spines.top: False 32 | axes.spines.right: False 33 | image.cmap: viridis 34 | xtick.major.size: 0 35 | ytick.major.size: 0 36 | xtick.minor.size: 0 37 | ytick.minor.size: 0 38 | 39 | # color-blind friendly cycle designed using https://colorcyclepicker.mpetroff.net/ 40 | axes.prop_cycle: cycler('color', ['2a2eec', 'fa7c17', '328c06', 'c10c90', '933708', '65e5f3', 'e6e135', '1ccd6a', 'bd8ad5', 'b16b57']) 41 | -------------------------------------------------------------------------------- /doc/source/user_guide/wrappers/linreg_ex_model.stan: -------------------------------------------------------------------------------- 1 | data { 2 | // Define data for fitting 3 | int N; 4 | array[N] real x; 5 | array[N] real y; 6 | // Define excluded data. It will not be used when fitting. 7 | int N_ex; 8 | array[N_ex] real x_ex; 9 | array[N_ex] real y_ex; 10 | } 11 | 12 | parameters { 13 | real b0; 14 | real b1; 15 | real sigma_e; 16 | } 17 | 18 | model { 19 | b0 ~ normal(0, 10); 20 | b1 ~ normal(0, 10); 21 | sigma_e ~ normal(0, 10); 22 | for (i in 1:N) { 23 | y[i] ~ normal(b0 + b1 * x[i], sigma_e); // use only data for fitting 24 | } 25 | 26 | } 27 | 28 | generated quantities { 29 | array[N] real log_lik; 30 | array[N_ex] real log_lik_ex; 31 | array[N] real y_hat; 32 | 33 | for (i in 1:N) { 34 | // calculate log likelihood and posterior predictive, there are 35 | // no restrictions on adding more generated quantities 36 | log_lik[i] = normal_lpdf(y[i] | b0 + b1 * x[i], sigma_e); 37 | y_hat[i] = normal_rng(b0 + b1 * x[i], sigma_e); 38 | } 39 | for (j in 1:N_ex) { 40 | // calculate the log likelihood of the excluded data given data_for_fitting 41 | log_lik_ex[j] = normal_lpdf(y_ex[j] | b0 + b1 * x_ex[j], sigma_e); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /arviz/wrappers/wrap_pymc.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=arguments-differ 2 | """Base class for PyMC interface wrappers.""" 3 | from .base import SamplingWrapper 4 | 5 | 6 | # pylint: disable=abstract-method 7 | class PyMCSamplingWrapper(SamplingWrapper): 8 | """PyMC (4.0+) sampling wrapper base class. 9 | 10 | See the documentation on :class:`~arviz.SamplingWrapper` for a more detailed 11 | description. An example of ``PyMCSamplingWrapper`` usage can be found 12 | in the :ref:`pymc_refitting` notebook. 13 | 14 | Warnings 15 | -------- 16 | Sampling wrappers are an experimental feature in a very early stage. Please use them 17 | with caution. 18 | """ 19 | 20 | def sample(self, modified_observed_data): 21 | """Update data and sample model on modified_observed_data.""" 22 | import pymc # pylint: disable=import-error 23 | 24 | with self.model: 25 | pymc.set_data(modified_observed_data) 26 | idata = pymc.sample( 27 | **self.sample_kwargs, 28 | ) 29 | return idata 30 | 31 | def get_inference_data(self, fitted_model): 32 | """Return sampling result without modifying. 33 | 34 | PyMC sampling already returns and InferenceData object. 35 | """ 36 | return fitted_model 37 | -------------------------------------------------------------------------------- /arviz/data/io_zarr.py: -------------------------------------------------------------------------------- 1 | """Input and output support for zarr data.""" 2 | 3 | from .converters import convert_to_inference_data 4 | from .inference_data import InferenceData 5 | 6 | 7 | def from_zarr(store): 8 | return InferenceData.from_zarr(store) 9 | 10 | 11 | from_zarr.__doc__ = InferenceData.from_zarr.__doc__ 12 | 13 | 14 | def to_zarr(data, store=None, **kwargs): 15 | """ 16 | Convert data to zarr, optionally saving to disk if ``store`` is provided. 17 | 18 | The zarr storage is using the same group names as the InferenceData. 19 | 20 | Parameters 21 | ---------- 22 | store : zarr.storage, MutableMapping or str, optional 23 | Zarr storage class or path to desired DirectoryStore. 24 | Default (None) a store is created in a temporary directory. 25 | **kwargs : dict, optional 26 | Passed to :py:func:`convert_to_inference_data`. 27 | 28 | Returns 29 | ------- 30 | zarr.hierarchy.group 31 | A zarr hierarchy group containing the InferenceData. 32 | 33 | Raises 34 | ------ 35 | TypeError 36 | If no valid store is found. 37 | 38 | 39 | References 40 | ---------- 41 | https://zarr.readthedocs.io/ 42 | 43 | """ 44 | inference_data = convert_to_inference_data(data, **kwargs) 45 | zarr_group = inference_data.to_zarr(store=store) 46 | return zarr_group 47 | -------------------------------------------------------------------------------- /arviz/plots/styles/arviz-grayscale.mplstyle: -------------------------------------------------------------------------------- 1 | # This style is based on Seaborn-white parameters, the main differences are 2 | # Default matplotlib font (no problem using Greek letters!) 3 | # Larger font size for several elements 4 | # Colorblind friendly color cycle 5 | figure.figsize: 7.2, 4.8 6 | figure.dpi: 100.0 7 | figure.facecolor: white 8 | figure.constrained_layout.use: True 9 | text.color: .15 10 | axes.labelcolor: .15 11 | legend.frameon: False 12 | legend.numpoints: 1 13 | legend.scatterpoints: 1 14 | xtick.direction: out 15 | ytick.direction: out 16 | xtick.color: .15 17 | ytick.color: .15 18 | axes.axisbelow: True 19 | lines.solid_capstyle: round 20 | 21 | axes.labelsize: 15 22 | axes.titlesize: 16 23 | xtick.labelsize: 14 24 | ytick.labelsize: 14 25 | legend.fontsize: 14 26 | 27 | axes.grid: False 28 | axes.facecolor: white 29 | axes.edgecolor: 0 30 | axes.linewidth: 1 31 | axes.spines.top: False 32 | axes.spines.right: False 33 | image.cmap: cet_gray # perceptually uniform gray scale from colorcet (linear_grey_10_95_c0) 34 | xtick.major.size: 0 35 | ytick.major.size: 0 36 | xtick.minor.size: 0 37 | ytick.minor.size: 0 38 | 39 | # First 4 colors are from colorcet and the last one is the "ArviZ-blue" 40 | # [to_hex(_linear_grey_0_100_c0[i]) for i in np.linspace(0, 195, 4).astype(int)] 41 | axes.prop_cycle: cycler('color', ["000000", "4a4a4a", "7e7f7f", "b8b8b8", "2a2eec"]) 42 | -------------------------------------------------------------------------------- /arviz/static/html/icons-svg-inline.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /doc/source/contributing/translate.md: -------------------------------------------------------------------------------- 1 | (translate)= 2 | # Translate ArviZ website and documentation 3 | You can contribute to ArviZ by helping with translations of our website and 4 | documentation. 5 | 6 | :::{important} 7 | Collaboration on translations happens on [Transifex](https://www.transifex.com/arviz/public/). 8 | That means that to contribute to ArviZ translations: 9 | 10 | * NO coding experience is required 11 | * NO GitHub account is needed 12 | ::: 13 | 14 | To help with translations you will need to go to [Transifex](https://www.transifex.com/arviz/public/) 15 | and sign up. After that you will be able to translate strings. 16 | 17 | We will regularly review the suggested translations and update the website. 18 | Thus, you should not expect the website to be updated automatically 19 | after you provide a translation on Transifex. 20 | 21 | ## Currently active translations 22 | * Project website [www.arviz.org](https://www.arviz.org/en/latest/) 23 | - [Catalan translation](https://www.arviz.org/ca/latest/) 24 | - [Spanish translation](https://www.arviz.org/es/latest/) 25 | - _more translations coming?_ 26 | * Python documentation: _coming soon_ 27 | 28 | ## Manage translations 29 | If you would like to be involved further with the translation process, 30 | adding new languages, reviewing translations suggested by other people... 31 | reach out on [Gitter](https://gitter.im/arviz-devs/community). 32 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to ArviZ 2 | This document outlines only the most common contributions. 3 | Please see the [Contributing guide](https://python.arviz.org/en/latest/contributing/index.html) 4 | on our documentation for a better view of how can you contribute to ArviZ. 5 | We welcome a wide range of contributions, not only code! 6 | 7 | ## Reporting issues 8 | If you encounter any bug or incorrect behaviour while using ArviZ, 9 | please report an issue to our [issue tracker](https://github.com/arviz-devs/arviz/issues). 10 | Please include any supporting information, in particular the version of 11 | ArviZ that you are using. 12 | The issue tracker has several templates available to help in writing the issue 13 | and including useful supporting information. 14 | 15 | ## Contributing code 16 | Thanks for your interest in contributing code to ArviZ! 17 | 18 | * If this is your first time contributing to a project on GitHub, please read through our [step by step](https://python.arviz.org/en/latest/contributing/pr_tutorial.html) guide to contributing to ArviZ 19 | * If you have contributed to other projects on GitHub you can go straight to our [pull request checklist](https://python.arviz.org/en/latest/contributing/pr_checklist.html) 20 | 21 | ### Adding new features 22 | If you are interested in adding a new feature to ArviZ, 23 | first submit an issue using the "Feature Request" label for the community 24 | to discuss its place and implementation within ArviZ. 25 | -------------------------------------------------------------------------------- /arviz/tests/conftest.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=redefined-outer-name 2 | """Configuration for test suite.""" 3 | import logging 4 | import os 5 | 6 | import numpy as np 7 | import pytest 8 | 9 | _log = logging.getLogger(__name__) 10 | 11 | 12 | @pytest.fixture(autouse=True) 13 | def random_seed(): 14 | """Reset numpy random seed generator.""" 15 | np.random.seed(0) 16 | 17 | 18 | def pytest_addoption(parser): 19 | """Definition for command line option to save figures from tests.""" 20 | parser.addoption("--save", nargs="?", const="test_images", help="Save images rendered by plot") 21 | 22 | 23 | @pytest.fixture(scope="session") 24 | def save_figs(request): 25 | """Enable command line switch for saving generation figures upon testing.""" 26 | fig_dir = request.config.getoption("--save") 27 | 28 | if fig_dir is not None: 29 | # Try creating directory if it doesn't exist 30 | _log.info("Saving generated images in %s", fig_dir) 31 | 32 | os.makedirs(fig_dir, exist_ok=True) 33 | _log.info("Directory %s created", fig_dir) 34 | 35 | # Clear all files from the directory 36 | # Does not alter or delete directories 37 | for file in os.listdir(fig_dir): 38 | full_path = os.path.join(fig_dir, file) 39 | 40 | try: 41 | os.remove(full_path) 42 | 43 | except OSError: 44 | _log.info("Failed to remove %s", full_path) 45 | 46 | return fig_dir 47 | -------------------------------------------------------------------------------- /doc/source/contributing/plotting_backends.md: -------------------------------------------------------------------------------- 1 | # Plotting backends 2 | ArviZ supports multiple backends. While adding another backend, please ensure you meet the 3 | following design patterns. 4 | 5 | ## Code Separation 6 | Each backend should be placed in a different module per the backend. 7 | See `arviz.plots.backends` for examples. 8 | 9 | The code in the root level of `arviz.plots` should not contain 10 | any opinion on backend. The idea is that the root level plotting 11 | function performs math and constructs keywords, and the backends 12 | code in `arviz.plots.backends` perform the backend specific 13 | keyword argument defaulting and plot behavior. 14 | 15 | The convenience function `get_plotting_function` available in 16 | `arviz.plots.plot_utils.get_plotting_function` should be called to obtain 17 | the correct plotting function from the associated backend. If 18 | adding a new backend follow the pattern provided to programmatically 19 | call the correct backend. 20 | 21 | ## Test Separation 22 | Tests for each backend should be split into their own module 23 | See [tests.test_plots_matplotlib](https://github.com/arviz-devs/arviz/blob/main/arviz/tests/base_tests/test_plots_matplotlib.py) for an example. 24 | 25 | ## Gallery Examples 26 | Gallery examples are not required but encouraged. Examples are 27 | compiled into the ArviZ documentation website. The [examples](https://github.com/arviz-devs/arviz/tree/main/examples) directory 28 | can be found in the root of the ArviZ git repository. 29 | -------------------------------------------------------------------------------- /arviz/data/io_json.py: -------------------------------------------------------------------------------- 1 | """Input and output support for data.""" 2 | 3 | from .io_dict import from_dict 4 | 5 | try: 6 | import ujson as json 7 | except ImportError: 8 | # Can't find ujson using json 9 | # mypy struggles with conditional imports expressed as catching ImportError: 10 | # https://github.com/python/mypy/issues/1153 11 | import json # type: ignore 12 | 13 | 14 | def from_json(filename): 15 | """Initialize object from a json file. 16 | 17 | Will use the faster `ujson` (https://github.com/ultrajson/ultrajson) if it is available. 18 | 19 | Parameters 20 | ---------- 21 | filename : str 22 | location of json file 23 | 24 | Returns 25 | ------- 26 | InferenceData object 27 | """ 28 | with open(filename, "rb") as file: 29 | idata_dict = json.load(file) 30 | 31 | return from_dict(**idata_dict, save_warmup=True) 32 | 33 | 34 | def to_json(idata, filename): 35 | """Save dataset as a json file. 36 | 37 | Will use the faster `ujson` (https://github.com/ultrajson/ultrajson) if it is available. 38 | 39 | WARNING: Only idempotent in case `idata` is InferenceData. 40 | 41 | Parameters 42 | ---------- 43 | idata : InferenceData 44 | Object to be saved 45 | filename : str 46 | name or path of the file to load trace 47 | 48 | Returns 49 | ------- 50 | str 51 | filename saved to 52 | """ 53 | file_name = idata.to_json(filename) 54 | return file_name 55 | -------------------------------------------------------------------------------- /doc/source/_static/key_feature_comparison.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /doc/source/user_guide/wrappers/linreg_model.stan: -------------------------------------------------------------------------------- 1 | data { 2 | int N; 3 | vector[N] time_since_joined; 4 | vector[N] slack_comments; 5 | vector[N] github_commits; 6 | } 7 | 8 | parameters { 9 | real b0; 10 | real b1; 11 | real log_b_sigma; 12 | 13 | real c0; 14 | real c1; 15 | real log_c_sigma; 16 | } 17 | 18 | transformed parameters { 19 | real b_sigma = exp(log_b_sigma); 20 | real c_sigma = exp(log_c_sigma); 21 | } 22 | 23 | model { 24 | b0 ~ normal(0,200); 25 | b1 ~ normal(0,200); 26 | b_sigma ~ normal(0,300); 27 | slack_comments ~ normal(b0 + b1 * time_since_joined, b_sigma); 28 | github_commits ~ normal(c0 + c1 * time_since_joined, c_sigma); 29 | 30 | } 31 | 32 | generated quantities { 33 | // elementwise log likelihood 34 | vector[N] log_likelihood_slack_comments; 35 | vector[N] log_likelihood_github_commits; 36 | 37 | // posterior predictive 38 | vector[N] slack_comments_hat; 39 | vector[N] github_commits_hat; 40 | 41 | //log likelihood & posterior predictive 42 | for (n in 1:N) { 43 | log_likelihood_slack_comments[n] = normal_lpdf(slack_comments[n] | b0 + b1 * time_since_joined[n], b_sigma); 44 | slack_comments_hat[n] = normal_rng(b0 + b1 * time_since_joined[n], b_sigma); 45 | 46 | log_likelihood_github_commits[n] = normal_lpdf(github_commits[n] | c0 + c1 * time_since_joined[n], c_sigma); 47 | github_commits_hat[n] = normal_rng(c0 + c1 * time_since_joined[n], c_sigma); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /examples/matplotlib/mpl_styles.py: -------------------------------------------------------------------------------- 1 | """ 2 | Matplotlib styles 3 | ================= 4 | _gallery_category: Styles 5 | _alt_text: Use Matplotlib Styles with `arviz.style.use()`. 6 | """ 7 | 8 | import matplotlib.pyplot as plt 9 | import numpy as np 10 | from scipy import stats 11 | 12 | import arviz as az 13 | 14 | x = np.linspace(0, 1, 100) 15 | dist = stats.beta(2, 5).pdf(x) 16 | 17 | style_list = [ 18 | "default", 19 | ["default", "arviz-colors"], 20 | "arviz-darkgrid", 21 | "arviz-whitegrid", 22 | "arviz-white", 23 | "arviz-grayscale", 24 | ["arviz-white", "arviz-redish"], 25 | ["arviz-white", "arviz-bluish"], 26 | ["arviz-white", "arviz-orangish"], 27 | ["arviz-white", "arviz-brownish"], 28 | ["arviz-white", "arviz-purplish"], 29 | ["arviz-white", "arviz-cyanish"], 30 | ["arviz-white", "arviz-greenish"], 31 | ["arviz-white", "arviz-royish"], 32 | ["arviz-white", "arviz-viridish"], 33 | ["arviz-white", "arviz-plasmish"], 34 | "arviz-doc", 35 | "arviz-docgrid", 36 | ] 37 | 38 | fig = plt.figure(figsize=(20, 10), layout="constrained") 39 | for idx, style in enumerate(style_list): 40 | with az.style.context(style, after_reset=True): 41 | ax = fig.add_subplot(5, 4, idx + 1, label=idx) 42 | colors = plt.rcParams["axes.prop_cycle"].by_key()["color"] 43 | for i in range(len(colors)): 44 | ax.plot(x, dist - i, f"C{i}", label=f"C{i}") 45 | ax.set_title(style) 46 | ax.set_ylabel("f(x)", rotation=0, labelpad=15) 47 | ax.set_xticklabels([]) 48 | 49 | plt.show() 50 | -------------------------------------------------------------------------------- /doc/source/contributing/how_to_add_to_example_gallery.md: -------------------------------------------------------------------------------- 1 | # How to add to the Example Gallery 2 | 3 | `Matplotlib` file is required for the chart to appear in the {ref}`example_gallery`. `Bokeh` uses the same metadata as long as the Plot Title and `{plot_name}` are the same. 4 | 5 | **Use the templates below to create new charts.** 6 | 7 | | {Metadata} | Description | 8 | | --- | --- | 9 | | Plot Title | Title of the chart shown in example gallery and table of contents | 10 | | Gallery Category | Single Category in example gallery and table of contents, defaults to Miscellaneous| 11 | | Alt Text | Text for overlay and alternative text for img thumbnail | 12 | 13 | **Gallery Categories** 14 | ``` 15 | [ 16 | "Mixed Plots", 17 | "Distributions", 18 | "Distribution Comparison", 19 | "Inference Diagnostics", 20 | "Regression or Time Series", 21 | "Model Comparison", 22 | "Model Checking", 23 | "Miscellaneous", 24 | "Styles", 25 | ] 26 | ``` 27 | 28 | ## Matplotlib Template (Required) 29 | 30 | Create `mpl_plot_{plot_name}.py` under `matplotlib/`. 31 | 32 | ``` 33 | """ 34 | {Plot Title} 35 | ========= 36 | _gallery_category: {Gallery Category} 37 | _alt_text: {Alt Text} 38 | """ 39 | {Additional imports here} 40 | 41 | import arviz as az 42 | 43 | az.style.use("arviz-doc") 44 | 45 | {Additional code here} 46 | ``` 47 | 48 | ## Bokeh Template 49 | 50 | Create `bokeh_plot_{plot_name}.py` under `matplotlib/`. 51 | 52 | ``` 53 | """ 54 | {Plot Title, must match the one in Matplotlib} 55 | ========= 56 | """ 57 | {Additional imports here} 58 | 59 | import arviz as az 60 | 61 | az.style.use("arviz-doc") 62 | 63 | {Additional code here} 64 | ``` -------------------------------------------------------------------------------- /doc/source/external_resources.md: -------------------------------------------------------------------------------- 1 | :::::{grid} 1 2 3 3 2 | 3 | ::::{grid-item-card} 4 | :img-top: https://raw.githubusercontent.com/pymc-devs/pymc/main/docs/logos/svg/PyMC_square.svg 5 | :link: https://github.com/pymc-devs/pymc-examples 6 | 7 | **PyMC example notebooks** 8 | 9 | Curated selection of PyMC guides and case studies. 10 | +++ 11 | Examples authored by PyMC developers and expert users. 12 | :::: 13 | 14 | 15 | ::::{grid-item-card} 16 | :img-top: https://raw.githubusercontent.com/stan-dev/logos/master/logo.png 17 | :link: https://mc-stan.org/users/documentation/case-studies 18 | 19 | **Stan case studies** 20 | 21 | The case studies on this page are intended to reflect best practices in Bayesian methodology and Stan programming. 22 | +++ 23 | Examples authored by Stan developers and expert users. 24 | :::: 25 | 26 | ::::{grid-item-card} 27 | :img-top: _static/images/bambi.png 28 | :link: https://github.com/bambinos/Bambi_resources 29 | 30 | **Bambi educational resources** 31 | 32 | Bambi is a high-level Bayesian model-building interface written in Python, 33 | designed to make it extremely easy to fit mixed-effects models. 34 | +++ 35 | Tutorials and book translations maintained by the Bambi team 36 | :::: 37 | 38 | ::::{grid-item-card} 39 | :img-top: https://oriolabril.github.io/oriol_unraveled/images/nb/labeled_arys.png 40 | :link: https://oriolabril.github.io/oriol_unraveled/categories/#arviz 41 | 42 | **Oriol unraveled** 43 | 44 | Blog mostly on statistics, diversity and open source. I also use the blog as a playground 45 | to test new pages for ArviZ docs. 46 | +++ 47 | Oriol Abril Pla is an ArviZ core contributor pursuing his PhD 48 | at Helsinki University 49 | :::: 50 | ::::: 51 | 52 | -------------------------------------------------------------------------------- /arviz/plots/backends/matplotlib/parallelplot.py: -------------------------------------------------------------------------------- 1 | """Matplotlib Parallel coordinates plot.""" 2 | 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | 6 | from ...plot_utils import _scale_fig_size 7 | from . import backend_kwarg_defaults, backend_show, create_axes_grid 8 | 9 | 10 | def plot_parallel( 11 | ax, 12 | colornd, 13 | colord, 14 | shadend, 15 | diverging_mask, 16 | posterior, 17 | textsize, 18 | var_names, 19 | legend, 20 | figsize, 21 | backend_kwargs, 22 | backend_config, # pylint: disable=unused-argument 23 | show, 24 | ): 25 | """Matplotlib parallel plot.""" 26 | if backend_kwargs is None: 27 | backend_kwargs = {} 28 | 29 | backend_kwargs = { 30 | **backend_kwarg_defaults(), 31 | **backend_kwargs, 32 | } 33 | 34 | figsize, _, _, xt_labelsize, _, _ = _scale_fig_size(figsize, textsize, 1, 1) 35 | backend_kwargs.setdefault("figsize", figsize) 36 | backend_kwargs["squeeze"] = True 37 | if ax is None: 38 | _, ax = create_axes_grid(1, backend_kwargs=backend_kwargs) 39 | 40 | ax.plot(posterior[:, ~diverging_mask], color=colornd, alpha=shadend) 41 | 42 | if np.any(diverging_mask): 43 | ax.plot(posterior[:, diverging_mask], color=colord, lw=1) 44 | 45 | ax.tick_params(labelsize=textsize) 46 | ax.set_xticks(range(len(var_names))) 47 | ax.set_xticklabels(var_names) 48 | 49 | if legend: 50 | ax.plot([], color=colornd, label="non-divergent") 51 | if np.any(diverging_mask): 52 | ax.plot([], color=colord, label="divergent") 53 | ax.legend(fontsize=xt_labelsize) 54 | 55 | if backend_show(show): 56 | plt.show() 57 | 58 | return ax 59 | -------------------------------------------------------------------------------- /doc/source/_static/key_feature_collaboration.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /arviz/plots/backends/matplotlib/hdiplot.py: -------------------------------------------------------------------------------- 1 | """Matplotlib hdiplot.""" 2 | 3 | import matplotlib.pyplot as plt 4 | from matplotlib import _pylab_helpers 5 | 6 | from ...plot_utils import _scale_fig_size, vectorized_to_hex 7 | from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser 8 | 9 | 10 | def plot_hdi(ax, x_data, y_data, color, figsize, plot_kwargs, fill_kwargs, backend_kwargs, show): 11 | """Matplotlib HDI plot.""" 12 | if backend_kwargs is None: 13 | backend_kwargs = {} 14 | 15 | backend_kwargs = { 16 | **backend_kwarg_defaults(), 17 | **backend_kwargs, 18 | } 19 | 20 | plot_kwargs = matplotlib_kwarg_dealiaser(plot_kwargs, "plot") 21 | plot_kwargs["color"] = vectorized_to_hex(plot_kwargs.get("color", color)) 22 | plot_kwargs.setdefault("alpha", 0) 23 | 24 | fill_kwargs = matplotlib_kwarg_dealiaser(fill_kwargs, "fill_between") 25 | fill_kwargs["color"] = vectorized_to_hex(fill_kwargs.get("color", color)) 26 | fill_kwargs.setdefault("alpha", 0.5) 27 | 28 | figsize, *_ = _scale_fig_size(figsize, None) 29 | backend_kwargs.setdefault("figsize", figsize) 30 | backend_kwargs["squeeze"] = True 31 | 32 | if ax is None: 33 | fig_manager = _pylab_helpers.Gcf.get_active() 34 | if fig_manager is not None: 35 | ax = fig_manager.canvas.figure.gca() 36 | else: 37 | _, ax = create_axes_grid( 38 | 1, 39 | backend_kwargs=backend_kwargs, 40 | ) 41 | 42 | ax.plot(x_data, y_data, **plot_kwargs) 43 | ax.fill_between(x_data, y_data[:, 0], y_data[:, 1], **fill_kwargs) 44 | 45 | if backend_show(show): 46 | plt.show() 47 | 48 | return ax 49 | -------------------------------------------------------------------------------- /doc/source/contributing/issue_reports.md: -------------------------------------------------------------------------------- 1 | (issue_reports)= 2 | # Issue reports 3 | 4 | We appreciate being notified of problems with the existing ArviZ code. 5 | We prefer that issues be filed on the 6 | [Github Issue Tracker](https://github.com/arviz-devs/arviz/issues), 7 | rather than on social media or by direct email to the developers. 8 | 9 | Please verify that your issue is not being currently addressed by other 10 | issues or pull requests by using the GitHub search tool to look for keywords 11 | in the project issue tracker. 12 | 13 | When writing an issue, make sure to include any supporting information, 14 | in particular, the version of ArviZ that you are using and how did you install it. 15 | The issue tracker has several templates available to help in writing the issue 16 | and including useful supporting information. 17 | 18 | ## Minimal reproducible example 19 | If your issue reports a bug or tries to show a specific behaviour, 20 | provide a way to reproduce the issue. Consider the advice on 21 | [stackoverflow](https://stackoverflow.com/help/minimal-reproducible-example) 22 | about writing a minimal reproducible code example. 23 | 24 | If even a minimal version of the code is still too long to comfortably share 25 | in the issue text, upload the code snippet as a 26 | [GitHub Gist](https://gist.github.com/) or a standalone Jupyter notebook. 27 | 28 | ## Sharing error tracebacks 29 | If relevant, also include the complete error messages and tracebacks. 30 | To avoid cluttering the issue body, you can optionally use the `details` 31 | html tag in GitHub to create a simple dropdown, like so: 32 | 33 | ```` 34 |
Click to see full traceback 35 | 36 | ``` 37 | long and barely comprehensible error traceback 38 | ``` 39 | 40 |
41 | ```` -------------------------------------------------------------------------------- /arviz/plots/__init__.py: -------------------------------------------------------------------------------- 1 | """Plotting functions.""" 2 | 3 | from .autocorrplot import plot_autocorr 4 | from .bpvplot import plot_bpv 5 | from .bfplot import plot_bf 6 | from .compareplot import plot_compare 7 | from .densityplot import plot_density 8 | from .distcomparisonplot import plot_dist_comparison 9 | from .distplot import plot_dist 10 | from .dotplot import plot_dot 11 | from .ecdfplot import plot_ecdf 12 | from .elpdplot import plot_elpd 13 | from .energyplot import plot_energy 14 | from .essplot import plot_ess 15 | from .forestplot import plot_forest 16 | from .hdiplot import plot_hdi 17 | from .kdeplot import plot_kde 18 | from .khatplot import plot_khat 19 | from .lmplot import plot_lm 20 | from .loopitplot import plot_loo_pit 21 | from .mcseplot import plot_mcse 22 | from .pairplot import plot_pair 23 | from .parallelplot import plot_parallel 24 | from .posteriorplot import plot_posterior 25 | from .ppcplot import plot_ppc 26 | from .rankplot import plot_rank 27 | from .separationplot import plot_separation 28 | from .traceplot import plot_trace 29 | from .tsplot import plot_ts 30 | from .violinplot import plot_violin 31 | 32 | __all__ = [ 33 | "plot_autocorr", 34 | "plot_bpv", 35 | "plot_bf", 36 | "plot_compare", 37 | "plot_density", 38 | "plot_dist", 39 | "plot_dot", 40 | "plot_ecdf", 41 | "plot_elpd", 42 | "plot_energy", 43 | "plot_ess", 44 | "plot_forest", 45 | "plot_hdi", 46 | "plot_kde", 47 | "plot_khat", 48 | "plot_lm", 49 | "plot_loo_pit", 50 | "plot_mcse", 51 | "plot_pair", 52 | "plot_parallel", 53 | "plot_posterior", 54 | "plot_ppc", 55 | "plot_dist_comparison", 56 | "plot_rank", 57 | "plot_trace", 58 | "plot_ts", 59 | "plot_violin", 60 | "plot_separation", 61 | ] 62 | -------------------------------------------------------------------------------- /arviz/plots/backends/bokeh/hdiplot.py: -------------------------------------------------------------------------------- 1 | """Bokeh hdiplot.""" 2 | 3 | import numpy as np 4 | 5 | from ...plot_utils import _scale_fig_size, vectorized_to_hex 6 | from .. import show_layout 7 | from . import backend_kwarg_defaults, create_axes_grid 8 | 9 | 10 | def plot_hdi(ax, x_data, y_data, color, figsize, plot_kwargs, fill_kwargs, backend_kwargs, show): 11 | """Bokeh HDI plot.""" 12 | if backend_kwargs is None: 13 | backend_kwargs = {} 14 | 15 | backend_kwargs = { 16 | **backend_kwarg_defaults(), 17 | **backend_kwargs, 18 | } 19 | 20 | plot_kwargs = {} if plot_kwargs is None else plot_kwargs 21 | plot_kwargs["color"] = vectorized_to_hex(plot_kwargs.get("color", color)) 22 | plot_kwargs.setdefault("alpha", 0) 23 | 24 | fill_kwargs = {} if fill_kwargs is None else fill_kwargs 25 | fill_kwargs["color"] = vectorized_to_hex(fill_kwargs.get("color", color)) 26 | fill_kwargs.setdefault("alpha", 0.5) 27 | 28 | figsize, *_ = _scale_fig_size(figsize, None) 29 | 30 | if ax is None: 31 | ax = create_axes_grid( 32 | 1, 33 | figsize=figsize, 34 | squeeze=True, 35 | backend_kwargs=backend_kwargs, 36 | ) 37 | 38 | plot_kwargs.setdefault("line_color", plot_kwargs.pop("color")) 39 | plot_kwargs.setdefault("line_alpha", plot_kwargs.pop("alpha", 0)) 40 | 41 | fill_kwargs.setdefault("fill_color", fill_kwargs.pop("color")) 42 | fill_kwargs.setdefault("fill_alpha", fill_kwargs.pop("alpha", 0)) 43 | 44 | ax.patch( 45 | np.concatenate((x_data, x_data[::-1])), 46 | np.concatenate((y_data[:, 0], y_data[:, 1][::-1])), 47 | **fill_kwargs, 48 | **plot_kwargs 49 | ) 50 | 51 | show_layout(ax, show) 52 | 53 | return ax 54 | -------------------------------------------------------------------------------- /arviz/tests/base_tests/test_stats_numba.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=redefined-outer-name, no-member 2 | import numpy as np 3 | import pytest 4 | 5 | from ...rcparams import rcParams 6 | from ...stats import r2_score, summary 7 | from ...utils import Numba 8 | from ..helpers import ( # pylint: disable=unused-import 9 | check_multiple_attrs, 10 | importorskip, 11 | multidim_models, 12 | ) 13 | from .test_stats import centered_eight, non_centered_eight # pylint: disable=unused-import 14 | 15 | numba = importorskip("numba") 16 | 17 | rcParams["data.load"] = "eager" 18 | 19 | 20 | @pytest.mark.parametrize("circ_var_names", [["mu"], None]) 21 | def test_summary_circ_vars(centered_eight, circ_var_names): 22 | assert summary(centered_eight, circ_var_names=circ_var_names) is not None 23 | state = Numba.numba_flag 24 | Numba.disable_numba() 25 | assert summary(centered_eight, circ_var_names=circ_var_names) is not NotImplementedError 26 | Numba.enable_numba() 27 | assert state == Numba.numba_flag 28 | 29 | 30 | def test_numba_stats(): 31 | """Numba test for r2_score""" 32 | state = Numba.numba_flag # Store the current state of Numba 33 | set_1 = np.random.randn(100, 100) 34 | set_2 = np.random.randn(100, 100) 35 | set_3 = np.random.rand(100) 36 | set_4 = np.random.rand(100) 37 | Numba.disable_numba() 38 | non_numba = r2_score(set_1, set_2) 39 | non_numba_one_dimensional = r2_score(set_3, set_4) 40 | Numba.enable_numba() 41 | with_numba = r2_score(set_1, set_2) 42 | with_numba_one_dimensional = r2_score(set_3, set_4) 43 | assert state == Numba.numba_flag # Ensure that initial state = final state 44 | assert np.allclose(non_numba, with_numba) 45 | assert np.allclose(non_numba_one_dimensional, with_numba_one_dimensional) 46 | -------------------------------------------------------------------------------- /arviz/data/__init__.py: -------------------------------------------------------------------------------- 1 | """Code for loading and manipulating data structures.""" 2 | 3 | from .base import CoordSpec, DimSpec, dict_to_dataset, numpy_to_data_array, pytree_to_dataset 4 | from .converters import convert_to_dataset, convert_to_inference_data 5 | from .datasets import clear_data_home, list_datasets, load_arviz_data 6 | from .inference_data import InferenceData, concat 7 | from .io_beanmachine import from_beanmachine 8 | from .io_cmdstan import from_cmdstan 9 | from .io_cmdstanpy import from_cmdstanpy 10 | from .io_datatree import from_datatree, to_datatree 11 | from .io_dict import from_dict, from_pytree 12 | from .io_emcee import from_emcee 13 | from .io_json import from_json, to_json 14 | from .io_netcdf import from_netcdf, to_netcdf 15 | from .io_numpyro import from_numpyro 16 | from .io_pyjags import from_pyjags 17 | from .io_pyro import from_pyro 18 | from .io_pystan import from_pystan 19 | from .io_zarr import from_zarr, to_zarr 20 | from .utils import extract, extract_dataset 21 | 22 | __all__ = [ 23 | "InferenceData", 24 | "concat", 25 | "load_arviz_data", 26 | "list_datasets", 27 | "clear_data_home", 28 | "numpy_to_data_array", 29 | "extract", 30 | "extract_dataset", 31 | "dict_to_dataset", 32 | "convert_to_dataset", 33 | "convert_to_inference_data", 34 | "from_beanmachine", 35 | "from_pyjags", 36 | "from_pystan", 37 | "from_emcee", 38 | "from_cmdstan", 39 | "from_cmdstanpy", 40 | "from_datatree", 41 | "from_dict", 42 | "from_pytree", 43 | "from_json", 44 | "from_pyro", 45 | "from_numpyro", 46 | "from_netcdf", 47 | "pytree_to_dataset", 48 | "to_datatree", 49 | "to_json", 50 | "to_netcdf", 51 | "from_zarr", 52 | "to_zarr", 53 | "CoordSpec", 54 | "DimSpec", 55 | ] 56 | -------------------------------------------------------------------------------- /arviz/data/example_data/code/rugby/rugby.csv: -------------------------------------------------------------------------------- 1 | home_team,away_team,home_score,away_score,i_home,i_away 2 | Wales,Italy,23,15,0,4 3 | France,England,26,24,1,5 4 | Ireland,Scotland,28,6,2,3 5 | Ireland,Wales,26,3,2,0 6 | Scotland,England,0,20,3,5 7 | France,Italy,30,10,1,4 8 | Wales,France,27,6,0,1 9 | Italy,Scotland,20,21,4,3 10 | England,Ireland,13,10,5,2 11 | Ireland,Italy,46,7,2,4 12 | Scotland,France,17,19,3,1 13 | England,Wales,29,18,5,0 14 | Italy,England,11,52,4,5 15 | Wales,Scotland,51,3,0,3 16 | France,Ireland,20,22,1,2 17 | Wales,England,16,21,0,5 18 | Italy,Ireland,3,26,4,2 19 | France,Scotland,15,8,1,3 20 | England,Italy,47,17,5,4 21 | Ireland,France,18,11,2,1 22 | Scotland,Wales,23,26,3,0 23 | Scotland,Italy,19,22,3,4 24 | France,Wales,13,20,1,0 25 | Ireland,England,19,9,2,5 26 | Wales,Ireland,23,16,0,2 27 | England,Scotland,25,13,5,3 28 | Italy,France,0,29,4,1 29 | Italy,Wales,20,61,4,0 30 | Scotland,Ireland,10,40,3,2 31 | England,France,55,35,5,1 32 | France,Italy,23,21,1,4 33 | Scotland,England,9,15,3,5 34 | Ireland,Wales,16,16,2,0 35 | France,Ireland,10,9,1,2 36 | Wales,Scotland,27,23,0,3 37 | Italy,England,9,40,4,5 38 | Wales,France,19,10,0,1 39 | Italy,Scotland,20,36,4,3 40 | England,Ireland,21,10,5,2 41 | Ireland,Italy,58,15,2,4 42 | England,Wales,25,21,5,0 43 | Scotland,France,29,18,3,1 44 | Wales,Italy,67,14,0,4 45 | Ireland,Scotland,35,25,2,3 46 | France,England,21,31,1,5 47 | Scotland,Ireland,27,22,3,2 48 | England,France,19,16,5,1 49 | Italy,Wales,7,33,4,0 50 | Italy,Ireland,10,63,4,2 51 | Wales,England,16,21,0,5 52 | France,Scotland,22,16,1,3 53 | Scotland,Wales,29,13,3,0 54 | Ireland,France,19,9,2,1 55 | England,Italy,36,15,5,4 56 | Wales,Ireland,22,9,0,2 57 | Italy,France,18,40,4,1 58 | England,Scotland,61,21,5,3 59 | Scotland,Italy,29,0,3,4 60 | France,Wales,20,18,1,0 61 | Ireland,England,13,9,2,5 62 | -------------------------------------------------------------------------------- /.azure-pipelines/azure-pipelines-benchmarks.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | - job: Benchmarks 3 | pool: 4 | vmImage: 'ubuntu-latest' 5 | timeoutInMinutes: 360 6 | strategy: 7 | matrix: 8 | Python_311: 9 | python.version: "3.11" 10 | name: "Python 3.11 - benchmarks" 11 | 12 | steps: 13 | 14 | - task: UsePythonVersion@0 15 | inputs: 16 | versionSpec: '$(python.version)' 17 | displayName: 'Use Python $(python.version)' 18 | 19 | - script: | 20 | ls -ahl 21 | env 22 | pwd 23 | gcc --version 24 | python --version 25 | displayName: 'Debug information' 26 | 27 | - script: | 28 | python -m pip install --upgrade pip 29 | python -m pip install wheel build 30 | python -m pip install --no-cache-dir -r requirements.txt 31 | python -m pip install --no-cache-dir -r requirements-optional.txt 32 | python -m pip install asv 33 | displayName: 'Install requirements' 34 | 35 | - script: | 36 | python -m pip freeze 37 | displayName: 'Debug information 2' 38 | 39 | - script: | 40 | python -m asv machine --yes 41 | git log --pretty=format:'%h' -n 1 > hashestobenchmark.txt 42 | cat hashestobenchmark.txt 43 | python -m asv run HASHFILE:hashestobenchmark.txt 44 | displayName: 'Run the benchmarks' 45 | workingDirectory: asv_benchmarks/ 46 | 47 | - script: | 48 | git log --pretty=format:'%h' -n 1 | xargs python -m asv show 49 | git log --pretty=format:'%h' -n 1 | xargs python -m asv show > ../benchmark_results.txt 50 | displayName: 'Print and save results' 51 | workingDirectory: asv_benchmarks/ 52 | 53 | - task: PublishBuildArtifacts@1 54 | inputs: 55 | pathtoPublish: 'benchmark_results.txt' 56 | artifactName: 'Benchmarks' 57 | displayName: 'Publish the benchmarks' 58 | -------------------------------------------------------------------------------- /arviz/data/example_data/code/radon/radon.py: -------------------------------------------------------------------------------- 1 | import arviz as az 2 | import pymc3 as pm 3 | import numpy as np 4 | import ujson as json 5 | 6 | with open("radon.json", "rb") as f: 7 | radon_data = json.load(f) 8 | 9 | radon_data = { 10 | key: np.array(value) if isinstance(value, list) else value 11 | for key, value in radon_data.items() 12 | } 13 | 14 | coords = { 15 | "Level": ["Basement", "Floor"], 16 | "obs_id": np.arange(radon_data["y"].size), 17 | "County": radon_data["county_name"], 18 | "g_coef": ["intercept", "slope"], 19 | } 20 | 21 | with pm.Model(coords=coords): 22 | floor_idx = pm.Data("floor_idx", radon_data["x"], dims="obs_id") 23 | county_idx = pm.Data("county_idx", radon_data["county"], dims="obs_id") 24 | uranium = pm.Data("uranium", radon_data["u"], dims="County") 25 | 26 | # Hyperpriors: 27 | g = pm.Normal("g", mu=0.0, sigma=10.0, dims="g_coef") 28 | sigma_a = pm.Exponential("sigma_a", 1.0) 29 | 30 | # Varying intercepts uranium model: 31 | a = pm.Deterministic("a", g[0] + g[1] * uranium, dims="County") 32 | za_county = pm.Normal("za_county", mu=0.0, sigma=1.0, dims="County") 33 | a_county = pm.Deterministic("a_county", a + za_county * sigma_a, dims="County") 34 | # Common slope: 35 | b = pm.Normal("b", mu=0.0, sigma=1.0) 36 | 37 | # Expected value per county: 38 | theta = a_county[county_idx] + b * floor_idx 39 | # Model error: 40 | sigma = pm.Exponential("sigma", 1.0) 41 | 42 | y = pm.Normal("y", theta, sigma=sigma, observed=radon_data["y"], dims="obs_id") 43 | 44 | prior = pm.sample_prior_predictive(500) 45 | trace = pm.sample( 46 | 1000, tune=500, target_accept=0.99, random_seed=117 47 | ) 48 | post_pred = pm.sample_posterior_predictive(trace) 49 | idata = az.from_pymc3(trace, prior=prior, posterior_predictive=post_pred) 50 | -------------------------------------------------------------------------------- /.azure-pipelines/azure-pipelines-wheel.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | - job: BuildWheel 3 | dependsOn: 4 | - BaseTests 5 | - ExternalTests 6 | condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/tags/')) 7 | pool: 8 | vmImage: 'ubuntu-latest' 9 | variables: 10 | - name: NUMBA_DISABLE_JIT 11 | value: 1 12 | timeoutInMinutes: 360 13 | strategy: 14 | matrix: 15 | Python_311: 16 | python.version: "3.11" 17 | name: "Python 3.11 - wheel" 18 | 19 | steps: 20 | 21 | - task: UsePythonVersion@0 22 | inputs: 23 | versionSpec: '$(python.version)' 24 | displayName: 'Use Python $(python.version)' 25 | 26 | - script: | 27 | ls -ahl 28 | env 29 | pwd 30 | gcc --version 31 | python --version 32 | displayName: 'Debug information' 33 | 34 | - script: | 35 | python -m pip install --upgrade pip 36 | python -m pip install wheel 37 | python -m pip install --no-cache-dir -r requirements.txt 38 | python -m pip install twine 39 | displayName: 'Install requirements' 40 | 41 | - script: | 42 | python setup.py sdist bdist_wheel 43 | ls -lh dist 44 | displayName: 'Build a wheel' 45 | 46 | - script: | 47 | mkdir install_test 48 | cd install_test 49 | ls -lh ../dist 50 | python -m pip install ../dist/*.whl 51 | python -c "import arviz as az; print(az);print(az.summary(az.load_arviz_data('non_centered_eight')))" 52 | cd .. 53 | displayName: 'Install and test the wheel' 54 | 55 | - script: | 56 | ls -ahl 57 | env 58 | displayName: 'Debug information 2' 59 | 60 | - task: PublishBuildArtifacts@1 61 | inputs: 62 | pathtoPublish: 'dist' 63 | artifactName: 'arviz_wheel_dist' 64 | displayName: 'Publish the wheel' 65 | 66 | - script: | 67 | python -m twine upload -u __token__ -p $(PYPI_PASSWORD) --skip-existing dist/* 68 | displayName: 'Upload wheel to PyPI' 69 | -------------------------------------------------------------------------------- /arviz/tests/base_tests/test_labels.py: -------------------------------------------------------------------------------- 1 | """Tests for labeller classes.""" 2 | 3 | import pytest 4 | 5 | from ...labels import ( 6 | BaseLabeller, 7 | DimCoordLabeller, 8 | DimIdxLabeller, 9 | IdxLabeller, 10 | MapLabeller, 11 | NoModelLabeller, 12 | NoVarLabeller, 13 | ) 14 | 15 | 16 | class Data: 17 | def __init__(self): 18 | self.sel = { 19 | "instrument": "a", 20 | "experiment": 3, 21 | } 22 | self.isel = { 23 | "instrument": 0, 24 | "experiment": 4, 25 | } 26 | 27 | 28 | @pytest.fixture 29 | def multidim_sels(): 30 | return Data() 31 | 32 | 33 | class Labellers: 34 | def __init__(self): 35 | self.labellers = { 36 | "BaseLabeller": BaseLabeller(), 37 | "DimCoordLabeller": DimCoordLabeller(), 38 | "IdxLabeller": IdxLabeller(), 39 | "DimIdxLabeller": DimIdxLabeller(), 40 | "MapLabeller": MapLabeller(), 41 | "NoVarLabeller": NoVarLabeller(), 42 | "NoModelLabeller": NoModelLabeller(), 43 | } 44 | 45 | 46 | @pytest.fixture 47 | def labellers(): 48 | return Labellers() 49 | 50 | 51 | @pytest.mark.parametrize( 52 | "args", 53 | [ 54 | ("BaseLabeller", "theta\na, 3"), 55 | ("DimCoordLabeller", "theta\ninstrument: a, experiment: 3"), 56 | ("IdxLabeller", "theta\n0, 4"), 57 | ("DimIdxLabeller", "theta\ninstrument#0, experiment#4"), 58 | ("MapLabeller", "theta\na, 3"), 59 | ("NoVarLabeller", "a, 3"), 60 | ("NoModelLabeller", "theta\na, 3"), 61 | ], 62 | ) 63 | class TestLabellers: 64 | # pylint: disable=redefined-outer-name 65 | def test_make_label_vert(self, args, multidim_sels, labellers): 66 | name, expected_label = args 67 | labeller_arg = labellers.labellers[name] 68 | label = labeller_arg.make_label_vert("theta", multidim_sels.sel, multidim_sels.isel) 69 | assert label == expected_label 70 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # ArviZ Community Code of Conduct 2 | 3 | ArviZ adopts the NumFOCUS Code of Conduct directly. In other words, we 4 | expect our community to treat others with kindness and understanding. 5 | 6 | 7 | # THE SHORT VERSION 8 | Be kind to others. Do not insult or put down others. 9 | Behave professionally. Remember that harassment and sexist, racist, 10 | or exclusionary jokes are not appropriate. 11 | 12 | All communication should be appropriate for a professional audience 13 | including people of many different backgrounds. Sexual language and 14 | imagery are not appropriate. 15 | 16 | ArviZ is dedicated to providing a harassment-free community for everyone, 17 | regardless of gender, sexual orientation, gender identity, and 18 | expression, disability, physical appearance, body size, race, 19 | or religion. We do not tolerate harassment of community members 20 | in any form. 21 | 22 | Thank you for helping make this a welcoming, friendly community for all. 23 | 24 | 25 | # How to Submit a Report 26 | If you feel that there has been a Code of Conduct violation an anonymous 27 | reporting form is available. 28 | **If you feel your safety is in jeopardy or the situation is an 29 | emergency, we urge you to contact local law enforcement before making 30 | a report. (In the U.S., dial 911.)** 31 | 32 | We are committed to promptly addressing any reported issues. 33 | If you have experienced or witnessed behavior that violates this 34 | Code of Conduct, please complete the form below to 35 | make a report. 36 | 37 | **REPORTING FORM:** https://numfocus.typeform.com/to/ynjGdT 38 | 39 | Reports are sent to the NumFOCUS Code of Conduct Enforcement Team 40 | (see below). 41 | 42 | You can view the Privacy Policy and Terms of Service for TypeForm here. 43 | The NumFOCUS Privacy Policy is here: 44 | https://www.numfocus.org/privacy-policy 45 | 46 | 47 | # Full Code of Conduct 48 | The full text of the NumFOCUS/ArviZ Code of Conduct can be found on 49 | NumFOCUS's website 50 | https://numfocus.org/code-of-conduct 51 | -------------------------------------------------------------------------------- /arviz/plots/backends/bokeh/ecdfplot.py: -------------------------------------------------------------------------------- 1 | """Bokeh ecdfplot.""" 2 | 3 | from matplotlib.colors import to_hex 4 | 5 | from ...plot_utils import _scale_fig_size 6 | from .. import show_layout 7 | from . import backend_kwarg_defaults, create_axes_grid 8 | 9 | 10 | def plot_ecdf( 11 | x_coord, 12 | y_coord, 13 | x_bands, 14 | lower, 15 | higher, 16 | plot_kwargs, 17 | fill_kwargs, 18 | plot_outline_kwargs, 19 | figsize, 20 | fill_band, 21 | ax, 22 | show, 23 | backend_kwargs, 24 | ): 25 | """Bokeh ecdfplot.""" 26 | if backend_kwargs is None: 27 | backend_kwargs = {} 28 | 29 | backend_kwargs = { 30 | **backend_kwarg_defaults(), 31 | **backend_kwargs, 32 | } 33 | 34 | (figsize, *_) = _scale_fig_size(figsize, None) 35 | 36 | if ax is None: 37 | ax = create_axes_grid( 38 | 1, 39 | figsize=figsize, 40 | squeeze=True, 41 | backend_kwargs=backend_kwargs, 42 | ) 43 | 44 | if plot_kwargs is None: 45 | plot_kwargs = {} 46 | 47 | plot_kwargs.setdefault("mode", "after") 48 | 49 | if fill_band: 50 | if fill_kwargs is None: 51 | fill_kwargs = {} 52 | fill_kwargs.setdefault("fill_color", to_hex("C0")) 53 | fill_kwargs.setdefault("fill_alpha", 0.2) 54 | else: 55 | if plot_outline_kwargs is None: 56 | plot_outline_kwargs = {} 57 | plot_outline_kwargs.setdefault("color", to_hex("C0")) 58 | plot_outline_kwargs.setdefault("alpha", 0.2) 59 | 60 | if x_bands is not None: 61 | ax.step(x_coord, y_coord, **plot_kwargs) 62 | 63 | if fill_band: 64 | ax.varea(x_bands, lower, higher, **fill_kwargs) 65 | else: 66 | ax.line(x_bands, lower, **plot_outline_kwargs) 67 | ax.line(x_bands, higher, **plot_outline_kwargs) 68 | else: 69 | ax.step(x_coord, y_coord, **plot_kwargs) 70 | 71 | show_layout(ax, show) 72 | 73 | return ax 74 | -------------------------------------------------------------------------------- /scripts/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM conda/miniconda3 2 | 3 | LABEL maintainer="Ravin Kumar" 4 | 5 | ARG SRC_DIR 6 | ARG PYTHON_VERSION 7 | ARG PYSTAN_VERSION 8 | ARG PYRO_VERSION 9 | ARG PYTORCH_VERSION 10 | ARG EMCEE_VERSION 11 | ARG TF_VERSION 12 | ARG PYMC3_VERSION 13 | 14 | ENV PYTHON_VERSION=${PYTHON_VERSION} 15 | ENV PYSTAN_VERSION=${PYSTAN_VERSION} 16 | ENV PYRO_VERSION=${PYRO_VERSION} 17 | ENV PYTORCH_VERSION=${PYTORCH_VERSION} 18 | ENV EMCEE_VERSION=${EMCEE_VERSION} 19 | ENV TF_VERSION=${TF_VERSION} 20 | ENV PYMC3_VERSION=${PYMC3_VERSION} 21 | 22 | # Change behavior of create_test.sh script 23 | ENV DOCKER_BUILD=true 24 | 25 | # For Sphinx documentation builds 26 | ENV LC_ALL=C.UTF-8 27 | ENV LANG=C.UTF-8 28 | 29 | # Update container 30 | RUN apt-get update && apt-get install -y git build-essential pandoc vim ffmpeg \ 31 | dos2unix libgtk-3-dev libdbus-glib-1-dev libxt-dev jags && rm -rf /var/lib/apt/lists/* 32 | 33 | # Copy needed scripts 34 | COPY $SRC_DIR/requirements*.txt /opt/arviz/ 35 | COPY $SRC_DIR/scripts /opt/arviz/scripts 36 | RUN find /opt/arviz/ -type f -print0 | xargs -0 dos2unix 37 | 38 | # Clear any cached models from copied from host filesystem 39 | RUN rm -f arviz/tests/saved_models/*.pkl 40 | RUN find -type d -name __pycache__ -exec rm -rf {} + 41 | 42 | # Change workdir 43 | WORKDIR /opt/arviz 44 | 45 | # Create conda environment. Defaults to Python 3.8 46 | RUN ./scripts/create_testenv.sh 47 | 48 | # Set automatic conda activation in non interactive and shells 49 | ENV BASH_ENV="/root/activate_conda.sh" 50 | RUN echo ". /root/activate_conda.sh" > /root/.bashrc 51 | 52 | # Remove conda cache 53 | RUN conda clean --all 54 | 55 | # Copy ArviZ 56 | COPY $SRC_DIR /opt/arviz 57 | RUN find /opt/arviz/ -type f -print0 | xargs -0 dos2unix 58 | 59 | # Clear any cached models from copied from host filesystem 60 | RUN rm -f arviz/tests/saved_models/*.pkl 61 | RUN find -type d -name __pycache__ -exec rm -rf {} + 62 | 63 | # Install editable using the setup.py 64 | RUN /bin/bash -c "source /root/.bashrc && python -m pip install -e ." 65 | -------------------------------------------------------------------------------- /arviz/plots/backends/matplotlib/ecdfplot.py: -------------------------------------------------------------------------------- 1 | """Matplotlib ecdfplot.""" 2 | 3 | import matplotlib.pyplot as plt 4 | from matplotlib.colors import to_hex 5 | 6 | from ...plot_utils import _scale_fig_size 7 | from . import backend_kwarg_defaults, create_axes_grid, backend_show 8 | 9 | 10 | def plot_ecdf( 11 | x_coord, 12 | y_coord, 13 | x_bands, 14 | lower, 15 | higher, 16 | plot_kwargs, 17 | fill_kwargs, 18 | plot_outline_kwargs, 19 | figsize, 20 | fill_band, 21 | ax, 22 | show, 23 | backend_kwargs, 24 | ): 25 | """Matplotlib ecdfplot.""" 26 | if backend_kwargs is None: 27 | backend_kwargs = {} 28 | 29 | backend_kwargs = { 30 | **backend_kwarg_defaults(), 31 | **backend_kwargs, 32 | } 33 | 34 | (figsize, _, _, _, _, _) = _scale_fig_size(figsize, None) 35 | backend_kwargs.setdefault("figsize", figsize) 36 | backend_kwargs["squeeze"] = True 37 | 38 | if ax is None: 39 | _, ax = create_axes_grid(1, backend_kwargs=backend_kwargs) 40 | 41 | if plot_kwargs is None: 42 | plot_kwargs = {} 43 | 44 | plot_kwargs.setdefault("where", "post") 45 | 46 | if fill_band: 47 | if fill_kwargs is None: 48 | fill_kwargs = {} 49 | fill_kwargs.setdefault("step", "post") 50 | fill_kwargs.setdefault("color", to_hex("C0")) 51 | fill_kwargs.setdefault("alpha", 0.2) 52 | else: 53 | if plot_outline_kwargs is None: 54 | plot_outline_kwargs = {} 55 | plot_outline_kwargs.setdefault("where", "post") 56 | plot_outline_kwargs.setdefault("color", to_hex("C0")) 57 | plot_outline_kwargs.setdefault("alpha", 0.2) 58 | 59 | ax.step(x_coord, y_coord, **plot_kwargs) 60 | 61 | if x_bands is not None: 62 | if fill_band: 63 | ax.fill_between(x_bands, lower, higher, **fill_kwargs) 64 | else: 65 | ax.plot(x_bands, lower, x_bands, higher, **plot_outline_kwargs) 66 | 67 | if backend_show(show): 68 | plt.show() 69 | 70 | return ax 71 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 14 | 15 | ## Checklist 16 | 17 | 18 | - [ ] Follows [official](https://github.com/arviz-devs/arviz/blob/main/CONTRIBUTING.md#pull-request-checklist) PR format 19 | - [ ] Includes a sample plot to visually illustrate the changes (only for plot-related functions) 20 | - [ ] New features are properly documented (with an example if appropriate)? 21 | - [ ] Includes new or updated tests to cover the new feature 22 | - [ ] Code style correct (follows pylint and black guidelines) 23 | - [ ] Changes are listed in [changelog](https://github.com/arviz-devs/arviz/blob/main/CHANGELOG.md#v0xx-unreleased) 24 | 25 | 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | arviz/tests/.pytest_cache/ 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | .asv/ 24 | .pytest_cache/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | .ipynb_checkpoints 29 | .virtual_documents 30 | 31 | # Environments 32 | .env 33 | .venv 34 | env/ 35 | venv/ 36 | ENV/ 37 | 38 | # PyInstaller 39 | # Usually these files are written by a python script from a template 40 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 41 | *.manifest 42 | *.spec 43 | 44 | # Installer logs 45 | pip-log.txt 46 | pip-delete-this-directory.txt 47 | 48 | # Unit test / coverage reports 49 | htmlcov/ 50 | .tox/ 51 | .coverage 52 | .coverage.* 53 | .cache 54 | nosetests.xml 55 | coverage.xml 56 | *,cover 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | 65 | # Sphinx documentation 66 | doc/build/ 67 | doc/source/savefig 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # IDE configs 73 | .idea/ 74 | .vscode/ 75 | .DS_Store 76 | saved_animations/ 77 | 78 | # mypy 79 | .mypy_cache 80 | 81 | # MacOS generated files 82 | .DS_Store 83 | 84 | # examples 85 | examples/**/*.html 86 | 87 | # Stan file 88 | doc/getting_started/*.stan 89 | doc/source/user_guide/wrappers/* 90 | !doc/source/user_guide/wrappers/*.stan 91 | !doc/source/user_guide/wrappers/*.ipynb 92 | !doc/source/user_guide/wrappers/*.md 93 | 94 | # eight-schools files 95 | doc/source/getting_started/schools* 96 | !doc/source/user_guide/wrappers/schools.stan 97 | !doc/source/user_guide/wrappers/schools.json 98 | doc/source/getting_started/eight_school* 99 | doc/source/getting_started/sample_data/ 100 | 101 | # MyST related 102 | doc/jupyter_execute 103 | 104 | # Dask related 105 | mydask.png 106 | **/dask-worker-space/* 107 | -------------------------------------------------------------------------------- /arviz/plots/backends/matplotlib/autocorrplot.py: -------------------------------------------------------------------------------- 1 | """Matplotlib Autocorrplot.""" 2 | 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | 6 | from ....stats import autocorr 7 | from ...plot_utils import _scale_fig_size 8 | from . import backend_kwarg_defaults, backend_show, create_axes_grid 9 | 10 | 11 | def plot_autocorr( 12 | axes, 13 | plotters, 14 | max_lag, 15 | figsize, 16 | rows, 17 | cols, 18 | combined, 19 | textsize, 20 | labeller, 21 | backend_kwargs, 22 | show, 23 | ): 24 | """Matplotlib autocorrplot.""" 25 | if backend_kwargs is None: 26 | backend_kwargs = {} 27 | 28 | backend_kwargs = { 29 | **backend_kwarg_defaults(), 30 | **backend_kwargs, 31 | } 32 | 33 | figsize, _, titlesize, xt_labelsize, linewidth, _ = _scale_fig_size( 34 | figsize, textsize, rows, cols 35 | ) 36 | 37 | backend_kwargs.setdefault("figsize", figsize) 38 | backend_kwargs.setdefault("sharex", True) 39 | backend_kwargs.setdefault("sharey", True) 40 | backend_kwargs.setdefault("squeeze", True) 41 | 42 | if axes is None: 43 | _, axes = create_axes_grid( 44 | len(plotters), 45 | rows, 46 | cols, 47 | backend_kwargs=backend_kwargs, 48 | ) 49 | 50 | for (var_name, selection, isel, x), ax in zip(plotters, np.ravel(axes)): 51 | x_prime = x 52 | if combined: 53 | x_prime = x.flatten() 54 | c_i = 1.96 / x_prime.size**0.5 55 | y = autocorr(x_prime) 56 | 57 | ax.fill_between([0, max_lag], -c_i, c_i, color="0.75") 58 | ax.vlines(x=np.arange(0, max_lag), ymin=0, ymax=y[0:max_lag], lw=linewidth) 59 | 60 | ax.set_title( 61 | labeller.make_label_vert(var_name, selection, isel), fontsize=titlesize, wrap=True 62 | ) 63 | ax.tick_params(labelsize=xt_labelsize) 64 | 65 | if np.asarray(axes).size > 0: 66 | np.asarray(axes).item(0).set_xlim(0, max_lag) 67 | np.asarray(axes).item(0).set_ylim(-1, 1) 68 | 69 | if backend_show(show): 70 | plt.show() 71 | 72 | return axes 73 | -------------------------------------------------------------------------------- /arviz/plots/backends/matplotlib/bfplot.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | from . import backend_kwarg_defaults, backend_show, create_axes_grid, matplotlib_kwarg_dealiaser 4 | from ...distplot import plot_dist 5 | from ...plot_utils import _scale_fig_size 6 | 7 | 8 | def plot_bf( 9 | ax, 10 | bf_10, 11 | bf_01, 12 | prior, 13 | posterior, 14 | ref_val, 15 | prior_at_ref_val, 16 | posterior_at_ref_val, 17 | var_name, 18 | colors, 19 | figsize, 20 | textsize, 21 | plot_kwargs, 22 | hist_kwargs, 23 | backend_kwargs, 24 | show, 25 | ): 26 | """Matplotlib Bayes Factor plot.""" 27 | if backend_kwargs is None: 28 | backend_kwargs = {} 29 | 30 | if hist_kwargs is None: 31 | hist_kwargs = {} 32 | 33 | backend_kwargs = { 34 | **backend_kwarg_defaults(), 35 | **backend_kwargs, 36 | } 37 | 38 | figsize, _, _, _, linewidth, _ = _scale_fig_size(figsize, textsize, 1, 1) 39 | 40 | plot_kwargs = matplotlib_kwarg_dealiaser(plot_kwargs, "plot") 41 | plot_kwargs.setdefault("linewidth", linewidth) 42 | hist_kwargs.setdefault("alpha", 0.5) 43 | 44 | backend_kwargs.setdefault("figsize", figsize) 45 | backend_kwargs.setdefault("squeeze", True) 46 | 47 | if ax is None: 48 | _, ax = create_axes_grid(1, backend_kwargs=backend_kwargs) 49 | 50 | plot_dist( 51 | prior, 52 | color=colors[0], 53 | label="Prior", 54 | ax=ax, 55 | plot_kwargs=plot_kwargs, 56 | hist_kwargs=hist_kwargs, 57 | ) 58 | plot_dist( 59 | posterior, 60 | color=colors[1], 61 | label="Posterior", 62 | ax=ax, 63 | plot_kwargs=plot_kwargs, 64 | hist_kwargs=hist_kwargs, 65 | ) 66 | 67 | ax.plot(ref_val, posterior_at_ref_val, "ko", lw=1.5) 68 | ax.plot(ref_val, prior_at_ref_val, "ko", lw=1.5) 69 | ax.axvline(ref_val, color="k", ls="--") 70 | ax.set_xlabel(var_name) 71 | ax.set_ylabel("Density") 72 | ax.set_title(f"The BF_10 is {bf_10:.2f}\nThe BF_01 is {bf_01:.2f}") 73 | plt.legend() 74 | 75 | if backend_show(show): 76 | plt.show() 77 | 78 | return ax 79 | -------------------------------------------------------------------------------- /doc/source/contributing/docstrings.md: -------------------------------------------------------------------------------- 1 | (docstrings)= 2 | # Docstring style 3 | 4 | Docstrings should follow the 5 | [numpy docstring guide](https://numpydoc.readthedocs.io/en/latest/format.html). Read more about it {ref}`docstring_formatting`. 6 | In ArviZ docs, docstrings consit of five main sections, i.e., 7 | 1. Short summary 8 | 2. Parameters 9 | 3. Returns 10 | 4. See Also 11 | 5. Examples 12 | Extended summary is strongly encouraged and references is required when relevant in order to cite the papers proposing or explaining the algorithms that are implemented. All other sections can also be used when convenient. 13 | 14 | ## References 15 | While adding description of parameters, examples, etc, it is important to add references to external libraries and ArviZ. 16 | Docstrings follow the same guide for adding references as the other docs. 17 | For adding references to external libraries functions and objects, see {ref}`reference_external_libs`. For referencing ArviZ objects, follow {ref}`reference_arviz_objects`. 18 | 19 | ## See Also 20 | In ArviZ docs, we have a lot of interconnected functions both within the library and with external libraries and it can take a lot of time to search for the related functions. It is cruical to add the See Also section to save users time. 21 | For adding the _See Also_ docstring section, you just need to add the function name. Sphinx will 22 | automatically add links to other ArviZ objects and functions listed in the _See Also_ 23 | section. 24 | 25 | For example, let's add {func}`~arviz.hdi` and {func}`~arviz.plot_ppc` in the _See Also_ section. 26 | 27 | ``` 28 | See Also 29 | -------- 30 | hdi : Calculate highest density interval (HDI) of array for given probability. 31 | plot_ppc : plot for posterior/prior predictive checks. 32 | ``` 33 | 34 | ## Kwargs parameters 35 | All the kwargs parameters in {ref}`plots ` modules are passed to the matplotlib or bokeh functions. While writing their description, the functions to which they are being passed must be mentioned. In order to check or add those functions, the process is the same for all the kwargs arguments. Let's read the step-by-step guide for `backend_kwargs` as an example, [here](https://github.com/arviz-devs/arviz/wiki/ArviZ-Hacktoberfest-2021). 36 | -------------------------------------------------------------------------------- /doc/source/api/inference_data.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: arviz 2 | 3 | .. _idata_api: 4 | 5 | InferenceData 6 | ------------- 7 | 8 | Constructor 9 | ........... 10 | 11 | .. autosummary:: 12 | :toctree: generated/ 13 | 14 | InferenceData 15 | 16 | Attributes 17 | .......... 18 | ``InferenceData`` objects store :class:`xarray:xarray.Dataset` as attributes. 19 | The :ref:`schema` contains the guidance related to these attributes. 20 | 21 | .. autosummary:: 22 | :toctree: generated/ 23 | 24 | InferenceData.get_index 25 | 26 | IO / Conversion 27 | ............... 28 | 29 | .. autosummary:: 30 | :toctree: generated/ 31 | 32 | InferenceData.to_dataframe 33 | InferenceData.to_json 34 | InferenceData.from_netcdf 35 | InferenceData.to_netcdf 36 | InferenceData.from_zarr 37 | InferenceData.to_zarr 38 | InferenceData.chunk 39 | InferenceData.close 40 | InferenceData.compute 41 | InferenceData.load 42 | InferenceData.persist 43 | InferenceData.unify_chunks 44 | 45 | Dictionary interface 46 | .................... 47 | 48 | .. autosummary:: 49 | :toctree: generated/ 50 | 51 | InferenceData.groups 52 | InferenceData.items 53 | InferenceData.values 54 | 55 | InferenceData contents 56 | ...................... 57 | 58 | .. autosummary:: 59 | :toctree: generated/ 60 | 61 | InferenceData.add_groups 62 | InferenceData.extend 63 | InferenceData.assign 64 | InferenceData.assign_coords 65 | InferenceData.rename 66 | InferenceData.rename_dims 67 | InferenceData.set_coords 68 | InferenceData.set_index 69 | 70 | Indexing 71 | ........ 72 | 73 | .. autosummary:: 74 | :toctree: generated/ 75 | 76 | InferenceData.isel 77 | InferenceData.sel 78 | InferenceData.reset_index 79 | 80 | Computation 81 | ........... 82 | 83 | .. autosummary:: 84 | :toctree: generated/ 85 | 86 | InferenceData.map 87 | InferenceData.cumsum 88 | InferenceData.max 89 | InferenceData.mean 90 | InferenceData.median 91 | InferenceData.min 92 | InferenceData.quantile 93 | InferenceData.sum 94 | 95 | Reshaping and reorganizing 96 | .......................... 97 | 98 | .. autosummary:: 99 | :toctree: generated/ 100 | 101 | InferenceData.stack 102 | InferenceData.unstack 103 | -------------------------------------------------------------------------------- /doc/source/_static/key_feature_visualizations.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/bug-fix.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 20 | 21 | 22 | ## Checklist 23 | 24 | 25 | - [ ] Does the PR follow [official](https://github.com/arviz-devs/arviz/blob/main/CONTRIBUTING.md#pull-request-checklist) 26 | PR format? 27 | - [ ] Does the PR include new or updated tests to prevent issue recurrence (using [pytest fixture pattern]( 28 | https://docs.pytest.org/en/latest/fixture.html#fixture))? 29 | - [ ] Is the code style correct (follows pylint and black guidelines)? 30 | - [ ] Is the fix listed in the [Maintenance and fixes](https://github.com/arviz-devs/arviz/blob/main/CHANGELOG.md#maintenance-and-fixes) 31 | section of the changelog? 32 | 33 | 44 | -------------------------------------------------------------------------------- /doc/source/contributing/diataxis_for_arviz.md: -------------------------------------------------------------------------------- 1 | (diataxis_for_arviz)= 2 | # Diátaxis for ArviZ 3 | 4 | ArviZ documentation has the {doc}`diataxis:index` as a North Star. 5 | 6 | There are however some specificities to ArviZ case and knowing Diátaxis alone 7 | is not enough to be able to understand ArviZ doc structure and correctly place 8 | new content pages within it. 9 | At the same time, having a basic understanding of Diátaxis is needed to understand 10 | this page and the content structure in ArviZ docs. 11 | 12 | These are: 13 | 14 | * Multiple target audiences and documentation goals 15 | * Strong visual component 16 | * Work in progress 17 | 18 | ## Multiple target audiences 19 | Diátaxis is a framework based around **user needs** in their exercise of a 20 | **practical craft** (more detail at {ref}`diataxis:needs` page in Diatáxis website). 21 | 22 | The scope of the ArviZ website however is not limited to ArviZ users nor it is limited to practical 23 | crafts like using ArviZ or contributing to it. 24 | 25 | After careful consideration, we decided to split the website into three components: 26 | two practical crafts, using and contributing 27 | (each of which follows Diátaxis independently of the other) 28 | and general information about the ArviZ project, 29 | it's people, community, marketing info... 30 | which can nor should follow the Diátaxis framework. 31 | 32 | ## Strong visual component 33 | ArviZ is a library with a strong visualization component. 34 | This translates for example into some duplicity when it comes to reference content. 35 | 36 | Both the {ref}`example_gallery` and the {ref}`api` pages are reference content. 37 | The API reference indexes by name and contains the description of each object, 38 | whereas the Example Gallery indexes by image and to avoid excessive duplication, 39 | links to the respective API page. 40 | 41 | This allows users who know the name of the function or who want to check the options 42 | available for the function they are currently using to quickly find it in the 43 | API reference while also allowing users who know how a plot looks but don't know 44 | their name nor the right ArviZ function to find it in the Example Gallery. 45 | 46 | ## Work in progress 47 | In addition, ArviZ documentation itself and the application of Diátaxis to it 48 | is still an active work in progress. That means that some pages will not 49 | match what is described in {ref}`content_structure` because their updating to 50 | enforce Diátaxis is still pending. 51 | -------------------------------------------------------------------------------- /arviz/data/example_data/.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | .virtual_documents 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | .python-version 87 | 88 | # pipenv 89 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 90 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 91 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 92 | # install all needed dependencies. 93 | #Pipfile.lock 94 | 95 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 96 | __pypackages__/ 97 | 98 | # Celery stuff 99 | celerybeat-schedule 100 | celerybeat.pid 101 | 102 | # SageMath parsed files 103 | *.sage.py 104 | 105 | # Environments 106 | .env 107 | .venv 108 | env/ 109 | venv/ 110 | ENV/ 111 | env.bak/ 112 | venv.bak/ 113 | 114 | # Spyder project settings 115 | .spyderproject 116 | .spyproject 117 | 118 | # Rope project settings 119 | .ropeproject 120 | 121 | # mkdocs documentation 122 | /site 123 | 124 | # mypy 125 | .mypy_cache/ 126 | .dmypy.json 127 | dmypy.json 128 | 129 | # Pyre type checker 130 | .pyre/ 131 | -------------------------------------------------------------------------------- /scripts/container.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | SRC_DIR=${SRC_DIR:-`pwd`} 3 | 4 | if [[ $* == *--clear-cache* ]]; then 5 | echo "Removing cached files and models" 6 | find -type d -name __pycache__ -exec rm -rf {} + 7 | rm -f arviz/tests/saved_models/*.pkl 8 | rm -f arviz/tests/saved_models/*.pkl.gzip 9 | fi 10 | 11 | # Build container for use of testing or notebook 12 | if [[ $* == *--build* ]]; then 13 | echo "Building Docker Image" 14 | docker build \ 15 | -t arviz \ 16 | -f $SRC_DIR/scripts/Dockerfile \ 17 | --build-arg SRC_DIR=. $SRC_DIR \ 18 | --build-arg PYTHON_VERSION=${PYTHON_VERSION} \ 19 | --build-arg PYSTAN_VERSION=${PYSTAN_VERSION} \ 20 | --build-arg PYRO_VERSION=${PYRO_VERSION} \ 21 | --build-arg PYTORCH_VERSION=${PYTORCH_VERSION} \ 22 | --build-arg EMCEE_VERSION=${EMCEE_VERSION} \ 23 | --build-arg TF_VERSION=${TF_VERSION} \ 24 | --build-arg PYMC3_VERSION=${PYMC3_VERSION} 25 | fi 26 | 27 | 28 | if [[ $* == *--test* ]]; then 29 | echo "Testing Arviz" 30 | docker run --mount type=bind,source="$(pwd)",target=/opt/arviz/ --rm arviz:latest bash -c \ 31 | "NUMBA_DISABLE_JIT=1 pytest -v arviz/tests/ --cov=arviz/" 32 | fi 33 | 34 | 35 | if [[ $* == *--docs* ]]; then 36 | echo "Build docs with sphinx" 37 | docker run --mount type=bind,source="$(pwd)",target=/opt/arviz --name arviz_sphinx --rm arviz:latest bash -c \ 38 | "if [ -d ./doc/build ]; then python -msphinx -M clean doc/source doc/build; fi && sphinx-build doc/source doc/build -b html" 39 | echo "Successful build. Find html docs in doc/build directory" 40 | fi 41 | 42 | 43 | if [[ $* == *--shell* ]]; then 44 | echo "Starting Arviz Container Shell" 45 | docker run -it --mount type=bind,source="$(pwd)",target=/opt/arviz --name arviz_shell --rm arviz:latest /bin/bash 46 | fi 47 | 48 | 49 | if [[ $* == *--notebook* ]]; then 50 | echo "Starting Arviz Container Jupyter server" 51 | docker run --mount type=bind,source="$(pwd)",target=/opt/arviz/ --name jupyter-dock -it -d -p 8888:8888 arviz 52 | docker exec -it jupyter-dock bash -c "jupyter notebook --ip 0.0.0.0 --no-browser --allow-root" 53 | fi 54 | 55 | 56 | if [[ $* == *--lab* ]]; then 57 | echo "Starting Arviz Container Jupyter server with Jupyter Lab interface" 58 | docker run --mount type=bind,source="$(pwd)",target=/opt/arviz/ --name jupyter-dock -it -d -p 8888:8888 arviz 59 | docker exec -it jupyter-dock bash -c "jupyter lab --ip 0.0.0.0 --no-browser --allow-root" 60 | fi 61 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/documentation.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 20 | 21 | ## Checklist 22 | 23 | 24 | - [ ] Does the PR follow [official](https://github.com/arviz-devs/arviz/blob/main/CONTRIBUTING.md#pull-request-checklist) 25 | PR format? 26 | - [ ] Is the documentation [numpydoc](https://numpydoc.readthedocs.io/en/latest/format.html) compliant? 27 | - [ ] Is the fix listed in the [Documentation](https://github.com/arviz-devs/arviz/blob/main/CHANGELOG.md#documentation) 28 | section of the changelog? 29 | 30 | 46 | -------------------------------------------------------------------------------- /arviz/plots/backends/bokeh/parallelplot.py: -------------------------------------------------------------------------------- 1 | """Bokeh Parallel coordinates plot.""" 2 | 3 | import numpy as np 4 | from bokeh.models import DataRange1d 5 | from bokeh.models.tickers import FixedTicker 6 | 7 | from ...plot_utils import _scale_fig_size 8 | from .. import show_layout 9 | from . import backend_kwarg_defaults, create_axes_grid 10 | 11 | 12 | def plot_parallel( 13 | ax, 14 | colornd, # pylint: disable=unused-argument 15 | colord, # pylint: disable=unused-argument 16 | shadend, # pylint: disable=unused-argument 17 | diverging_mask, 18 | posterior, 19 | textsize, 20 | var_names, 21 | legend, # pylint: disable=unused-argument 22 | figsize, 23 | backend_kwargs, 24 | backend_config, 25 | show, 26 | ): 27 | """Bokeh parallel plot.""" 28 | if backend_config is None: 29 | backend_config = {} 30 | 31 | backend_config = { 32 | **backend_kwarg_defaults( 33 | ("bounds_x_range", "plot.bokeh.bounds_x_range"), 34 | ("bounds_y_range", "plot.bokeh.bounds_y_range"), 35 | ), 36 | **backend_config, 37 | } 38 | 39 | if backend_kwargs is None: 40 | backend_kwargs = {} 41 | 42 | backend_kwargs = { 43 | **backend_kwarg_defaults(), 44 | **backend_kwargs, 45 | } 46 | 47 | figsize, *_ = _scale_fig_size(figsize, textsize, 1, 1) 48 | 49 | if ax is None: 50 | ax = create_axes_grid( 51 | 1, 52 | figsize=figsize, 53 | squeeze=True, 54 | backend_kwargs=backend_kwargs, 55 | ) 56 | 57 | non_div = list(posterior[:, ~diverging_mask].T) 58 | x_non_div = [list(range(len(non_div[0]))) for _ in range(len(non_div))] 59 | 60 | ax.multi_line( 61 | x_non_div, 62 | non_div, 63 | line_color="black", 64 | line_alpha=0.05, 65 | ) 66 | 67 | if np.any(diverging_mask): 68 | div = list(posterior[:, diverging_mask].T) 69 | x_non_div = [list(range(len(div[0]))) for _ in range(len(div))] 70 | ax.multi_line(x_non_div, div, color="lime", line_width=1, line_alpha=0.5) 71 | 72 | ax.xaxis.ticker = FixedTicker(ticks=list(range(len(var_names)))) 73 | ax.xaxis.major_label_overrides = dict(zip(map(str, range(len(var_names))), map(str, var_names))) 74 | ax.xaxis.major_label_orientation = np.pi / 2 75 | 76 | ax.x_range = DataRange1d(bounds=backend_config["bounds_x_range"], min_interval=2) 77 | ax.y_range = DataRange1d(bounds=backend_config["bounds_y_range"], min_interval=5) 78 | 79 | show_layout(ax, show) 80 | 81 | return ax 82 | -------------------------------------------------------------------------------- /arviz/data/io_netcdf.py: -------------------------------------------------------------------------------- 1 | """Input and output support for data.""" 2 | 3 | from .converters import convert_to_inference_data 4 | from .inference_data import InferenceData 5 | 6 | 7 | def from_netcdf(filename, *, engine="h5netcdf", group_kwargs=None, regex=False): 8 | """Load netcdf file back into an arviz.InferenceData. 9 | 10 | Parameters 11 | ---------- 12 | filename : str 13 | name or path of the file to load trace 14 | engine : {"h5netcdf", "netcdf4"}, default "h5netcdf" 15 | Library used to read the netcdf file. 16 | group_kwargs : dict of {str: dict} 17 | Keyword arguments to be passed into each call of :func:`xarray.open_dataset`. 18 | The keys of the higher level should be group names or regex matching group 19 | names, the inner dicts re passed to ``open_dataset``. 20 | This feature is currently experimental 21 | regex : str 22 | Specifies where regex search should be used to extend the keyword arguments. 23 | 24 | Returns 25 | ------- 26 | InferenceData object 27 | 28 | Notes 29 | ----- 30 | By default, the datasets of the InferenceData object will be lazily loaded instead 31 | of loaded into memory. This behaviour is regulated by the value of 32 | ``az.rcParams["data.load"]``. 33 | """ 34 | if group_kwargs is None: 35 | group_kwargs = {} 36 | return InferenceData.from_netcdf( 37 | filename, engine=engine, group_kwargs=group_kwargs, regex=regex 38 | ) 39 | 40 | 41 | def to_netcdf(data, filename, *, group="posterior", engine="h5netcdf", coords=None, dims=None): 42 | """Save dataset as a netcdf file. 43 | 44 | WARNING: Only idempotent in case `data` is InferenceData 45 | 46 | Parameters 47 | ---------- 48 | data : InferenceData, or any object accepted by `convert_to_inference_data` 49 | Object to be saved 50 | filename : str 51 | name or path of the file to load trace 52 | group : str (optional) 53 | In case `data` is not InferenceData, this is the group it will be saved to 54 | engine : {"h5netcdf", "netcdf4"}, default "h5netcdf" 55 | Library used to read the netcdf file. 56 | coords : dict (optional) 57 | See `convert_to_inference_data` 58 | dims : dict (optional) 59 | See `convert_to_inference_data` 60 | 61 | Returns 62 | ------- 63 | str 64 | filename saved to 65 | """ 66 | inference_data = convert_to_inference_data(data, group=group, coords=coords, dims=dims) 67 | file_name = inference_data.to_netcdf(filename, engine=engine) 68 | return file_name 69 | -------------------------------------------------------------------------------- /arviz/plots/backends/matplotlib/separationplot.py: -------------------------------------------------------------------------------- 1 | """Matplotlib separation plot.""" 2 | 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | 6 | from ...plot_utils import _scale_fig_size 7 | from . import backend_kwarg_defaults, backend_show, create_axes_grid 8 | 9 | 10 | def plot_separation( 11 | y, 12 | y_hat, 13 | y_hat_line, 14 | label_y_hat, 15 | expected_events, 16 | figsize, 17 | textsize, 18 | color, 19 | legend, 20 | locs, 21 | width, 22 | ax, 23 | plot_kwargs, 24 | y_hat_line_kwargs, 25 | exp_events_kwargs, 26 | backend_kwargs, 27 | show, 28 | ): 29 | """Matplotlib separation plot.""" 30 | if backend_kwargs is None: 31 | backend_kwargs = {} 32 | 33 | if plot_kwargs is None: 34 | plot_kwargs = {} 35 | 36 | # plot_kwargs.setdefault("color", "C0") 37 | # if color: 38 | plot_kwargs["color"] = color 39 | 40 | if y_hat_line_kwargs is None: 41 | y_hat_line_kwargs = {} 42 | 43 | y_hat_line_kwargs.setdefault("color", "k") 44 | 45 | if exp_events_kwargs is None: 46 | exp_events_kwargs = {} 47 | 48 | exp_events_kwargs.setdefault("color", "k") 49 | exp_events_kwargs.setdefault("marker", "^") 50 | exp_events_kwargs.setdefault("s", 100) 51 | exp_events_kwargs.setdefault("zorder", 2) 52 | 53 | backend_kwargs = { 54 | **backend_kwarg_defaults(), 55 | **backend_kwargs, 56 | } 57 | 58 | (figsize, *_) = _scale_fig_size(figsize, textsize, 1, 1) 59 | backend_kwargs.setdefault("figsize", figsize) 60 | backend_kwargs["squeeze"] = True 61 | 62 | if ax is None: 63 | _, ax = create_axes_grid(1, backend_kwargs=backend_kwargs) 64 | 65 | idx = np.argsort(y_hat) 66 | 67 | for i, loc in enumerate(locs): 68 | positive = not y[idx][i] == 0 69 | alpha = 1 if positive else 0.3 70 | ax.bar(loc, 1, width=width, alpha=alpha, **plot_kwargs) 71 | 72 | if y_hat_line: 73 | ax.plot(np.linspace(0, 1, len(y_hat)), y_hat[idx], label=label_y_hat, **y_hat_line_kwargs) 74 | 75 | if expected_events: 76 | expected_events = int(np.round(np.sum(y_hat))) 77 | ax.scatter( 78 | y_hat[idx][len(y_hat) - expected_events - 1], 79 | 0, 80 | label="Expected events", 81 | **exp_events_kwargs 82 | ) 83 | 84 | if legend and (expected_events or y_hat_line): 85 | handles, labels = ax.get_legend_handles_labels() 86 | labels_dict = dict(zip(labels, handles)) 87 | ax.legend(labels_dict.values(), labels_dict.keys()) 88 | 89 | ax.set_xticks([]) 90 | ax.set_yticks([]) 91 | ax.set_xlim(0, 1) 92 | ax.set_ylim(0, 1) 93 | 94 | if backend_show(show): 95 | plt.show() 96 | 97 | return ax 98 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/new-feature.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 20 | 21 | 22 | ## Checklist 23 | 24 | 25 | - [ ] Does the PR follow [official](https://github.com/arviz-devs/arviz/blob/main/CONTRIBUTING.md#pull-request-checklist) 26 | PR format? 27 | - [ ] Has included a sample plot to visually illustrate the changes? (only for plot-related functions) 28 | - [ ] Is the new feature properly documented with an example? 29 | - [ ] Does the PR include new or updated tests to cover the new feature (using [pytest fixture pattern]( 30 | https://docs.pytest.org/en/latest/fixture.html#fixture))? 31 | - [ ] Is the code style correct (follows pylint and black guidelines)? 32 | - [ ] Is the new feature listed in the [New features](https://github.com/arviz-devs/arviz/blob/main/CHANGELOG.md#new-features) 33 | section of the changelog? 34 | 35 | 51 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import codecs 2 | import os 3 | import re 4 | 5 | import setuptools 6 | from setuptools import find_packages, setup 7 | from setuptools.command.develop import develop 8 | from setuptools.command.install import install 9 | 10 | PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__)) 11 | REQUIREMENTS_FILE = os.path.join(PROJECT_ROOT, "requirements.txt") 12 | REQUIREMENTS_OPTIONAL_FILE = os.path.join(PROJECT_ROOT, "requirements-optional.txt") 13 | REQUIREMENTS_DEV_FILE = os.path.join(PROJECT_ROOT, "requirements-dev.txt") 14 | README_FILE = os.path.join(PROJECT_ROOT, "README.md") 15 | VERSION_FILE = os.path.join(PROJECT_ROOT, "arviz", "__init__.py") 16 | 17 | 18 | def get_requirements(): 19 | with codecs.open(REQUIREMENTS_FILE) as buff: 20 | return buff.read().splitlines() 21 | 22 | 23 | def get_requirements_dev(): 24 | with codecs.open(REQUIREMENTS_DEV_FILE) as buff: 25 | return buff.read().splitlines() 26 | 27 | 28 | def get_requirements_optional(): 29 | with codecs.open(REQUIREMENTS_OPTIONAL_FILE) as buff: 30 | return buff.read().splitlines() 31 | 32 | 33 | def get_long_description(): 34 | with codecs.open(README_FILE, "rt") as buff: 35 | return buff.read() 36 | 37 | 38 | def get_version(): 39 | lines = open(VERSION_FILE, "rt").readlines() 40 | version_regex = r"^__version__ = ['\"]([^'\"]*)['\"]" 41 | for line in lines: 42 | mo = re.search(version_regex, line, re.M) 43 | if mo: 44 | return mo[1] 45 | raise RuntimeError(f"Unable to find version in {VERSION_FILE}.") 46 | 47 | 48 | setup( 49 | name="arviz", 50 | license="Apache-2.0", 51 | version=get_version(), 52 | description="Exploratory analysis of Bayesian models", 53 | author="ArviZ Developers", 54 | url="http://github.com/arviz-devs/arviz", 55 | packages=find_packages(), 56 | install_requires=get_requirements(), 57 | extras_require={ 58 | "all": get_requirements_optional(), 59 | "preview": ["arviz-base[h5netcdf]", "arviz-stats[xarray]", "arviz-plots"], 60 | }, 61 | long_description=get_long_description(), 62 | long_description_content_type="text/markdown", 63 | include_package_data=True, 64 | python_requires=">=3.10", 65 | classifiers=[ 66 | "Development Status :: 4 - Beta", 67 | "Framework :: Matplotlib", 68 | "Intended Audience :: Science/Research", 69 | "Intended Audience :: Education", 70 | "License :: OSI Approved :: Apache Software License", 71 | "Programming Language :: Python", 72 | "Programming Language :: Python :: 3", 73 | "Programming Language :: Python :: 3.10", 74 | "Programming Language :: Python :: 3.11", 75 | "Programming Language :: Python :: 3.12", 76 | "Topic :: Scientific/Engineering", 77 | "Topic :: Scientific/Engineering :: Visualization", 78 | "Topic :: Scientific/Engineering :: Mathematics", 79 | ], 80 | ) 81 | -------------------------------------------------------------------------------- /arviz/tests/external_tests/test_data_beanmachine.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=no-member, invalid-name, redefined-outer-name 2 | import numpy as np 3 | import pytest 4 | 5 | from ...data.io_beanmachine import from_beanmachine # pylint: disable=wrong-import-position 6 | from ..helpers import ( # pylint: disable=unused-import, wrong-import-position 7 | chains, 8 | draws, 9 | eight_schools_params, 10 | importorskip, 11 | load_cached_models, 12 | ) 13 | 14 | pytest.skip("Ignore beanmachine tests until it supports pytorch 2", allow_module_level=True) 15 | 16 | # Skip all tests if beanmachine or pytorch not installed 17 | torch = importorskip("torch") 18 | bm = importorskip("beanmachine.ppl") 19 | dist = torch.distributions 20 | 21 | 22 | class TestDataBeanMachine: 23 | @pytest.fixture(scope="class") 24 | def data(self, eight_schools_params, draws, chains): 25 | class Data: 26 | model, prior, obj = load_cached_models( 27 | eight_schools_params, 28 | draws, 29 | chains, 30 | "beanmachine", 31 | )["beanmachine"] 32 | 33 | return Data 34 | 35 | @pytest.fixture(scope="class") 36 | def predictions_data(self, data): 37 | """Generate predictions for predictions_params""" 38 | posterior_samples = data.obj 39 | model = data.model 40 | predictions = bm.inference.predictive.simulate([model.obs()], posterior_samples) 41 | return predictions 42 | 43 | def get_inference_data(self, eight_schools_params, predictions_data): 44 | predictions = predictions_data 45 | return from_beanmachine( 46 | sampler=predictions, 47 | coords={ 48 | "school": np.arange(eight_schools_params["J"]), 49 | "school_pred": np.arange(eight_schools_params["J"]), 50 | }, 51 | ) 52 | 53 | def test_inference_data(self, data, eight_schools_params, predictions_data): 54 | inference_data = self.get_inference_data(eight_schools_params, predictions_data) 55 | model = data.model 56 | mu = model.mu() 57 | tau = model.tau() 58 | eta = model.eta() 59 | obs = model.obs() 60 | 61 | assert mu in inference_data.posterior 62 | assert tau in inference_data.posterior 63 | assert eta in inference_data.posterior 64 | assert obs in inference_data.posterior_predictive 65 | 66 | def test_inference_data_has_log_likelihood_and_observed_data(self, data): 67 | idata = from_beanmachine(data.obj) 68 | obs = data.model.obs() 69 | 70 | assert obs in idata.log_likelihood 71 | assert obs in idata.observed_data 72 | 73 | def test_inference_data_no_posterior(self, data): 74 | model = data.model 75 | # only prior 76 | inference_data = from_beanmachine(data.prior) 77 | assert not model.obs() in inference_data.posterior 78 | assert "observed_data" not in inference_data 79 | -------------------------------------------------------------------------------- /arviz/plots/backends/bokeh/separationplot.py: -------------------------------------------------------------------------------- 1 | """Bokeh separation plot.""" 2 | 3 | import numpy as np 4 | 5 | from ...plot_utils import _scale_fig_size, vectorized_to_hex 6 | from .. import show_layout 7 | from . import backend_kwarg_defaults, create_axes_grid 8 | 9 | 10 | def plot_separation( 11 | y, 12 | y_hat, 13 | y_hat_line, 14 | label_y_hat, 15 | expected_events, 16 | figsize, 17 | textsize, 18 | color, 19 | legend, 20 | locs, 21 | width, 22 | ax, 23 | plot_kwargs, 24 | y_hat_line_kwargs, 25 | exp_events_kwargs, 26 | backend_kwargs, 27 | show, 28 | ): 29 | """Matplotlib separation plot.""" 30 | if backend_kwargs is None: 31 | backend_kwargs = {} 32 | 33 | if plot_kwargs is None: 34 | plot_kwargs = {} 35 | 36 | # plot_kwargs.setdefault("color", "#2a2eec") 37 | # if color: 38 | plot_kwargs["color"] = vectorized_to_hex(color) 39 | 40 | backend_kwargs = { 41 | **backend_kwarg_defaults(), 42 | **backend_kwargs, 43 | } 44 | 45 | if y_hat_line_kwargs is None: 46 | y_hat_line_kwargs = {} 47 | 48 | y_hat_line_kwargs.setdefault("color", "black") 49 | y_hat_line_kwargs.setdefault("line_width", 2) 50 | 51 | if exp_events_kwargs is None: 52 | exp_events_kwargs = {} 53 | 54 | exp_events_kwargs.setdefault("color", "black") 55 | exp_events_kwargs.setdefault("size", 15) 56 | 57 | if legend: 58 | y_hat_line_kwargs.setdefault("legend_label", label_y_hat) 59 | exp_events_kwargs.setdefault( 60 | "legend_label", 61 | "Expected events", 62 | ) 63 | 64 | figsize, *_ = _scale_fig_size(figsize, textsize) 65 | 66 | idx = np.argsort(y_hat) 67 | 68 | backend_kwargs["x_range"] = (0, 1) 69 | backend_kwargs["y_range"] = (0, 1) 70 | 71 | if ax is None: 72 | ax = create_axes_grid(1, figsize=figsize, squeeze=True, backend_kwargs=backend_kwargs) 73 | 74 | for i, loc in enumerate(locs): 75 | positive = not y[idx][i] == 0 76 | alpha = 1 if positive else 0.3 77 | ax.vbar( 78 | loc, 79 | top=1, 80 | width=width, 81 | fill_alpha=alpha, 82 | line_alpha=alpha, 83 | **plot_kwargs, 84 | ) 85 | 86 | if y_hat_line: 87 | ax.line( 88 | np.linspace(0, 1, len(y_hat)), 89 | y_hat[idx], 90 | **y_hat_line_kwargs, 91 | ) 92 | 93 | if expected_events: 94 | expected_events = int(np.round(np.sum(y_hat))) 95 | ax.triangle( 96 | y_hat[idx][len(y_hat) - expected_events - 1], 97 | 0, 98 | **exp_events_kwargs, 99 | ) 100 | 101 | ax.axis.visible = False 102 | ax.xgrid.grid_line_color = None 103 | ax.ygrid.grid_line_color = None 104 | 105 | show_layout(ax, show) 106 | 107 | return ax 108 | -------------------------------------------------------------------------------- /arviz/plots/backends/bokeh/autocorrplot.py: -------------------------------------------------------------------------------- 1 | """Bokeh Autocorrplot.""" 2 | 3 | import numpy as np 4 | from bokeh.models import DataRange1d, BoxAnnotation 5 | from bokeh.models.annotations import Title 6 | 7 | 8 | from ....stats import autocorr 9 | from ...plot_utils import _scale_fig_size 10 | from .. import show_layout 11 | from . import backend_kwarg_defaults, create_axes_grid 12 | 13 | 14 | def plot_autocorr( 15 | axes, 16 | plotters, 17 | max_lag, 18 | figsize, 19 | rows, 20 | cols, 21 | combined, 22 | textsize, 23 | labeller, 24 | backend_config, 25 | backend_kwargs, 26 | show, 27 | ): 28 | """Bokeh autocorrelation plot.""" 29 | if backend_config is None: 30 | backend_config = {} 31 | 32 | len_y = plotters[0][-1].size 33 | backend_config.setdefault("bounds_x_range", (0, len_y)) 34 | 35 | backend_config = { 36 | **backend_kwarg_defaults( 37 | ("bounds_y_range", "plot.bokeh.bounds_y_range"), 38 | ), 39 | **backend_config, 40 | } 41 | 42 | if backend_kwargs is None: 43 | backend_kwargs = {} 44 | 45 | backend_kwargs = { 46 | **backend_kwarg_defaults( 47 | ("dpi", "plot.bokeh.figure.dpi"), 48 | ), 49 | **backend_kwargs, 50 | } 51 | 52 | figsize, _, _, _, line_width, _ = _scale_fig_size(figsize, textsize, rows, cols) 53 | 54 | if axes is None: 55 | axes = create_axes_grid( 56 | len(plotters), 57 | rows, 58 | cols, 59 | figsize=figsize, 60 | sharex=True, 61 | sharey=True, 62 | backend_kwargs=backend_kwargs, 63 | ) 64 | else: 65 | axes = np.atleast_2d(axes) 66 | 67 | data_range_x = DataRange1d( 68 | start=0, end=max_lag, bounds=backend_config["bounds_x_range"], min_interval=5 69 | ) 70 | data_range_y = DataRange1d( 71 | start=-1, end=1, bounds=backend_config["bounds_y_range"], min_interval=0.1 72 | ) 73 | 74 | for (var_name, selection, isel, x), ax in zip( 75 | plotters, (item for item in axes.flatten() if item is not None) 76 | ): 77 | x_prime = x 78 | if combined: 79 | x_prime = x.flatten() 80 | c_i = 1.96 / x_prime.size**0.5 81 | y = autocorr(x_prime) 82 | 83 | ax.add_layout(BoxAnnotation(bottom=-c_i, top=c_i, fill_color="gray")) 84 | ax.segment( 85 | x0=np.arange(len(y)), 86 | y0=0, 87 | x1=np.arange(len(y)), 88 | y1=y, 89 | line_width=line_width, 90 | line_color="black", 91 | ) 92 | 93 | title = Title() 94 | title.text = labeller.make_label_vert(var_name, selection, isel) 95 | ax.title = title 96 | ax.x_range = data_range_x 97 | ax.y_range = data_range_y 98 | 99 | show_layout(axes, show) 100 | 101 | return axes 102 | -------------------------------------------------------------------------------- /scripts/container.ps1: -------------------------------------------------------------------------------- 1 | if (!(Test-Path env:SRC_DIR)) { 2 | $SRC_DIR=$pwd.Path 3 | } 4 | 5 | $build = $false 6 | $clearCache = $false 7 | $docs = $false 8 | $lab = $false 9 | $notebook = $false 10 | $shell = $false 11 | $test = $false 12 | 13 | foreach ($arg in $args) { 14 | if ($arg -eq "--build") { 15 | $build = $true 16 | } 17 | elseif ($arg -eq "--clear-cache") { 18 | $clearCache = $true 19 | } 20 | elseif ($arg -eq "--docs") { 21 | $docs = $true 22 | } 23 | elseif ($arg -eq "--lab") { 24 | $lab = $true 25 | } 26 | elseif ($arg -eq "--notebook") { 27 | $notebook = $true 28 | } 29 | elseif ($arg -eq "--shell") { 30 | $shell = $true 31 | } 32 | elseif ($arg -eq "--test") { 33 | $test = $true 34 | } 35 | } 36 | 37 | if ($build) { 38 | echo "Building Docker Image" 39 | # Build container for use of testing or notebook 40 | docker build ` 41 | -t arviz ` 42 | -f $SRC_DIR/scripts/Dockerfile ` 43 | --build-arg SRC_DIR=. $SRC_DIR ` 44 | --build-arg PYTHON_VERSION=${PYTHON_VERSION} ` 45 | --build-arg PYSTAN_VERSION=${PYSTAN_VERSION} ` 46 | --build-arg PYRO_VERSION=${PYRO_VERSION} ` 47 | --build-arg PYTORCH_VERSION=${PYTORCH_VERSION} ` 48 | --build-arg EMCEE_VERSION=${EMCEE_VERSION} ` 49 | --build-arg TF_VERSION=${TF_VERSION} ` 50 | --build-arg PYMC3_VERSION=${PYMC3_VERSION} 51 | } 52 | 53 | if ($clearCache) { 54 | echo "Removing cached files and models" 55 | Get-ChildItem -Path $SRC_DIR -Recurse -Force -Include "__pycache__" | Remove-Item -Force -Recurse 56 | Get-ChildItem -Path ($SRC_DIR + "\arviz\tests\saved_models") -Recurse -Force -Include "*.pkl" | Remove-Item -Force -Recurse 57 | } 58 | 59 | if ($test) { 60 | echo "Testing Arviz" 61 | docker run --mount type=bind,source=$SRC_DIR,target=/opt/arviz/ --rm arviz:latest bash -c ` 62 | "NUMBA_DISABLE_JIT=1 pytest -v arviz/tests/ --cov=arviz/" 63 | } 64 | 65 | if ($docs) { 66 | echo "Build docs with sphinx" 67 | docker run --mount type=bind,source=$SRC_DIR,target=/opt/arviz --name arviz_sphinx --rm arviz:latest bash -c ` 68 | "if [ -d ./doc/build ]; then python -msphinx -M clean doc doc/build; fi && sphinx-build doc doc/build -b html" 69 | } 70 | 71 | if ($shell) { 72 | echo "Starting Arviz Container Shell" 73 | docker run -it --mount type=bind,source=$SRC_DIR,target=/opt/arviz --name arviz_shell --rm arviz:latest /bin/bash 74 | } 75 | 76 | if ($notebook) { 77 | echo "Starting Arviz Container Jupyter server" 78 | docker run --mount type=bind,source=$SRC_DIR,target=/opt/arviz/ --name jupyter-dock -it -d -p 8888:8888 arviz 79 | docker exec -it jupyter-dock bash -c "jupyter notebook --ip 0.0.0.0 --no-browser --allow-root" 80 | } 81 | 82 | if ($lab) { 83 | echo "Starting Arviz Container Jupyter server with Jupyter Lab interface" 84 | docker run --mount type=bind,source=$SRC_DIR,target=/opt/arviz/ --name jupyter-dock -it -d -p 8888:8888 arviz 85 | docker exec -it jupyter-dock bash -c "jupyter lab --ip 0.0.0.0 --no-browser --allow-root" 86 | } 87 | --------------------------------------------------------------------------------