Load model and data files
Load the coin model and example data available within treepplr.
The data in this example is a sequence of coin flip results. treeppl can only read data in JSON format, that’s why all example data are in this format.
str(data)
#> List of 1
#> $ coinflips: logi [1:20] FALSE TRUE TRUE TRUE FALSE TRUE ...
#> - attr(*, "class")= chr "json"
Run TreePPL
Now we can compile and run the TreePPL program. The function tp_treeppl() has many optional arguments to change the inference method used. Here, we will use the default settings and only pass the model and the data.
output_list <- tp_treeppl(model = model, data = data)
Plot the posterior distribution
TreePPL outputs the log weight of each sample, so first we need to get the normalized weights and then we can plot the posterior distribution produced.
# turn list into a data frame where each row represents one sample
# and calculate normalized weights from log weights
output <- tp_parse(output_list) %>%
dplyr::mutate(weight = exp(log_weight - max(.$log_weight)))
ggplot2::ggplot(output) +
ggplot2::geom_histogram(aes(samples, y = after_stat(density), weight=weight), col = "white", fill = "lightblue") +
ggplot2::geom_density(aes(samples, weight=weight)) +
ggplot2::theme_bw()