Exploratory analysis of Bayesian models with comprehensive data manipulation, statistical diagnostics, and visualization capabilities
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Global and context-specific configuration management for ArviZ behavior including plotting backends, statistical defaults, and data handling preferences.
rcParams: RcParams
"""
Global configuration parameters object for ArviZ settings.
Categories:
data.*: Data handling preferences
plot.*: Plotting backend and style settings
stats.*: Statistical computation defaults
Access pattern: az.rcParams['category.parameter'] = value
"""class rc_context:
"""
Context manager for temporary configuration changes.
Allows temporary modification of ArviZ settings within a specific scope,
automatically restoring previous values when exiting the context.
"""
def __init__(self, rc: dict = None, fname: str = None):
"""
Initialize context manager for temporary settings.
Args:
rc (dict, optional): Dictionary of parameter -> value mappings
fname (str, optional): Path to rcParams configuration file
"""
def __enter__(self):
"""Enter context with modified settings."""
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exit context and restore original settings."""# Data handling preferences
az.rcParams["data.load"] = "lazy" # "lazy" or "eager" data loading
az.rcParams["data.save_warmup"] = False # Whether to save warmup samples
az.rcParams["data.log_likelihood"] = True # Include log likelihood by default# Backend configuration
az.rcParams["plot.backend"] = "matplotlib" # "matplotlib", "bokeh", "plotly"
az.rcParams["plot.max_subplots"] = 40 # Maximum subplots per figure
az.rcParams["plot.point_estimate"] = "mean" # "mean", "median", "mode"
# Style preferences
az.rcParams["plot.density_kind"] = "kde" # "kde" or "hist"
az.rcParams["plot.theme"] = "default" # Plot theme# Statistical computation defaults
az.rcParams["stats.hdi_prob"] = 0.94 # Default HDI probability
az.rcParams["stats.information_criterion"] = "loo" # "loo" or "waic"
az.rcParams["stats.ic_scale"] = "log" # "log", "negative_log", "deviance"import arviz as az
# View current settings
print(az.rcParams["plot.backend"])
print(az.rcParams["stats.hdi_prob"])
# Modify global settings
az.rcParams["plot.backend"] = "bokeh"
az.rcParams["stats.hdi_prob"] = 0.89
# Settings persist for the session
az.plot_posterior(idata) # Uses Bokeh backend
az.summary(idata) # Uses 89% HDI# Temporary backend change
with az.rc_context({"plot.backend": "plotly"}):
az.plot_trace(idata) # Uses Plotly backend
az.plot_posterior(idata)
# Automatically reverts to previous backend
# Multiple temporary settings
temp_settings = {
"plot.backend": "bokeh",
"stats.hdi_prob": 0.89,
"plot.point_estimate": "median"
}
with az.rc_context(temp_settings):
summary = az.summary(idata) # Uses 89% HDI with median estimates
az.plot_forest(idata) # Uses Bokeh backend
# All settings revert automatically# Load settings from configuration file
with az.rc_context(fname="my_arviz_config.json"):
az.plot_posterior(idata)
results = az.compare(model_dict)# Set publication-quality defaults
publication_settings = {
"plot.backend": "matplotlib",
"plot.point_estimate": "mean",
"plot.density_kind": "kde",
"stats.hdi_prob": 0.95,
"plot.max_subplots": 20
}
# Apply settings globally
for key, value in publication_settings.items():
az.rcParams[key] = value
# Or use as context
with az.rc_context(publication_settings):
# Generate publication plots
az.plot_posterior(idata, hdi_prob=0.95)
az.plot_forest(idata)# Interactive plotting setup
interactive_config = {
"plot.backend": "bokeh",
"plot.max_subplots": 25
}
# Static plotting setup
static_config = {
"plot.backend": "matplotlib",
"plot.max_subplots": 40
}
# Switch between modes
with az.rc_context(interactive_config):
az.plot_pair(idata) # Interactive plot
with az.rc_context(static_config):
az.plot_trace(idata) # Static plot# Settings for large datasets
performance_config = {
"data.load": "lazy",
"plot.max_subplots": 20,
"stats.information_criterion": "waic" # Faster than LOO for large data
}
with az.rc_context(performance_config):
# Process large inference data efficiently
summary = az.summary(large_idata)
comparison = az.compare(large_model_dict)ArviZ supports JSON configuration files:
{
"data.load": "lazy",
"data.save_warmup": false,
"plot.backend": "matplotlib",
"plot.point_estimate": "mean",
"plot.density_kind": "kde",
"stats.hdi_prob": 0.94,
"stats.information_criterion": "loo"
}# Data parameters
"data.load" # "lazy" or "eager"
"data.save_warmup" # True or False
"data.log_likelihood" # True or False
# Plot parameters
"plot.backend" # "matplotlib", "bokeh", "plotly"
"plot.max_subplots" # Integer (default 40)
"plot.point_estimate" # "mean", "median", "mode"
"plot.density_kind" # "kde" or "hist"
"plot.theme" # "default", "arviz-white", etc.
# Stats parameters
"stats.hdi_prob" # Float between 0 and 1 (default 0.94)
"stats.information_criterion" # "loo" or "waic"
"stats.ic_scale" # "log", "negative_log", "deviance"# Valid values are enforced
try:
az.rcParams["plot.backend"] = "invalid_backend"
except ValueError as e:
print(f"Invalid backend: {e}")
try:
az.rcParams["stats.hdi_prob"] = 1.5 # Must be between 0 and 1
except ValueError as e:
print(f"Invalid HDI probability: {e}")# Save current settings at start of analysis
original_settings = {
"plot.backend": az.rcParams["plot.backend"],
"stats.hdi_prob": az.rcParams["stats.hdi_prob"]
}
# Modify as needed during analysis
az.rcParams["plot.backend"] = "bokeh"
# Restore at end if needed
for key, value in original_settings.items():
az.rcParams[key] = value# Create project-specific configuration function
def setup_project_config():
"""Configure ArviZ for this specific project."""
config = {
"plot.backend": "matplotlib",
"stats.hdi_prob": 0.89,
"plot.point_estimate": "median",
"data.save_warmup": False
}
for key, value in config.items():
az.rcParams[key] = value
# Use at start of analysis
setup_project_config()def diagnostic_plots(idata):
"""Generate diagnostic plots with appropriate settings."""
diag_config = {
"plot.backend": "matplotlib", # Better for diagnostic plots
"plot.max_subplots": 50
}
with az.rc_context(diag_config):
az.plot_trace(idata)
az.plot_rank(idata)
az.plot_ess(idata)
def presentation_plots(idata):
"""Generate presentation plots with interactive backend."""
pres_config = {
"plot.backend": "bokeh", # Interactive for presentations
"plot.point_estimate": "mean",
"stats.hdi_prob": 0.95
}
with az.rc_context(pres_config):
az.plot_posterior(idata)
az.plot_forest(idata)__version__: str
"""
ArviZ version string.
Provides the current version of the ArviZ library installation.
Useful for debugging, compatibility checks, and version reporting.
Example: "0.22.0"
"""import arviz as az
# Check ArviZ version
print(f"ArviZ version: {az.__version__}")
# Version-specific compatibility
from packaging import version
if version.parse(az.__version__) >= version.parse("0.20.0"):
# Use newer features
az.plot_forest(idata, combined=True)
else:
# Use legacy syntax
az.plot_forest(idata)
# Include version in analysis reports
def analysis_info():
"""Print analysis environment information."""
import sys
import numpy as np
import xarray as xr
print(f"Python: {sys.version}")
print(f"ArviZ: {az.__version__}")
print(f"NumPy: {np.__version__}")
print(f"Xarray: {xr.__version__}")
analysis_info()Install with Tessl CLI
npx tessl i tessl/pypi-arviz