import math
from math import *
from random import *class BN:
    nNodes = 0
    nValuesPerNode = []
    parents = []
    CondPrNode = []    def _init_(self):
        nNodes = 0
        nValuesPerNode = []
        parents = []
        CondPrNode = []    # function loading a BN from a file
    def loadBN(self, filename):
        print "Loading BN from file "+filename
        f = file(filename, 'r')        # 1- Get number of nodes
        self.nNodes = int(f.readline())        # 2- Get number of possible values for each node
        tmp = f.readline().split()
        for i in tmp:
            self.nValuesPerNode.append(int(i))        # 3- For each node, get:
        for node in range(self.nNodes):
            self.parents.append([])
            # 3-a the list of parents and
            tmp = f.readline().split()
            for i in tmp:
                self.parents[node].append(int(i))            # 3-b the conditional probability distribution
            #print "node's "+str(node)+" parents: "+str(self.parents)
            self.CondPrNode.append([])
            self.loadCPD(f,node,self.parents[node])
        #print "self.CondPrNode="+str(self.CondPrNode)        f.close()
        print "BN loaded"
        print    # function loading the conditional probability distribution of a node
    # from the next line in file f
    def loadCPD(self, f, node, remainingParents):
        if (len(remainingParents) == 0):
            tmp = f.readline().split()
            tmp2 = []
            for p in tmp:
                tmp2.append(float(p))
            self.CondPrNode[node].append(tmp2)
        else:
            for i in range(self.nValuesPerNode[remainingParents[0]]):
                self.loadCPD(f, node, remainingParents[1:])    # function giving the index in the CPD table of the distribution
    # conditioned on the parents values (in vector pValues)
    def indexCPD(self, node, e):
        pValues = []
        for p in self.parents[node]:
            pValues.append(e[p])
        return self.indexCPDrec(self.parents[node], pValues)    def indexCPDrec(self, remainingParents, pValues):
        last = len(remainingParents)-1
        if (last == -1):
            return 0
        elif (last == 0):
            return pValues[last]
        else:
            return pValues[last] + self.nValuesPerNode[last] * self.indexCPDrec(remainingParents[0:last], pValues[0:last])    # Sampling algorithm.
    # Returns a vector of values sampled according to the distribution
    # defined by the Bayesian network.
    def Sample(self):
        S = [] #<INSERT YOUR CODE HERE !!!>        
        return S    # Enumeration algorithm to infer X given evidence e.
    def EnumerationAsk(self,X,e):
        Q = [] #<INSERT YOUR CODE HERE !!!>        
        return Normalize(Q)    def EnumerateAll(self, vars, e): #<INSERT YOUR CODE HERE !!!>         return 0.
            def Normalize(Q): #<INSERT YOUR CODE HERE !!!>    
    return Q
# main function starts here:# 1- Reading the file
print "Enter name of BN-file to read> ",
filename = str(raw_input())
bn = BN()
bn.loadBN(filename)# 2- "Interactive command line"
while (1):
    print "> ",
    command = str(raw_input())
    
    if (command == "quit"):
        break
        
    elif (command == "sample"):
        print "How many samples do you need ?"
        n = int(raw_input())
        for i in range(n):
            print "\t"+str(bn.Sample())
        
    elif (command == "infer"):
        print "Give a list of evidence variables (nodes) and their values:"
        print "nEvidence"
        print "e1 value"
        print "e2 value"
        print "..."
        print "en value"
        e = []
        for i in range(int(raw_input())):
            tmp = raw_input().split()
            e.append([int(tmp[0]), int(tmp[1])])
        e.sort()
        print "\te="+str(e)
        
        e2 = []
        for i in range(bn.nNodes):
            e2.append(-1)
        for i in e:
            e2[i[0]] = i[1]
            
        print "Give the query variable:",
        X = int(raw_input())
        print "\tX="+str(X)        print "\t"+str(bn.EnumerationAsk(X,e2))
        
    else:
        print "[Help] available commands:"
        print " - sample"
        print " - infer"
        print " - quit"
        printprint "bye"

解决方案 »

  1.   

    晕晕的。。:)
    其实挺简单的。。就是一些小的function多了点而已。。汗。。
      

  2.   

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;//
    //import math
    //from math import *
    //from random import *
    //
    //class BN:
    public class BN{
    //    nNodes = 0
    //    nValuesPerNode = []
    //    parents = []
    //    CondPrNode = []
    public int nNodes  =0;
    int[] nValuesPerNode;
    List[] parents;
    List[] condPrNode;

    //
    //    def _init_(self):
    //        nNodes = 0
    //        nValuesPerNode = []
    //        parents = []
    //        CondPrNode = []
    //
      public BN(){
      //nNodes = 0;
      //nValuesPerNode = null;
     // parents = null;
      //condPrNode = null;   
      }
      
    //    # function loading a BN from a file
    //    def loadBN(self, filename):      
      public void loadBN(String fileName)throws Exception{
    //        print "Loading BN from file "+filename
      System.out.println("Loading BN from file "+fileName);
    //        f = file(filename, 'r')
              BufferedReader f = new BufferedReader(new FileReader(fileName));
    //        # 1- Get number of nodes
    //        self.nNodes = int(f.readline())
              this.nNodes = Integer.parseInt( f.readLine() );
    //        # 2- Get number of possible values for each node
    //        tmp = f.readline().split()
              String[] tmp = f.readLine().split("");
              nValuesPerNode = new int[tmp.length ];
    //        for i in tmp:
    //            self.nValuesPerNode.append(int(i))
              for(int i=0;i<tmp.length ;i++){
               nValuesPerNode[i]=Integer.parseInt(tmp[i]);
              }
    //        # 3- For each node, get:
    //        for node in range(self.nNodes):
              parents = new List[nNodes];
              condPrNode = new List[nNodes];
              for(int node=0;node<nNodes;node++){
    //            self.parents.append([])
               parents[node]=new ArrayList();          
    //            # 3-a the list of parents and
    //            tmp = f.readline().split()
               tmp = f.readLine().split( "");           
    //            for i in tmp:
    //                self.parents[node].append(int(i))
               for(int i=0;i<tmp.length ;i++){
               parents[node].add(Integer.valueOf(tmp[i]));
               }           
    //            # 3-b the conditional probability distribution
    //            #print "node's "+str(node)+" parents: "+str(self.parents)           
    //            self.CondPrNode.append([])          
    //            self.loadCPD(f,node,self.parents[node])
               List tls = new ArrayList(parents[node]);
               loadCPD(f,node,tls);
              }
    //        #print "self.CondPrNode="+str(self.CondPrNode)
    //
    //        f.close()
              f.close() ;
    //        print "BN loaded"
              System.out.println("BN loaded"); 
    //        print
    //
      }
      
    //    # function loading the conditional probability distribution of a node
    //    # from the next line in file f   
    //    def loadCPD(self, f, node, remainingParents):
      private void loadCPD(BufferedReader f,int node,List remainingParents )throws Exception{
    //        if (len(remainingParents) == 0):
      if(remainingParents.size() ==0){
    //            tmp = f.readline().split()
      String[] tmp = f.readLine().split("");
    //            tmp2 = []
      List tmp2 = new ArrayList();
    //            for p in tmp:
    //                tmp2.append(float(p))
      for(int p = 0;p<tmp.length ;p++){
      tmp2.add(Float.valueOf(tmp[p]));
      }
    //            self.CondPrNode[node].append(tmp2)
      condPrNode[node].add(tmp2);
      }
    //        else:
      else{
    //            for i in range(self.nValuesPerNode[remainingParents[0]]):
    //                self.loadCPD(f, node, remainingParents[1:])
      for(int i=0;i<nValuesPerNode[((Integer)(remainingParents.get(0))).intValue()];i++){
      remainingParents.remove( 0);
      loadCPD(f,node,remainingParents);
      }
      }
      }
    //
    //    # function giving the index in the CPD table of the distribution
    //    # conditioned on the parents values (in vector pValues)
    //    def indexCPD(self, node, e):
      private int indexCPD(int node,int e){
    //        pValues = []
      List pValues = new ArrayList();
    //        for p in self.parents[node]:
    //            pValues.append(e[p])
      for(int i=0;i<parents[node].size();i++){
      pValues.add(parents[node].get( i));
      }
    //        return self.indexCPDrec(self.parents[node], pValues)
      return indexCPDRec(parents[node],pValues);
      }
    //
    //    def indexCPDrec(self, remainingParents, pValues):
      private int indexCPDRec(List remainingParents,List pValues ){
    //        last = len(remainingParents)-1
      int last = remainingParents.size()-1;
    //        if (last == -1):
      if(last==-1){
      return 0;
      }   
    //            return 0
    //        elif (last == 0):
    //            return pValues[last]
      if(last==0){
      return ((Integer)pValues.get( last)).intValue() ;
      }
    //        else:
    //            return pValues[last] + self.nValuesPerNode[last] * self.indexCPDrec(remainingParents[0:last], pValues[0:last])
      remainingParents.remove(last);
      pValues.remove( last);
      return ((Integer)pValues.get(last)).intValue() +nValuesPerNode[last]*indexCPDRec(remainingParents,pValues);
      }
    //    # Sampling algorithm.
    //    # Returns a vector of values sampled according to the distribution
    //    # defined by the Bayesian network.
    //    def Sample(self):
      private List sample(){
    //        S = []        
    //        return S
      return new ArrayList();
      }
    //
    //    # Enumeration algorithm to infer X given evidence e.
    //    def EnumerationAsk(self,X,e):
      private Object enumerationAsk(Object X,Object e){
    //        Q = []
      List Q = new ArrayList();
    //     
    //        return Normalize(Q)
      return normalize(Q);
      }
    //
    //    def EnumerateAll(self, vars, e):
    //
          private int  enumerateAll(Object vars,Object e){ 
    //         return 0.
              return 0;
          }
    //
    //            
    //
    //def Normalize(Q):
      private Object normalize(Object Q){ 
    //    return Q
      return Q;
      }
      

  3.   


    //# main function starts here:
    //
      public static void main(String[] args)throws Exception {
    //# 1- Reading the file
    //print "Enter name of BN-file to read> ",
      System.out.println("Enter name of BN-file to read> ") ;
    //filename = str(raw_input())
      BufferedReader raw_input = new BufferedReader(new InputStreamReader(System.in));
      String fileName = raw_input.readLine() ;
    //bn = BN()
      BN bn = new BN();
    //bn.loadBN(filename)
      bn.loadBN(fileName);
    //
    //# 2- "Interactive command line"
    //while (1):
      while(true){
    //    print "> ",
          System.out.println(">");
    //    command = str(raw_input())
              String command = raw_input.readLine() ;
         
    //    if (command == "quit"):
    //        break
              if(command.equals( "quit"))break;
    //        
    //    elif (command == "sample"):
              if(command.equals("sample")){
    //        print "How many samples do you need ?"
               System.out.println("How many samples do you need ?");
    //        n = int(raw_input())
               int n = Integer.parseInt( raw_input.readLine());
    //        for i in range(n):
    //            print "\t"+str(bn.Sample())
              for(int i=0;i<n;i++){
              
                  System.out.println("\t");
              print(bn.sample() );
              }
              }
    //        
    //    elif (command == "infer"):
              if(command.equals( "infer")){
    //        print "Give a list of evidence variables (nodes) and their values:"
               System.out.println("Give a list of evidence variables (nodes) and their values:");
    //        print "nEvidence"
               System.out.println("nEvidence");
    //        print "e1 value"
               System.out.println("e1 value");
    //        print "e2 value"
               System.out.println("e2 value");
    //        print "..."
               System.out.println("...");
    //        print "en value"
               System.out.println("en value");
    //        e = []
              List e = new ArrayList();
    //        for i in range(int(raw_input())):
    //            tmp = raw_input().split()
    //            e.append([int(tmp[0]), int(tmp[1])])
              for(int i=0;i<Integer.parseInt( raw_input.readLine());i++){
               String [] tmp = raw_input.readLine().split("");
               e.add(new int[]{Integer.parseInt(tmp[0]),Integer.parseInt(tmp[1])});
              }
    //        e.sort()
              Collections.sort(e);
    //        print "\te="+str(e)
              print(e);
    //        e2 = []
              List e2 = new ArrayList();
    //        for i in range(bn.nNodes):
    //            e2.append(-1)
              for(int i=0;i<bn.nNodes ;i++){
               e.add( new Integer(-1));
              }          
    //        for i in e:
    //            e2[i[0]] = i[1]
              for(int i=0;i<e.size() ;i++){
               e2.set(((int[])e.get(i))[0],new Integer(((int[])e.get(i))[1]));
              }            
    //        print "Give the query variable:",
              System.out.println("Give the query variable:" );
    //        X = int(raw_input())
              int x = Integer.parseInt( raw_input.readLine());
    //        print "\tX="+str(X)
              System.out.println("\t x="+x);
    //
    //        print "\t"+str(bn.EnumerationAsk(X,e2))
              System.out.println(bn.enumerationAsk(new Integer(x),e2));
              }
    //        
    //    else:
    //        print "[Help] available commands:"
              System.out.println("[Help] available commands:");
    //        print " - sample"
              System.out.println(" - sample");
    //        print " - infer"
              System.out.println(" - infer");
    //        print " - quit"
              System.out.println("- quit");
    //        print
      }
    //
    //print "bye"
      System.out.println("bye");
      }
      public static void print(List list){
      if(list==null)return ;
      for(int i=0;i<list.size();i++){
      System.out.println(list.get(i));
      }
      }
    }