public FactorGraph readBnAsFg ( InputStream networkIs , InputStream cpdIs ) throws IOException { // Read network file. BufferedReader networkReader = new BufferedReader ( new InputStreamReader ( networkIs ) ) ; // -- read the number of variables. int numVars = Integer . parseInt ( networkReader . readLine ( ) . trim ( ) ) ; varMap = new HashMap < String , Var > ( ) ; VarSet allVars = new VarSet ( ) ; for ( int i = 0 ; i < numVars ; i ++ ) { Var var = parseVar ( networkReader . readLine ( ) ) ; allVars . add ( var ) ; varMap . put ( var . getName ( ) , var ) ; } assert ( allVars . size ( ) == numVars ) ; // -- read the dependencies between variables. // ....or not... networkReader . close ( ) ; // Read CPD file. BufferedReader cpdReader = new BufferedReader ( new InputStreamReader ( cpdIs ) ) ; factorMap = new LinkedHashMap < VarSet , ExplicitFactor > ( ) ; String line ; while ( ( line = cpdReader . readLine ( ) ) != null ) { // Parse out the variable configuration. VarConfig config = new VarConfig ( ) ; String [ ] assns = whitespaceOrComma . split ( line ) ; for ( int i = 0 ; i < assns . length - 1 ; i ++ ) { String assn = assns [ i ] ; String [ ] va = equals . split ( assn ) ; assert ( va . length == 2 ) ; String varName = va [ 0 ] ; String stateName = va [ 1 ] ; config . put ( varMap . get ( varName ) , stateName ) ; } // The double is the last value on the line. double value = Double . parseDouble ( assns [ assns . length - 1 ] ) ; // Factor graphs store the log value. value = FastMath . log ( value ) ; // Get the factor for this configuration, creating a new one if necessary. VarSet vars = config . getVars ( ) ; ExplicitFactor f = factorMap . get ( vars ) ; if ( f == null ) { f = new ExplicitFactor ( vars ) ; } // Set the value in the factor. f . setValue ( config . getConfigIndex ( ) , value ) ; factorMap . put ( vars , f ) ; } cpdReader . close ( ) ; // Create the factor graph. FactorGraph fg = new FactorGraph ( ) ; for ( ExplicitFactor f : factorMap . values ( ) ) { fg . addFactor ( f ) ; } return fg ; }
Reads a Bayesian Network from a network InputStream and a CPD InputStream and returns a factor graph representation of it .