API Reference

ArviZ.InferenceDataType
InferenceData(::PyObject)
InferenceData(; kwargs...)

Loose wrapper around arviz.InferenceData, which is a container for inference data storage using xarray.

InferenceData can be constructed either from an arviz.InferenceData or from multiple Datasets assigned to groups specified as kwargs.

Instead of directly creating an InferenceData, use the exported from_xyz functions or convert_to_inference_data.

source
ArviZ.concat!Method
concat!(data1::InferenceData, data::InferenceData...; kwargs...) -> InferenceData

In-place version of concat, where data1 is modified to contain the concatenation of data and args. See concat for a description of kwargs.

source
ArviZ.convert_to_inference_dataMethod
convert_to_inference_data(::AbstractParticles; kwargs...) -> InferenceData
convert_to_inference_data(
    ::AbstractArray{<:AbstractParticles};
    kwargs...,
) -> InferenceData

Convert a single- or multi-dimensional MonteCarloMeasurements.AbstractParticles to an InferenceData.

source
ArviZ.convert_to_inference_dataMethod
convert_to_inference_data(obj::NamedTuple; kwargs...) -> InferenceData
convert_to_inference_data(obj::Vector{<:NamedTuple}; kwargs...) -> InferenceData
convert_to_inference_data(obj::Matrix{<:NamedTuple}; kwargs...) -> InferenceData
convert_to_inference_data(obj::Vector{Vector{<:NamedTuple}}; kwargs...) -> InferenceData

Convert obj to an InferenceData. See from_namedtuple for a description of obj possibilities and kwargs.

source
ArviZ.from_mcmcchainsMethod
from_mcmcchains(posterior::AbstractChains; kwargs...) -> InferenceData
from_mcmcchains(; kwargs...) -> InferenceData
from_mcmcchains(
    posterior::AbstractChains,
    posterior_predictive::Any,
    log_likelihood::String;
    kwargs...
) -> InferenceData

Convert data in an MCMCChains.AbstractChains format into an InferenceData.

Any keyword argument below without an an explicitly annotated type above is allowed, so long as it can be passed to convert_to_inference_data.

Arguments

  • posterior::AbstractChains: Draws from the posterior

Keywords

  • posterior_predictive::Any=nothing: Draws from the posterior predictive distribution or name(s) of predictive variables in posterior
  • prior::Any=nothing: Draws from the prior
  • prior_predictive::Any=nothing: Draws from the prior predictive distribution or name(s) of predictive variables in prior
  • observed_data::Dict{String,Array}=nothing: Observed data on which the posterior is conditional. It should only contain data which is modeled as a random variable. Keys are parameter names and values.
  • constant_data::Dict{String,Array}=nothing: Model constants, data included in the model which is not modeled as a random variable. Keys are parameter names and values.
  • log_likelihood::String=nothing: Name of variable in posterior with log likelihoods
  • library=MCMCChains: Name of library that generated the chains
  • coords::Dict{String,Vector}=nothing: Map from named dimension to named indices
  • dims::Dict{String,Vector{String}}=nothing: Map from variable name to names of its dimensions

Returns

  • InferenceData: The data with groups corresponding to the provided data
source
ArviZ.from_namedtupleFunction
from_namedtuple(posterior::NamedTuple; kwargs...) -> InferenceData
from_namedtuple(posterior::Vector{<:NamedTuple}; kwargs...) -> InferenceData
from_namedtuple(posterior::Matrix{<:NamedTuple}; kwargs...) -> InferenceData
from_namedtuple(posterior::Vector{Vector{<:NamedTuple}}; kwargs...) -> InferenceData

Convert a NamedTuple or container of NamedTuples to an InferenceData.

If containers are passed, they are flattened into a single NamedTuple with array elements whose first dimensions correspond to the dimensions of the containers.

Arguments

  • posterior: The data to be converted. It may be of the following types:
    • ::NamedTuple: The keys are the variable names and the values are arrays with dimensions (nchains, ndraws, sizes...).
    • ::Vector{<:NamedTuple}: Each element is a NamedTuple from a chain with array values with dimensions (ndraws, sizes...).
    • ::Matrix{<:NamedTuple}: Each element is a single draw from a single chain, with array/scalar values with dimensions sizes. The dimensions of the matrix container are (nchains, ndraws)
    • ::Vector{Vector{<:NamedTuple}}: The same as the above case.

Keywords

  • posterior_predictive::Any=nothing: Draws from the posterior predictive distribution
  • sample_stats::Any=nothing: Statistics of the posterior sampling process
  • prior::Any=nothing: Draws from the prior
  • prior_predictive::Any=nothing: Draws from the prior predictive distribution
  • sample_stats_prior::Any=nothing: Statistics of the prior sampling process
  • observed_data::Dict{String,Array}=nothing: Observed data on which the posterior is conditional. It should only contain data which is modeled as a random variable. Keys are parameter names and values.
  • constant_data::Dict{String,Array}=nothing: Model constants, data included in the model which is not modeled as a random variable. Keys are parameter names and values.
  • library=nothing: Name of library that generated the draws
  • coords::Dict{String,Vector}=nothing: Map from named dimension to named indices
  • dims::Dict{String,Vector{String}}=nothing: Map from variable name to names of its dimensions

Returns

  • InferenceData: The data with groups corresponding to the provided data

Examples

using ArviZ
nchains, ndraws = 2, 10

data1 = (
    x = rand(nchains, ndraws),
    y = randn(nchains, ndraws, 2),
    z = randn(nchains, ndraws, 3, 2),
)
idata1 = from_namedtuple(data1)

data2 = [(x = rand(ndraws), y = randn(ndraws, 2), z = randn(ndraws, 3, 2)) for _ = 1:nchains];
idata2 = from_namedtuple(data2)

data3 = [(x = rand(), y = randn(2), z = randn(3, 2)) for _ = 1:nchains, _ = 1:ndraws];
idata3 = from_namedtuple(data3)

data4 = [[(x = rand(), y = randn(2), z = randn(3, 2)) for _ = 1:ndraws] for _ = 1:nchains];
idata4 = from_namedtuple(data4)
source
ArviZ.with_interactive_backendMethod
with_interactive_backend(f; backend::Symbol = nothing)

Execute the thunk f in a temporary interactive context with the chosen backend, or provide no arguments to use a default.

Example

idata = load_arviz_data("centered_eight")
plot_posterior(idata) # inline
with_interactive_backend() do
    plot_density(idata) # interactive
end
plot_trace(idata) # inline
source
ArviZ.with_rc_contextMethod
with_rc_context(f; rc = nothing, fname = nothing)

Execute the thunk f within a context controlled by rc params. To see supported params, execute rc_params().

This allows one to do:

with_rc_context(fname = "pystan.rc") do
    idata = load_arviz_data("radon")
    plot_posterior(idata; var_names=["gamma"])
end

The plot would have settings from pystan.rc.

A dictionary can also be passed to the context manager:

with_rc_context(rc = Dict("plot.max_subplots" => 1), fname = "pystan.rc") do
    idata = load_arviz_data("radon")
    plot_posterior(idata, var_names=["gamma"])
end

The rc dictionary takes precedence over the settings loaded from fname. Passing a dictionary only is also valid.

source
StatsBase.summarystatsMethod
summarystats(data::Dataset; kwargs...) -> Union{Pandas.DataFrame,Dataset}
summarystats(data::InferenceData; group = :posterior kwargs...) -> Union{Pandas.DataFrame,Dataset}

Compute summary statistics on data.

Arguments

  • data::Union{Dataset,InferenceData}: The data on which to compute summary statistics. If data is an InferenceData, only the dataset corresponding to group is used.

Keywords

  • var_names::Vector{String}=nothing: Names of variables to include in summary
  • include_circ::Bool=false: Whether to include circular statistics
  • fmt::String="wide": Return format is either Pandas.DataFrame ("wide", "long") or Dataset ("xarray").
  • round_to::Int=nothing: Number of decimals used to round results. Use nothing to return raw numbers.
  • stat_funcs::Union{Dict{String,Function},Vector{Function}}=nothing: A vector of functions or a dict of functions with function names as keys used to calculate statistics. By default, the mean, standard deviation, simulation standard error, and highest posterior density intervals are included. The functions will be given one argument, the samples for a variable as an array, The functions should operate on an array, returning a single number. For example, Statistics.mean, or Statistics.var would both work.
  • extend::Bool=true: If true, use the statistics returned by stat_funcs in addition to, rather than in place of, the default statistics. This is only meaningful when stat_funcs is not nothing.
  • credible_interval::Real=0.94: Credible interval to plot. This is only meaningful when stat_funcs is nothing.
  • order::String="C": If fmt is "wide", use either "C" or "F" unpacking order.
  • index_origin::Int=1: If fmt is "wide", select 𝑛-based indexing for multivariate parameters.

Returns

  • Union{Pandas.DataFrame,Dataset}: Return type dicated by fmt argument. Return value will contain summary statistics for each variable. Default statistics are:
    • mean
    • sd
    • hpd_3%
    • hpd_97%
    • mcse_mean
    • mcse_sd
    • ess_bulk
    • ess_tail
    • r_hat (only computed for traces with 2 or more chains)

Examples

using ArviZ
idata = load_arviz_data("centered_eight")
summarystats(idata; var_names=["mu", "tau"])

Other statistics can be calculated by passing a list of functions or a dictionary with key, function pairs:

using StatsBase, Statistics
function median_sd(x)
    med = median(x)
    sd = sqrt(mean((x .- med).^2))
    return sd
end

func_dict = Dict(
    "std" => x -> std(x; corrected = false),
    "median_std" => median_sd,
    "5%" => x -> percentile(x, 5),
    "median" => median,
    "95%" => x -> percentile(x, 95),
)

summarystats(idata; var_names = ["mu", "tau"], stat_funcs = func_dict, extend = false)
source
ArviZ.DatasetType
Dataset(::PyObject)
Dataset(; data_vars = nothing, coords = nothing, attrs = nothing)

Loose wrapper around xarray.Dataset, mostly used for dispatch.

Keywords

  • data_vars::Dict{String,Any}: Dict mapping variable names to
    • Vector: Data vector. Single dimension is named after variable.
    • Tuple{String,Vector}: Dimension name and data vector.
    • Tuple{NTuple{N,String},Array{T,N}} where {N,T}: Dimension names and data array.
  • coords::Dict{String,Any}: Dict mapping dimension names to index names. Possible arguments has same form as data_vars.
  • attrs::Dict{String,Any}: Global attributes to save on this dataset.

In most cases, use convert_to_dataset or convert_to_constant_dataset or to create a Dataset instead of directly using a constructor.

source
ArviZ.convert_to_constant_datasetMethod
convert_to_constant_dataset(obj::Dict; kwargs...) -> Dataset
convert_to_constant_dataset(obj::NamedTuple; kwargs...) -> Dataset

Convert obj into a Dataset. Unlike convert_to_dataset, this is intended for containing constant parameters such as observed data and constant data, and the first two dimensions are not required to be the number of chains and draws.

Keywords

  • coords::Dict{String,Vector}: Map from named dimension to index names
  • dims::Dict{String,Vector{String}}: Map from variable name to names of its dimensions
  • library::Any: A library associated with the data to add to attrs.
  • attrs::Dict{String,Any}: Global attributes to save on this dataset.
source
ArviZ.dataset_to_dictMethod
dataset_to_dict(ds::Dataset) -> Tuple{Dict{String,Array},NamedTuple}

Convert a Dataset to a dictionary of Arrays. The function also returns keyword arguments to dict_to_dataset.

source
ArviZ.dict_to_datasetMethod
dict_to_dataset(data::Dict{String,Array}; kwargs...) -> Dataset

Convert a dictionary with data and keys as variable names to a Dataset.

Keywords

  • attrs::Dict{String,Any}: Json serializable metadata to attach to the dataset, in addition to defaults.
  • library::String: Name of library used for performing inference. Will be attached to the attrs metadata.
  • coords::Dict{String,Array}: Coordinates for the dataset
  • dims::Dict{String,Vector{String}}: Dimensions of each variable. The keys are variable names, values are vectors of coordinates.

Examples

using ArviZ
ArviZ.dict_to_dataset(Dict("x" => randn(4, 100), "y" => randn(4, 100)))
source
ArviZ.groupnamesMethod
groupnames(data::InferenceData) -> Vector{Symbol}

Get the names of the groups (datasets) in data.

source
ArviZ.groupsMethod
groups(data::InferenceData) -> Dict{Symbol,Dataset}

Get the groups in data as a dictionary mapping names to datasets.

source
ArviZ.reshape_valuesMethod
reshape_values(x::AbstractArray) -> AbstractArray

Convert from MCMCChains variable values with dimensions (ndraw, size..., nchain) to ArviZ's expected (nchain, ndraw, size...).

source
ArviZ.stackMethod
stack(x::NamedTuple) -> NamedTuple
stack(x::AbstractArray{NamedTuple}) -> NamedTuple
stack(x::AbstractArray{AbstractArray{<:NamedTuple}}) -> NamedTuple

Given a container of NamedTuples, concatenate them, using the container dimensions as the dimensions of the resulting arrays.

Examples

using ArviZ
nchains, ndraws = 4, 100
data = [(x = rand(), y = randn(2), z = randn(2, 3)) for _ in 1:nchains, _ in 1:ndraws];
stacked_data = ArviZ.stack(data);
source
ArviZ.summaryMethod
summary(
    data;
    group = :posterior,
    coords = nothing,
    dims = nothing,
    kwargs...,
) -> Union{Pandas.DataFrame,PyObject}

Compute summary statistics on any object that can be passed to convert_to_dataset.

Keywords

  • coords::Dict{String,Vector}=nothing: Map from named dimension to named indices.
  • dims::Dict{String,Vector{String}}=nothing: Map from variable name to names of its dimensions.
  • kwargs: Keyword arguments passed to summarystats.
source
ArviZ.use_styleMethod
use_style(style::String)
use_style(style::Vector{String})

Use matplotlib style settings from a style specification style.

The style name of "default" is reserved for reverting back to the default style settings.

ArviZ-specific styles are ["arviz-whitegrid", "arviz-darkgrid", "arviz-colors", "arviz-white"]. To see all available style specifications, use styles().

If a Vector of styles is provided, they are applied from first to last.

source
ArviZ.@forwardfunMacro
@forwardfun f
@forwardfun(f)

Wrap a function arviz.f in f, forwarding its docstrings.

source
ArviZ.@forwardplotfunMacro
@forwardplotfun f
@forwardplotfun(f)

Wrap a plotting function arviz.f in f, forwarding its docstrings.

This macro also ensures that outputs for the different backends are correctly handled.

source