00001 import java.io.File;
00002 import java.io.PrintStream;
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 BN2CSV {
00011 public static int currentColumn;
00012
00017 public static void main(String[] args) throws Exception {
00018 if(args.length != 1) {
00019 System.out.println("usage: BN2CSV <Bayesian network file>");
00020 return;
00021 }
00022
00023 String bnFile = args[0];
00024 File f = new File(bnFile + ".csv");
00025 PrintStream out = new PrintStream(f);
00026
00027 BeliefNetworkEx bn = new BeliefNetworkEx(bnFile);
00028 for(BeliefNode node : bn.bn.getNodes()) {
00029
00030 int columns = 1;
00031 CPF cpf = node.getCPF();
00032 BeliefNode[] domProd = cpf.getDomainProduct();
00033 for(int i = 1; i < domProd.length; i++)
00034 columns *= domProd[i].getDomain().getOrder();
00035 columns++;
00036
00037
00038 int numParents = domProd.length-1;
00039 int domainSize = domProd[0].getDomain().getOrder();
00040 int rows = domainSize + numParents;
00041
00042 String[][] table = new String[columns][rows];
00043
00044
00045 currentColumn = 0;
00046 int row = 0;
00047 for(int i = 1; i < domProd.length; i++)
00048 table[currentColumn][row++] = domProd[i].getName();
00049 for(int i = 0; i < domainSize; i++)
00050 table[currentColumn][row++] = node.getDomain().getName(i);
00051
00052
00053 walkCPT(cpf, 1, new int[domProd.length], table);
00054
00055
00056 out.println("\n" + node.getName());
00057 for(int r = 0; r < rows; r++) {
00058 for(int c = 0; c < columns; c++) {
00059 if(c > 0)
00060 out.print('\t');
00061 out.print(table[c][r]);
00062 }
00063 out.println();
00064 }
00065 }
00066 }
00067
00068 protected static void walkCPT(CPF cpf, int i, int[] addr, String[][] table) {
00069 BeliefNode[] domProd = cpf.getDomainProduct();
00070
00071 if(i == addr.length) {
00072 currentColumn++;
00073 int row = 0;
00074 for(int j = 1; j < domProd.length; j++)
00075 table[currentColumn][row++] = domProd[j].getDomain().getName(addr[j]);
00076 Discrete dom = (Discrete)domProd[0].getDomain();
00077 for(int j = 0; j < dom.getOrder(); j++) {
00078 addr[0] = j;
00079 table[currentColumn][row++] = Double.toString(cpf.getDouble(addr));
00080 }
00081 return;
00082 }
00083
00084 Discrete dom = (Discrete)domProd[i].getDomain();
00085 for(int j = 0; j < dom.getOrder(); j++) {
00086 addr[i] = j;
00087 walkCPT(cpf, i+1, addr, table);
00088 }
00089 }
00090
00091 }