### Install ArviZ from Source Source: https://github.com/arviz-devs/arviz/blob/main/README.md Clone the ArviZ repository and install it locally using setup.py. This method is useful for developers or for installing a specific commit. ```bash git clone https://github.com/arviz-devs/arviz.git cd arviz python setup.py install ``` -------------------------------- ### Install and Test ArviZ Locally Source: https://github.com/arviz-devs/arviz/wiki/ArviZ-Release-Checklist Install ArviZ in development mode and run the test suite. Ensure this is done after updating the version number. ```bash python setup.py develop pytest arviz/tests ``` -------------------------------- ### Install ArviZ with Preview Features Source: https://github.com/arviz-devs/arviz/blob/main/README.md Use this command to install the latest stable version of ArviZ along with preview features. This is useful for accessing the newest functionalities. ```bash pip install "arviz[preview]" ``` -------------------------------- ### Install Development Environment Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_tutorial.md Install tox and the ArviZ local package in editable mode to set up your development environment. ```bash pip install tox pip install -e . ``` -------------------------------- ### Install ArviZ with optional backends Source: https://context7.com/arviz-devs/arviz/llms.txt Install ArviZ using pip, specifying optional dependencies for plotting backends (Matplotlib, Bokeh, Plotly) and I/O support (NetCDF, Zarr). Conda installation is also available. ```bash pip install "arviz[matplotlib,h5netcdf]" ``` ```bash pip install "arviz[zarr,bokeh]" ``` ```bash pip install "arviz[plotly]" ``` ```bash conda install -c conda-forge arviz arviz-plots ``` -------------------------------- ### Install ArviZ with Optional Dependencies Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/getting_started.md Use this command to install ArviZ with specific optional features like I/O and plotting capabilities. Choose the features you need based on the available options. ```bash pip install "arviz[, ]" ``` ```bash pip install "arviz[zarr, matplotlib]" ``` ```bash pip install "arviz[h5netcdf, plotly, bokeh]" ``` -------------------------------- ### Verify PyPI Installation Source: https://github.com/arviz-devs/arviz/wiki/ArviZ-Release-Checklist After releasing to PyPI, install the new version and verify that ArviZ can be imported. This confirms the release was successful. ```python python -c 'from arviz import *' ``` -------------------------------- ### Load Built-in ArviZ Example Datasets Source: https://context7.com/arviz-devs/arviz/llms.txt Use `az.load_arviz_data` to load example datasets provided with ArviZ. This is useful for testing, learning, and reproducing documentation examples. The function returns an `InferenceData` object as a `DataTree`. ```python import arviz as az # List available datasets (see docs for full list) # Includes: "centered_eight", "non_centered_eight", "radon", "rugby", etc. dt = az.load_arviz_data("centered_eight") print(list(dt.children)) # ['posterior', 'posterior_predictive', 'log_likelihood', # 'sample_stats', 'prior', 'prior_predictive', 'observed_data', 'constant_data'] dt_nc = az.load_arviz_data("non_centered_eight") print(dt_nc["posterior"].dataset) # # Dimensions: (chain: 4, draw: 500, school: 8) # Data variables: # mu (chain, draw) float64 ... # theta_t (chain, draw, school) float64 ... # tau (chain, draw) float64 ... # theta (chain, draw, school) float64 ... ``` -------------------------------- ### Verify ArviZ Installation Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/getting_started.md Run this Python code to check if ArviZ is installed correctly and to display its version along with the versions of its constituent libraries. This helps in troubleshooting installation issues. ```python import arviz as az print(az.info) ``` -------------------------------- ### Build and Upload ArviZ to PyPI Source: https://github.com/arviz-devs/arviz/wiki/ArviZ-Release-Checklist Create source and wheel distributions and upload them to PyPI using Twine. Ensure Twine is installed and you have the necessary credentials. ```bash python setup.py sdist bdist_wheel twine upload dist/* ``` -------------------------------- ### Install ArviZ Development Version from GitHub Source: https://github.com/arviz-devs/arviz/blob/main/README.md Install the latest development version of ArviZ directly from its GitHub repository using pip. This is suitable for users who want to test the most recent code. ```bash pip install git+git://github.com/arviz-devs/arviz.git ``` -------------------------------- ### az.load_arviz_data Source: https://context7.com/arviz-devs/arviz/llms.txt Loads one of ArviZ's bundled example datasets as a `DataTree`. This function is useful for testing, learning, and reproducing examples from the documentation. ```APIDOC ## `az.load_arviz_data` — Load built-in example datasets Loads one of ArviZ's bundled example datasets as a `DataTree`. Useful for testing, learning, and reproducing examples from the documentation. ```python import arviz as az # List available datasets (see docs for full list) # Includes: "centered_eight", "non_centered_eight", "radon", "rugby", etc. dt = az.load_arviz_data("centered_eight") print(list(dt.children)) # ['posterior', 'posterior_predictive', 'log_likelihood', # 'sample_stats', 'prior', 'prior_predictive', 'observed_data', 'constant_data'] dt_nc = az.load_arviz_data("non_centered_eight") print(dt_nc["posterior"].dataset) # # Dimensions: (chain: 4, draw: 500, school: 8) # Data variables: # mu (chain, draw) float64 ... # theta_t (chain, draw, school) float64 ... # tau (chain, draw) float64 ... # theta (chain, draw, school) float64 ... ``` ``` -------------------------------- ### See Also Section Example Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/docstrings.md Illustrates how to format the 'See Also' section in a docstring, including function names and brief descriptions. Sphinx automatically creates links for listed ArviZ objects. ```python See Also -------- arviz_stats.hdi : Calculate highest density interval (HDI) of array for given probability. arviz_plots.plot_ppc_dist : plot for posterior/prior predictive checks. ``` -------------------------------- ### Verify ArviZ installation and component versions Source: https://context7.com/arviz-devs/arviz/llms.txt Use `az.info` to check the ArviZ version and confirm the availability of its sub-libraries (`arviz_base`, `arviz_stats`, `arviz_plots`). This is useful for troubleshooting import issues. Detailed logging can be enabled for further diagnostics. ```python import arviz as az print(az.info) # Status information for ArviZ 1.1.0 # # arviz_base 1.1.0 available, exposing its functions as part of the `arviz` namespace # arviz_stats 1.1.0 available, exposing its functions as part of the `arviz` namespace # arviz_plots 1.1.0 available, exposing its functions as part of the `arviz` namespace # Enable detailed logging if a library fails to import import logging logging.basicConfig(level=logging.INFO) import arviz as az ``` -------------------------------- ### Install ArviZ and ArviZ-Plots via Conda Source: https://github.com/arviz-devs/arviz/blob/main/README.md Install ArviZ and its plotting companion package using conda-forge. This command ensures both core ArviZ functionality and plotting tools are set up. ```bash conda install -c conda-forge arviz arviz-plots ``` -------------------------------- ### Setting computational backend to 'base' Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/migration_guide.ipynb Configure ArviZ to use the 'base' computational backend for statistics functions by setting `az.rcParams["stats.module"]`. This example also times the execution of the `histogram` method. ```python dt = az.load_arviz_data("radon") az.rcParams["stats.module"] = "base" %timeit dt.azstats.histogram(dim="draw") ``` -------------------------------- ### Setting computational backend to 'numba' Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/migration_guide.ipynb Configure ArviZ to use the 'numba' computational backend for statistics functions by setting `az.rcParams["stats.module"]`. This example also times the execution of the `histogram` method. ```python az.rcParams["stats.module"] = "numba" %timeit dt.azstats.histogram(dim="draw") ``` -------------------------------- ### Suggesting Matplotlib References with sphobjinv Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/syntax_guide.md Example of using the sphobjinv command-line tool to suggest possible references for 'axes.plot' from Matplotlib documentation. ```bash $ sphobjinv suggest -t 90 -u https://matplotlib.org/objects.inv "axes.plot" Remote inventory found. :py:method:`matplotlib.axes.Axes.plot` :py:method:`matplotlib.axes.Axes.plot_date` :std:doc:`api/_as_gen/matplotlib.axes.Axes.plot` :std:doc:`api/_as_gen/matplotlib.axes.Axes.plot_date` ``` -------------------------------- ### az.info — Verify installation and component versions Source: https://context7.com/arviz-devs/arviz/llms.txt A string attribute that reports the ArviZ version and the availability of each sub-library (`arviz_base`, `arviz_stats`, `arviz_plots`). Useful for troubleshooting import issues. ```APIDOC ## az.info ### Description Verifies ArviZ installation and component versions. ### Usage ```python import arviz as az print(az.info) ``` ### Example Output ``` Status information for ArviZ 1.1.0 arviz_base 1.1.0 available, exposing its functions as part of the `arviz` namespace arviz_stats 1.1.0 available, exposing its functions as part of the `arviz` namespace arviz_plots 1.1.0 available, exposing its functions as part of the `arviz` namespace ``` ``` -------------------------------- ### Legacy InferenceData Migration Warning Source: https://context7.com/arviz-devs/arviz/llms.txt Shows how ArviZ raises a `MigrationWarning` when legacy `InferenceData` is accessed, directing users to the migration guide and returning `xarray.DataTree`. ```python import arviz as az import warnings # Accessing legacy InferenceData triggers a warning and returns DataTree with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") from arviz import InferenceData assert issubclass(w[0].category, az.MigrationWarning) assert "migration_guide" in str(w[0].message) # InferenceData is now DataTree from xarray import DataTree assert InferenceData is DataTree # Migration guide: https://python.arviz.org/en/latest/user_guide/migration_guide.html ``` -------------------------------- ### Load Inference Data from NetCDF or Zarr Source: https://context7.com/arviz-devs/arviz/llms.txt Use `az.from_netcdf` to load data from NetCDF files and `az.from_zarr` for Zarr stores. These functions are compatible with ArviZ's `InferenceData` objects and can also load data saved from legacy formats. The example demonstrates saving and reloading data for a round-trip check. ```python import arviz as az # Load a NetCDF file (engine auto-detected or explicit) dt = az.from_netcdf("inference_results.nc") dt = az.from_netcdf("inference_results.nc", engine="h5netcdf") # Load a Zarr store dt = az.from_zarr("inference_results.zarr") # Save and reload round-trip example dt = az.load_arviz_data("centered_eight") dt.to_netcdf("example.nc", engine="h5netcdf") dt_reloaded = az.from_netcdf("example.nc") print(dt_reloaded.groups) # ('/', '/posterior', '/posterior_predictive', '/log_likelihood', # '/sample_stats', '/prior', '/prior_predictive', '/observed_data', '/constant_data') # Access a specific group as DataTree or Dataset posterior_dt = dt_reloaded["posterior"] # DataTree posterior_ds = dt_reloaded["posterior"].dataset # Dataset (view) theta = dt_reloaded["posterior"]["theta"] # DataArray (unchanged) ``` -------------------------------- ### Compute R-hat Convergence Diagnostic Source: https://context7.com/arviz-devs/arviz/llms.txt Compute the rank-normalized R-hat statistic using `az.rhat`. Values near 1.0 suggest chain convergence, while values above 1.01–1.05 indicate potential mixing issues. The example shows how to check for problematic variables. ```python import arviz as az dt = az.load_arviz_data("centered_eight") rhat_result = az.rhat(dt) print(rhat_result) # # Group: /posterior # Data variables: # mu float64 1.001 # theta (school) float64 1.002 1.000 ... 1.001 1.001 # tau float64 1.003 # Check for problematic variables (rhat > 1.01) import xarray as xr rhat_ds = rhat_result["posterior"].dataset problematic = { var: float(rhat_ds[var].max()) for var in rhat_ds if float(rhat_ds[var].max()) > 1.01 } print(problematic) # e.g. {'tau': 1.025} ``` -------------------------------- ### Atomic Plot Function Example Source: https://github.com/arviz-devs/arviz/wiki/Plot-hierarchy Demonstrates the signature and common input parameters for atomic plot functions, which operate on a single axis. These functions typically accept data arrays, sources, axes, labels, and keyword arguments for plot customization. ```python *arr: one or two {ndarray, str} source: {xarray.Dataset, pandas.DataFrame,bokeh.ColumnDataSource}; optional ax: {matplotlib.axis, bokeh.figure}; optional labels: one or two {str, bokeh.Text} line_kwargs: {dict}; optional line properties fill_kwargs: {dict}; optional area properties special_kwargs: {dict}; optional special plot specific properties backend: {"matplotlib","bokeh"} ``` -------------------------------- ### Build and View ArviZ Docs Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/sphinx_doc_build.md Use these commands to build the documentation with Sphinx and then view it in a browser. Re-run the build command after making changes. ```bash tox -e docs # build docs with sphinx tox -e viewdocs # view docs in browser ``` -------------------------------- ### Build Documentation with Tox Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_checklist.md Use this command to build the project's documentation after incorporating your changes. This ensures that the documentation is up-to-date and correctly formatted. ```shell tox -e docs ``` -------------------------------- ### Live Preview of ArviZ Docs Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/sphinx_doc_build.md Enable a live preview of the documentation that automatically updates when changes are saved. This avoids the need to manually rebuild after every modification. ```bash tox -e livedocs ``` -------------------------------- ### Get Default Summary - ArviZ Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/label_guide.rst Generates a summary of the inference data with its default dimension order. ```python az.summary(experiments) ``` -------------------------------- ### Reduce Dimensions with `hdi` Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/migration_guide.ipynb Use `dim` to specify dimensions to reduce. This example reduces 'school' and 'draw' dimensions using the `hdi` function. ```python dt.azstats.hdi(dim=["school", "draw"]) ``` -------------------------------- ### Load data and display summary Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/label_guide.rst Loads the 'centered_eight' dataset and displays a summary using default labeling. ```python import arviz as az schools = az.load_arviz_data("centered_eight") az.summary(schools) ``` -------------------------------- ### List Available Tox Commands Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_tutorial.md List the available development tasks managed by tox for the ArviZ repository. ```bash tox list -m dev ``` -------------------------------- ### Accessing Groups in InferenceData Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/migration_guide.ipynb Access the groups attribute of a DataTree object to get a list of Unix directory paths representing the groups. This is an alternative to the old InferenceData.groups. ```python dt.groups ``` -------------------------------- ### Accessing Sample Stats Prior with PyStan Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/schema/PyStan_schema_example.ipynb Access the sample statistics from the prior distribution. This is useful for understanding the prior's behavior. ```python idata_stan.sample_stats_prior ``` -------------------------------- ### Clean and Rebuild ArviZ Docs Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/sphinx_doc_build.md Execute this command to clean all cache and intermediate files, forcing a complete rebuild of the documentation from scratch. This is useful when changes are not reflected correctly by standard build commands. ```bash tox -e cleandocs ``` -------------------------------- ### Check Code Style with Tox Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_checklist.md Run this command to ensure your code adheres to the project's style guidelines. It's a crucial step before submitting your pull request. ```shell tox -e check ``` -------------------------------- ### Stage and Commit Changes Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_tutorial.md Stage your modified files and commit them with a descriptive message to record your changes locally. ```bash git add modified_files git commit -m "commit message here" ``` -------------------------------- ### Compute Credible Intervals (HDI/ETI) Source: https://context7.com/arviz-devs/arviz/llms.txt Compute Highest Density Intervals (HDI) or Equal-Tailed Intervals (ETI) for posterior variables using `az.hdi` or `az.eti`. These functions reduce over specified dimensions and support arbitrary variable subsets. The example shows HDI calculation with a specified probability. ```python import arviz as az dt = az.load_arviz_data("centered_eight") # HDI over chain and draw (default ci_prob=0.89) hdi_result = az.hdi(dt, hdi_prob=0.94) print(hdi_result["posterior"].dataset) # # Dimensions: (ci_bound: 2, school: 8) ``` -------------------------------- ### Sample from Prior Distribution in PyStan Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/schema/PyStan_schema_example.ipynb Samples from the defined prior distribution using PyStan's `sampling` method with `Fixed_param` algorithm for prior predictive checks. ```python linreg_prior_data_dict = {"N": N, "time_since_joined": time_since_joined} prior = sm_prior.sampling( data=linreg_prior_data_dict, iter=150, chains=1, algorithm="Fixed_param", warmup=0 ) ``` -------------------------------- ### Compute PSIS-LOO-CV with az.loo Source: https://context7.com/arviz-devs/arviz/llms.txt Calculate the Pareto-smoothed importance sampling leave-one-out cross-validation (PSIS-LOO-CV) estimate of predictive performance using az.loo. This function returns an ELPDData object containing LOO estimates, standard errors, and Pareto-k diagnostics. Use `pointwise=True` to get pointwise estimates. ```python import arviz as az dt = az.load_arviz_data("centered_eight") loo_result = az.loo(dt, pointwise=True) print(loo_result) ``` ```python # Check Pareto-k diagnostic (values < 0.7 are good) print(loo_result.pareto_k) ``` ```python # LOO with R2 metric loo_r2 = az.loo_r2(dt) ``` -------------------------------- ### Subset and Summarize with IdxLabeller - ArviZ Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/label_guide.rst Generate a summary of a subsetted inference data object using `IdxLabeller`. Ensure positional indexes are used on the corresponding subset for accurate results. ```python az.summary(schools.isel(school=[2, 5, 7]), labeller=azl.IdxLabeller()) ``` -------------------------------- ### Compute Monte Carlo Standard Error (MCSE) Source: https://context7.com/arviz-devs/arviz/llms.txt Calculate the Monte Carlo Standard Error (MCSE) for posterior mean and quantile estimates using `az.mcse`. MCSE measures the precision of MCMC estimates and is used with ESS to assess sampling quality. The example shows calculation for means and specific quantiles. ```python import arviz as az dt = az.load_arviz_data("centered_eight") mcse_result = az.mcse(dt) print(mcse_result["posterior"].dataset) # MCSE for specific quantiles mcse_quantile = az.mcse(dt, method="quantile", prob=0.05) ``` -------------------------------- ### Add Upstream Remote (SSH/HTTPS) Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_tutorial.md Add the base ArviZ repository as a remote named 'upstream' to your local clone, using either SSH or HTTPS. ```bash cd git remote add upstream git@github.com:arviz-devs/.git ``` ```bash cd git remote add upstream https://github.com/arviz-devs/.git ``` -------------------------------- ### Import ArviZ Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/migration_guide.ipynb Imports the ArviZ library under the conventional alias 'az'. ```python import arviz as az ``` -------------------------------- ### Sample from Posterior Distribution in PyStan Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/schema/PyStan_schema_example.ipynb Samples from the posterior distribution of the linear regression model using PyStan's `sampling` method with specified data and MCMC parameters. ```python linreg_data_dict = { "N": N, "slack_comments": slack_comments, "github_commits": github_commits, "time_since_joined": time_since_joined, "N_pred": N_pred, "time_since_joined_pred": candidate_devs_time, } posterior = sm.sampling(data=linreg_data_dict, iter=200, chains=4) ``` -------------------------------- ### Access Sample Stats Data in PyStan Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/schema/PyStan_schema_example.ipynb Retrieve the sample statistics dataset from a PyStan InferenceData object. This includes metrics like acceptance statistics, step size, and tree depth. ```python idata_stan.sample_stats ``` -------------------------------- ### Import Libraries for PyStan and ArviZ Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/schema/PyStan_schema_example.ipynb Imports necessary libraries for data manipulation and ArviZ visualization. Sets display style for xarray. ```python import arviz as az import pystan import pandas as pd import numpy as np import xarray xarray.set_options(display_style="html"); ``` -------------------------------- ### Sync Local Repository with Upstream Main Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_tutorial.md Sync your local main branch with the upstream repository's main branch before creating a new feature branch. ```bash git checkout main git fetch upstream git rebase upstream/main ``` -------------------------------- ### Accessing Prior Predictive Samples with PyStan Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/schema/PyStan_schema_example.ipynb Retrieve prior predictive samples generated using PyStan. These samples represent data generated from the prior distributions. ```python idata_stan.prior_predictive ``` -------------------------------- ### Use IdxLabeller for Positional Indexes - ArviZ Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/label_guide.rst Utilize `IdxLabeller` to display positional indexes instead of coordinate values in the summary. This is helpful for understanding data structure. ```python az.summary(schools, labeller=azl.IdxLabeller()) ``` -------------------------------- ### Configuring Sample Dimensions for Data Conversion Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/migration_guide.ipynb Set the 'data.sample-dims' rcParam to 'sample' to automatically handle data without a chain dimension during conversion. This avoids the need for manual dimension addition. ```python az.rcParams["data.sample_dims"] = "sample" ``` -------------------------------- ### Sync and Push Changes Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_tutorial.md Sync your local branch with upstream changes and then push your feature branch to your GitHub fork. ```bash git fetch upstream git rebase upstream/main git push -u origin my-feature ``` -------------------------------- ### Model Comparison Visualization Source: https://context7.com/arviz-devs/arviz/llms.txt Visualizes the output of `az.compare()` as a dot plot with error bars. This facilitates ranking models and assessing the significance of differences between them. ```python import arviz as az dt_c = az.load_arviz_data("centered_eight") dt_nc = az.load_arviz_data("non_centered_eight") comparison = az.compare({"centered": dt_c, "non_centered": dt_nc}) az.plot_compare(comparison) ``` -------------------------------- ### Clone ArviZ Fork (SSH/HTTPS) Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_tutorial.md Clone your forked ArviZ repository to your local machine using either SSH or HTTPS. ```bash git clone git@github.com:/.git ``` ```bash git clone https://github.com//.git ``` -------------------------------- ### Import Libraries for PyMC3 and ArviZ Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/schema/PyMC3_schema_example.ipynb Imports necessary libraries including ArviZ, PyMC3, pandas, numpy, and xarray. Sets xarray display style to HTML for better rendering. ```python import arviz as az import pymc3 as pm import pandas as pd import numpy as np import xarray xarray.set_options(display_style="html"); ``` -------------------------------- ### az.from_netcdf and az.from_zarr Source: https://context7.com/arviz-devs/arviz/llms.txt Load inference data from NetCDF or Zarr formats. `az.from_netcdf` is an alias for `xarray.open_datatree`, and `az.from_zarr` is a pre-configured partial for Zarr files. ```APIDOC ## `az.from_netcdf` / `az.from_zarr` — Load saved inference results `az.from_netcdf` is an alias for `xarray.open_datatree`; `az.from_zarr` is a pre-configured partial that sets `engine="zarr"`. Both load existing inference data files saved in NetCDF or Zarr formats, including files originally saved from legacy `arviz.InferenceData` objects. ```python import arviz as az # Load a NetCDF file (engine auto-detected or explicit) dt = az.from_netcdf("inference_results.nc") dt = az.from_netcdf("inference_results.nc", engine="h5netcdf") # Load a Zarr store dt = az.from_zarr("inference_results.zarr") # Save and reload round-trip example dt = az.load_arviz_data("centered_eight") dt.to_netcdf("example.nc", engine="h5netcdf") dt_reloaded = az.from_netcdf("example.nc") print(dt_reloaded.groups) # ('/', '/posterior', '/posterior_predictive', '/log_likelihood', # '/sample_stats', '/prior', '/prior_predictive', '/observed_data', '/constant_data') # Access a specific group as DataTree or Dataset posterior_dt = dt_reloaded["posterior"] # DataTree posterior_ds = dt_reloaded["posterior"].dataset # Dataset (view) theta = dt_reloaded["posterior"]["theta"] # DataArray (unchanged) ``` ``` -------------------------------- ### Execute Tox Development Tasks Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_tutorial.md Run specific tox environments for tasks like testing or code style checks. ```bash tox -e test-namespace tox -e check ``` -------------------------------- ### Resetting computational backend to 'base' Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/migration_guide.ipynb Resets the computational backend for ArviZ statistics functions to 'base' by setting `az.rcParams["stats.module"]`. ```python az.rcParams["stats.module"] = "base" ``` -------------------------------- ### Access Sample Statistics Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/schema/PyMC3_schema_example.ipynb Retrieves and displays the sampling statistics, such as energy, step size, and divergence information, from the InferenceData object. ```python idata_pymc3.sample_stats ``` -------------------------------- ### Create Feature Branch Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_tutorial.md Create a new branch for your development work. Always create a feature branch before making changes. ```bash git checkout -b my-feature ``` -------------------------------- ### DataTree Group Navigation and Transformation Source: https://context7.com/arviz-devs/arviz/llms.txt Demonstrates how to navigate, filter, and transform ArviZ data structures using xarray's DataTree. Supports accessing groups as DataTrees, Datasets, or DataArrays. ```python import arviz as az dt = az.load_arviz_data("centered_eight") # Check available groups print(list(dt.children)) # ['posterior', 'posterior_predictive', 'log_likelihood', ...] # Access a group as DataTree, Dataset, or DataArray post_dt = dt["posterior"] # DataTree post_ds = dt["posterior"].dataset # Dataset (view) theta = dt["posterior"]["theta"] # DataArray # Apply a function to selected groups (replaces idata.map) shifted = dt.copy() shifted.update( dt.match("*_predictive").map_over_datasets(lambda ds: ds + 3) ) # Filter to specific groups subset = dt.filter( lambda node: node.name in ("posterior", "observed_data") ) # Merge two DataTrees (replaces idata.extend) dt_new = az.from_dict({"prior": {"alpha": [0.1, 0.2, 0.3]}}) dt.update(dt_new) # left-merge: dt groups take priority # Select specific coordinates dt.sel(school=["Choate", "Deerfield"]) ``` -------------------------------- ### Set ArviZ Style and Plot with Matplotlib Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/migration_guide.ipynb Applies a global ArviZ style and then generates a rank plot using the matplotlib backend. Ensure ArviZ data is loaded before plotting. ```python az.style.use("arviz-vibrant") dt = az.load_arviz_data("centered_eight") az.plot_rank(dt, var_names=["mu", "tau"], backend="matplotlib"); ``` -------------------------------- ### Troubleshoot ArviZ Import Errors Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/getting_started.md If you encounter import errors, configure logging to INFO level and re-import ArviZ. This can help in diagnosing issues by showing detailed import messages. ```python import logging logging.basicConfig(level=logging.INFO) import arviz as az ``` -------------------------------- ### General Intersphinx Reference Syntax in rST Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/syntax_guide.md Shows the general syntax for creating intersphinx links in reStructuredText, including the optional intersphinx key. ```rst :type_id:`(intersphinx_key:)object_id` ``` -------------------------------- ### Replicate inplace behavior with update Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/migration_guide.ipynb To replicate the `inplace=True` behavior of the old `.map` method, create a copy of the DataTree, apply the transformation to the desired groups using `match` and `map_over_datasets`, and then update the original DataTree with the modified groups using `.update`. ```python shifted_dt = dt.copy() shifted_dt.update(dt.match("*_predictive").map_over_datasets(lambda ds: ds + 3)) ``` -------------------------------- ### Generating Random Data for Conversion Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/user_guide/migration_guide.ipynb Generate random data using numpy's random number generator. This data will be used to demonstrate ArviZ's enhanced converter flexibility. ```python import numpy as np rng = np.random.default_rng() data = rng.normal(size=1000) ``` -------------------------------- ### Update Version String for Development Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/how_to_release.md After a release, update the version string to include the development flag (e.g., `.dev0`) to indicate ongoing development. This follows PEP 440 compliance. ```text 0.13.0.dev0 ``` -------------------------------- ### General Intersphinx Reference Syntax in MyST Markdown Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/syntax_guide.md Shows the general syntax for creating intersphinx links in MyST Markdown, including the optional intersphinx key. ```markdown {type_id}`(intersphinx_key:)object_id` ``` -------------------------------- ### Run Tests for Python 3.12 Environment Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/pr_checklist.md Execute all tests for the Python 3.12 environment using tox. Replace 'py312' with your target Python version if needed (e.g., 'py311', 'py313'). ```shell tox -e py312 ``` -------------------------------- ### Link to Matplotlib Docs in rST Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/contributing/syntax_guide.md Demonstrates how to create a link to Matplotlib's Axes.plot documentation using a specific intersphinx key in reStructuredText. ```rst :meth:`mpl:matplotlib.axes.Axes.plot` ``` -------------------------------- ### Access Prior Data in PyStan Source: https://github.com/arviz-devs/arviz/blob/main/docs/source/schema/PyStan_schema_example.ipynb Retrieve the prior distributions defined for the PyStan model parameters. This dataset shows the initial beliefs about the parameters before observing data. ```python idata_stan.prior ```