## INPUT: spn (an SPN) spn.print <- function(spn) { ## show some general stats about the spn cat(paste("root nodes=",spn.nnodes(spn),"sum=",spn.nsumnodes(spn),"prod=",spn.nprodnodes(spn),"leaf=",spn.nleafnodes(spn),"params=",spn.nparams(spn),"height=",spn.height(spn),"\n")) ## and print the spn in a nice way, recursively return(spn.print.aux(spn$root, "")) } ## recursively function to print an spn; spaces will show how deep the nodes are when printing spn.print.aux <- function(node, spaces) { if(node$type == 'leaf') { cat(paste(spaces,"leaf var",node$scope,"=",node$value,"\n")) } if(node$type == 'prod') { cat(paste(spaces,"prod scope",paste(node$scope,collapse=" "),"with n=",node$n,"\n")) for(nod in node$children) { spn.print.aux(nod, paste(spaces," ")) } } if(node$type == 'sum') { cat(paste(spaces,"sum scope",paste(node$scope,collapse=" "),"with n=",node$n," w=",paste(node$weight,collapse=" "),"\n")) for(nod in node$children) { spn.print.aux(nod, paste(spaces," ")) } } } spn.height <- function(spn) { return(spn.height.aux(spn$root)) } spn.height.aux <- function(node) { if(node$type == 'leaf') return(0) h <- 0 for(nod in node$children) { h <- max(h, spn.height.aux(nod)) } return(h+1) } spn.nnodes <- function(spn) { return(spn.nnodes.aux(spn$root,type='all')) } spn.nsumnodes <- function(spn) { return(spn.nnodes.aux(spn$root,type='sum')) } spn.nprodnodes <- function(spn) { return(spn.nnodes.aux(spn$root,type='prod')) } spn.nleafnodes <- function(spn) { return(spn.nnodes.aux(spn$root,type='leaf')) } spn.nnodes.aux <- function(node,type) { if(node$type == 'leaf') return(1*(type == 'all' || type == 'leaf')) h <- 1*(type == 'all' || type == node$type) for(nod in node$children) { h <- h + spn.nnodes.aux(nod,type) } return(h) } spn.nparams <- function(spn) { return(spn.nparams.aux(spn$root)) } spn.nparams.aux <- function(node) { if(node$type == 'leaf') return(0) if(node$type == 'sum') h <- length(node$weight) else h <- 0 for(nod in node$children) { h <- h + spn.nparams.aux(nod) } return(h) }