Learn R Programming

⚠️There's a newer version (0.7.8) of this package.Take me there.

dbnR

Introduction

This package offers an implementation of Gaussian dynamic Bayesian networks (GDBN) structure learning and inference based partially on Marco Scutari’s package bnlearn (https://www.bnlearn.com/). It also allows the construction of higher-order DBNs. Three structure learning algorithms are implemented:

Inference is performed either via the particle filtering offered by bnlearn or by doing exact inference over the multivariate Gaussian equivalent of a network implemented in this package. A visualization tool is also implemented for GDBNs and bnlearn’s BNs via the visNetwork package (https://github.com/datastorm-open/visNetwork).

Current development

The main functionality of the package is running and working. In order of importance, the next objectives are:

  • To refractor the DMMHC algorithm into R6 for consistency with the PSOHO algorithm and with any new structure learning algorithms.
  • To add an automatically generated shiny interface of the net. This makes interacting with the network easier and allows for simulation prototypes.

For now, the dbn.fit object as an extension of bnlearn’s bn.fit object will stay the same except for the “mu” and “sigma” attributes added to it. This way, it remains easy to call bnlearn’s methods on the dbn.fit object and I can store the MVN transformation inside the same object. Not an elegant solution, but its simplicity is enough. What should be addressed is having to perform the folding of a dataset outside the predict function.

Getting Started

Prerequisites

This package requires R ≥ 3.6.1 to work properly. It also works for R ≥ 3.5.0, the only difference is the color palette of the DBN visualization tool.

The bnlearn and data.table packages, among others, are required for this package to work. They will be installed automatically when installing this package. They can also be installed manually via CRAN with the command

install.packages(c("bnlearn", "data.table"))

The packages visNetwork, magrittr and grDevices are optional for the visualization tool. They will only be required if you want to use it.

Installing

As of today, the easiest way of installing dbnR is via CRAN. To install it, simply run

install.packages('dbnR')

You can also install the latest version in GitHub with the install_github function in the devtools package. The commands you need to run are

library(devtools)
devtools::install_github("dkesada/dbnR")

This will install the required dependencies if they are not available. After this, you will be ready to use the package.

Basic examples

To get the structure of a GDBN from a dataset, you need to use the function learn_dbn_struc

library(dbnR)
data(motor)

size <- 3
dt_train <- motor[200:2500]
dt_val <- motor[2501:3000]
net <- learn_dbn_struc(dt_train, size)

The dt argument has to be either a data.frame or a data.table of numeric columns, in the example we use the sample dataset included in the package. The size argument determines the number of time slices that your net is going to have, that is, the Markovian order of the net. A Markovian order of 1 means that your data in the present is independent of the past given the previous time slice. If your case doesn’t meet this criteria, the size of the net can be increased, to take into account more past time slices in the inference. In our function, Markovian order = size - 1. The function returns a ‘dbn’ object that inherits from the ‘bn’ class in bnlearn, so that its auxiliary functions like ‘arcs’ and such also work on DBN structures.

Once the structure is learnt, it can be plotted and used to learn the parameters

plot_dynamic_network(net)

f_dt_train <- fold_dt(dt_train, size)
fit <- fit_dbn_params(net, f_dt_train, method = "mle")

After learning the net, two different types of inference can be performed: point-wise inference over a dataset and forecasting to some horizon. Point-wise inference uses the folded dt to try and predict the objective variables in each row. Forecasting to some horizon, on the other hand, tries to predict the behaviour in the future M instants given some initial evidence of the variables.

There is an extensive example of how to use the package in the markdowns folder, which covers more advanced concepts of structure learning and inference.

License

This project is licensed under the GPL-3 License, following on bnlearn’s GPL(≥ 2) license.

References

Applications of dbnR

  • Quesada, D., Valverde, G., Larrañaga, P., & Bielza, C. (2021). Long-term forecasting of multivariate time series in industrial furnaces with dynamic Gaussian Bayesian networks. Engineering Applications of Artificial Intelligence, 103, 104301.

  • Quesada, D., Bielza, C., & Larrañaga, P. (2021, September). Structure Learning of High-Order Dynamic Bayesian Networks via Particle Swarm Optimization with Order Invariant Encoding. In International Conference on Hybrid Artificial Intelligence Systems (pp. 158-171). Springer, Cham.

Copy Link

Version

Install

install.packages('dbnR')

Monthly Downloads

722

Version

0.7.5

License

GPL-3

Issues

Pull Requests

Stars

Forks

Maintainer

David Quesada

Last Published

March 14th, 2022

Functions in dbnR (0.7.5)

Velocity

R6 class that defines velocities affecting causality lists in the PSO
Particle

R6 class that defines a Particle in the PSO algorithm
acc_successions

Returns a vector with the number of consecutive nodes in each level
bn_translate_exp

Experimental function that translates a natPosition vector into a DBN network.
calc_mu

Calculate the mu vector of means of a Gaussian linear network. Front end of a C++ function.
cl_to_arc_matrix_cpp

Create a matrix with the arcs defined in a causlist object
Position

R6 class that defines DBNs as causality lists
calc_mu_cpp

Calculate the mu vector of means of a Gaussian linear network. This is the C++ backend of the function.
calc_sigma_cpp

Calculate the sigma covariance matrix of a Gaussian linear network. This is the C++ backend of the function.
calc_sigma

Calculate the sigma covariance matrix of a Gaussian linear network. Front end of a C++ function.
add_attr_to_fit

Adds the mu vector and sigma matrix as attributes to the bn.fit or dbn.fit object
exact_prediction_step

Performs exact inference in a time slice of the dbn
PsoCtrl

R6 class that defines the PSO controller
create_blacklist

Creates the blacklist of arcs from a folded data.table
approx_prediction_step

Performs approximate inference in a time slice of the dbn
filter_same_cycle

Filter the instances in a data.table that have values of different ids in each row
merge_nets

Merges and replicates the arcs in the static BN into all the time-slices in the DBN
learn_dbn_struc

Learns the structure of a markovian n DBN model from data
natPosition

R6 class that defines DBNs as vectors of natural numbers
nat_cte_times_vel_cpp

Multiply a Velocity by a constant real number
expand_time_nodes

Extends the names of the nodes in t_0 to t_(max-1)
forecast_ts

Performs forecasting with the GDBN over a data set
nat_pos_minus_pos_cpp

Subtracts two natPositions to obtain the natVelocity that transforms ps1 into ps2
nat_cl_to_arc_matrix_cpp

Create a matrix with the arcs defined in a causlist object
fold_dt_rec

Widens the dataset to take into account the t previous time slices
natPsoCtrl

R6 class that defines the PSO controller
check_time0_formatted

Checks if the vector of names are time formatted to t0
crop_names_cpp

If the names of the nodes have "_t_0" appended at the end, remove it
dmmhc

Learns the structure of a markovian n DBN model from data
cte_times_vel_cpp

Multiply a Velocity by a constant real number
generate_random_network_exp

Experimental function that generates a random DBN and samples a dataset that defines it
natCauslist

This file contains all the classes needed for the natPSOHO structure learning algorithm. It was implemented as an independent package in https://github.com/dkesada/natPSOHO and then merged into dbnR. All the original source files are merged into one to avoid bloating the R/ folder of the package.
dynamic_ordering

Gets the ordering of a single time slice in a DBN
natParticle

R6 class that defines a Particle in the PSO algorithm
nodes_gen_exp

Generates the names of the nodes in t_0 and in all the network
one_hot_cpp

One-hot encoder for natural numbers without the 0
approximate_inference

Performs approximate inference forecasting with the GDBN over a data set
one_hot

One hot encoder for natural numbers without the 0.
randomize_vl_cpp

Randomize a velocity with the given probabilities
recount_arcs_exp

Experimental function that recounts the number of arcs in the position
exact_inference

Performs exact inference forecasting with the GDBN over a data set
init_list_cpp

Initialize the particles
create_causlist_cpp

Create a causal list from a DBN. This is the C++ backend of the function.
as_named_vector

Converts a single row data.table into a named vector
exact_inference_backwards

Performs exact inference smoothing with the GDBN over a data set
create_natcauslist_cpp

Create a natural causal list from a DBN. This is the C++ backend of the function.
filtered_fold_dt

Fold a dataset to a certain size and avoid overlapping of different time-series
init_cl_cpp

Initialize the nodes vector
fold_dt

Widens the dataset to take into account the t previous time slices
fit_dbn_params

Fits a markovian n DBN model
plot_static_network

Plots a Bayesian networks in a hierarchical way
plot_network

Plots a Bayesian networks or a dynamic Bayesian network
plot_dynamic_network

Plots a dynamic Bayesian network in a hierarchical way
nat_pos_plus_vel_cpp

Add a velocity to a position
motor

Multivariate time series dataset on the temperature of an electric motor
nat_vel_plus_vel_cpp

Adds two natVelocities
mvn_inference

Performs inference over a multivariate normal distribution
initialize_cl_cpp

Create a causality list and initialize it
node_levels

Defines a level for every node in the net
ordering_gen_exp

Generates the names of n variables.
pos_plus_vel_cpp

Add a velocity to a position
reduce_freq

Reduce the frequency of the time series data in a data.table
rename_nodes_cpp

Return a list of nodes with the time slice appended up to the desired size of the network
pos_minus_pos_cpp

Subtracts two Positions to obtain the Velocity that transforms one into the other
natVelocity

R6 class that defines velocities in the PSO
natPsoho

Learn a DBN structure with a PSO approach
predict_dt

Performs inference over a test data set with a GBN
psoho

Learn a DBN structure with a PSO approach
vel_plus_vel_cpp

Add two Velocities
trunc_geom

Geometric distribution sampler truncated to a maximum
time_rename

Renames the columns in a data.table so that they end in '_t_0'
predict_bn

Performs inference over a fitted GBN
smooth_ts

Performs smoothing with the GDBN over a data set
Causlist

This file contains all the classes needed for the PSOHO structure learning algorithm. It was implemented as an independent package in https://github.com/dkesada/PSOHO and then merged into dbnR. All the original source files are merged into one to avoid bloating the R/ folder of the package.