00001 import java.io.PrintStream;
00002 import java.util.HashMap;
00003
00004 import edu.ksu.cis.bnj.ver3.core.BeliefNode;
00005 import edu.ksu.cis.bnj.ver3.core.CPF;
00006 import edu.ksu.cis.bnj.ver3.core.Discrete;
00007 import edu.tum.cs.bayesnets.core.BeliefNetworkEx;
00008
00009
00010 public class BNlistCPTs {
00011
00012 protected static HashMap<BeliefNode, Integer> domLengths;
00013
00018 public static void main(String[] args) throws Exception {
00019 if(args.length != 1) {
00020 System.out.println("usage: BNlistCPTs <Bayesian network file>");
00021 return;
00022 }
00023
00024 String bnFile = args[0];
00025
00026 PrintStream out = System.out;
00027
00028 BeliefNetworkEx bn = new BeliefNetworkEx(bnFile);
00029
00030 domLengths = new HashMap<BeliefNode, Integer>();
00031 for(BeliefNode node : bn.bn.getNodes()) {
00032 int max_length = 0;
00033 Discrete dom = (Discrete)node.getDomain();
00034 for(int i = 0; i < dom.getOrder(); i++) {
00035 max_length = Math.max(max_length, dom.getName(i).length());
00036 }
00037 domLengths.put(node, max_length);
00038 }
00039
00040 for(BeliefNode node : bn.bn.getNodes()) {
00041 out.println("\n" + node.getName() + ":");
00042
00043 CPF cpf = node.getCPF();
00044 walkCPT(cpf, 1, new int[cpf.getDomainProduct().length], out);
00045 }
00046 }
00047
00048 protected static void walkCPT(CPF cpf, int i, int[] addr, PrintStream out) {
00049 BeliefNode[] domProd = cpf.getDomainProduct();
00050
00051 if(i == addr.length) {
00052 Discrete dom = (Discrete)domProd[0].getDomain();
00053 String condition = null;
00054 for(int j = 0; j < dom.getOrder(); j++) {
00055 addr[0] = j;
00056 double value = cpf.getDouble(addr);
00057 if(value != 0) {
00058 if(condition == null) {
00059 StringBuffer sb = new StringBuffer();
00060 for(int k = 1; k < domProd.length; k++) {
00061 sb.append(" ");
00062 sb.append(domProd[k].getName()).append('=').append(String.format(String.format("%%-%ds", domLengths.get(domProd[k])), domProd[k].getDomain().getName(addr[k])));
00063 }
00064 condition = sb.toString();
00065 }
00066 out.printf("%.6f %s=%s |%s\n",
00067 value,
00068 domProd[0].getName(),
00069 String.format(String.format("%%-%ds", domLengths.get(domProd[0])), domProd[0].getDomain().getName(addr[0])), condition);
00070 }
00071 }
00072 return;
00073 }
00074
00075 Discrete dom = (Discrete)domProd[i].getDomain();
00076 for(int j = 0; j < dom.getOrder(); j++) {
00077 addr[i] = j;
00078 walkCPT(cpf, i+1, addr, out);
00079 }
00080 }
00081 }