For context, I am conducting hazard modelling, examining the flow of impacts from node to node within a network using Bayesian network analysis. I have a simplified network diagram dag below which I will need to scale up for a more complex network later.
I want to create a hypothetical scenario where node A1 is in an "Interrupted" state. I am using setEvidence function, but when I run a query of the state of node A3, I am getting "NaN" as the result.
Any idea on how to resolve this? Below is the simplified code.
# Load required libraries
library(bnlearn)
library(gRain)
# Define states
states <- c("Normal", "Interrupted")
# Define CPTs
cptA <- matrix(c(1, 0),
nrow = 1,
dimnames = list(NULL, states))
cptA1 <- array(
c(1, 0,
0, 1),
dim = c(2, 2),
dimnames = list(
A1 = states,
A = states
)
)
cptA2 <- array(
c(1, 0,
0, 1),
dim = c(2, 2),
dimnames = list(
A2 = states,
A1 = states
)
)
cptA3 <- array(
c(1, 0,
0, 1),
dim = c(2, 2),
dimnames = list(
A3 = states,
A2 = states
)
)
# Build DAG
dag <- model2network("[A][A1|A][A2|A1][A3|A2]")
# Fit the Bayesian network
fitted <- custom.fit(dag, dist = list(
A = cptA,
A1 = cptA1,
A2 = cptA2,
A3 = cptA3
))
# Convert to gRain object for inference
grain_net <- as.grain(fitted)
# Set evidence: force A1 = "Interrupted"
grain_evidence <- setEvidence(grain_net, evidence = list(A1 = "Interrupted"))
# Query the posterior of A3
query_result <- querygrain(grain_evidence, nodes = "A3")
# Print the result
print(query_result)