def get_inf_bp(self, logdomain=False, verbose=False): sn = dai.FactorGraph(self.vecfac) prop = dai.PropertySet() prop["tol"] = "1e-9" if logdomain: prop["logdomain"] = "1" else: prop["logdomain"] = "0" prop["updates"] = "SEQFIX" if verbose: prop["verbose"] = "1" else: prop["verbose"] = "0" lb_inf = dai.BP(sn, prop) return lb_inf
def build_libdaiFactorGraph_from_SATproblem(clauses, N): ''' Inputs: - clauses: (list of list of ints) variables should be numbered 1 to N with no gaps - N: (int) the number of variables in the sat problem. This should be equal the largest variable name (otherwise could have problems with implicit variables, e.g. a missing variable x_i is equivalent to the clause (x_i or not x_i), doubling the solution count) Outputs: - sat_FactorGraph: (dai.FactorGraph) ''' #make sure variables are numbered 1 to N with no gaps all_literals = {} max_literal = 0 for clause in clauses: for var in clause: lit = abs(var) all_literals[lit] = True if lit > max_literal: max_literal = lit assert (len(all_literals) == max_literal) assert (max_literal == N) for i in range(1, max_literal + 1): assert (i in all_literals) # Define binary variables in the factor graph variables = [] for var_idx in range(max_literal): variables.append(dai.Var(var_idx, 2)) #variable can take 2 values factors = [] for clause in clauses: factors.append(build_libdaiFactor_fromClause(clause, variables)) assert (len(factors) == len(clauses)) assert (len(variables) == max_literal) # Build factor graph sat_Factors = dai.VecFactor() for factor in factors: sat_Factors.append(factor) sat_FactorGraph = dai.FactorGraph(sat_Factors) return sat_FactorGraph
def _prepare_dai_factor_graph(self, filename): self.factor_graph.dump(filename) self.dai_factor_graph = dai.FactorGraph() self.dai_factor_graph.ReadFromFile(filename)
def get_factor_graph(self): if self.vecfac is None: self.setup_factor_graph() return dai.FactorGraph(self.vecfac)
def build_libdaiFactorGraph_from_SpinGlassModel(sg_model, fixed_variables={}): ''' copied from https://github.com/jkuck/mrf_nesting_ub/blob/master/Factor_Graphs/libdai_ising_model.py Inputs: - sg_model: (SG_model) - fixed_variables: (dictionary) key: (int) 0 to N-1 variable index value: (int) -1 or 1, the value the variable is fixed to Outputs: - sg_FactorGraph: (dai.FactorGraph) ''' N = sg_model.lcl_fld_params.shape[0] assert (N == sg_model.lcl_fld_params.shape[1]) # accumulator_var_idx = None # if len(fixed_variables) > 0: # assert(len(fixed_variables) < N**2) # for var_idx in range(N**2): # if var_idx not in fixed_variables: # accumulator_var_idx = var_idx #this variable gets all the fixed factors multiplied into its single node factor # break # assert(accumulator_var_idx is not None) # Define binary variables in the factor graph variables = [] for var_idx in range(N**2): if var_idx in fixed_variables: variables.append(dai.Var(var_idx, 1)) #variable can take 1 values if var_idx not in fixed_variables: variables.append(dai.Var(var_idx, 2)) #variable can take 2 values factors = [] # Define factors for each single variable factor for var_idx in range(N**2): r = var_idx // N c = var_idx % N factors.append( build_single_node_factor(variables, fixed_variables, var_idx, f=sg_model.lcl_fld_params[r, c])) # Define pairwise factors for var_idx in range(N**2): r = var_idx // N c = var_idx % N if r < N - 1: factors.append( build_pairwise_factor(variables, fixed_variables, var_idx1=var_idx, var_idx2=var_idx + N, c=sg_model.cpl_params_v[r, c])) if c < N - 1: factors.append( build_pairwise_factor(variables, fixed_variables, var_idx1=var_idx, var_idx2=var_idx + 1, c=sg_model.cpl_params_h[r, c])) #Define higher order factors if sg_model.contains_higher_order_potentials: # Add higher order factors for potential_idx in range(sg_model.ho_potential_count): factor_potentials_list.append( sg_model.higher_order_potentials[potential_idx]) masks_list.append( torch.zeros_like( sg_model.higher_order_potentials[potential_idx])) assert (len(factors) == N**2 + 2 * N * (N - 1)) # Build factor graph sg_Factors = dai.VecFactor() for factor in factors: sg_Factors.append(factor) sg_FactorGraph = dai.FactorGraph(sg_Factors) return sg_FactorGraph
P_W_given_S_R[0] = 1.0 # S = 0, R = 0, W = 0 P_W_given_S_R[1] = 0.1 # S = 1, R = 0, W = 0 P_W_given_S_R[2] = 0.1 # S = 0, R = 1, W = 0 P_W_given_S_R[3] = 0.01 # S = 1, R = 1, W = 0 P_W_given_S_R[4] = 0.0 # S = 0, R = 0, W = 1 P_W_given_S_R[5] = 0.9 # S = 1, R = 0, W = 1 P_W_given_S_R[6] = 0.9 # S = 0, R = 1, W = 1 P_W_given_S_R[7] = 0.99 # S = 1, R = 1, W = 1 # Build factor graph consisting of those four factors SprinklerFactors = dai.VecFactor() SprinklerFactors.append(P_C) SprinklerFactors.append(P_R_given_C) SprinklerFactors.append(P_S_given_C) SprinklerFactors.append(P_W_given_S_R) SprinklerNetwork = dai.FactorGraph(SprinklerFactors) # Write factorgraph to a file SprinklerNetwork.WriteToFile('sprinkler.fg') print 'Sprinkler network written to sprinkler.fg' # Output some information about the factorgraph print SprinklerNetwork.nrVars(), 'variables' print SprinklerNetwork.nrFactors(), 'factors' # Calculate joint probability of all four variables P = dai.Factor() for I in range(SprinklerNetwork.nrFactors()): P *= SprinklerNetwork.factor(I) P.normalize( ) # Not necessary: a Bayesian network is already normalized by definition
a = dai.IntVector() if len(sys.argv) != 2 and len(sys.argv) != 3: print 'Usage:', sys.argv[0], "<filename.fg> [maxstates]" print 'Reads factor graph <filename.fg> and runs' print 'Belief Propagation, Max-Product and JunctionTree on it.' print 'JunctionTree is only run if a junction tree is found with' print 'total number of states less than <maxstates> (where 0 means unlimited).' sys.exit(1) else: # Report inference algorithms built into libDAI # print 'Builtin inference algorithms:', dai.builtinInfAlgNames() # TODO THIS CRASHES # Read FactorGraph from the file specified by the first command line argument fg = dai.FactorGraph() fg.ReadFromFile(sys.argv[1]) maxstates = 1000000 if len(sys.argv) == 3: maxstates = int(sys.argv[2]) # Set some constants maxiter = 10000 tol = 1e-9 verb = 1 # Store the constants in a PropertySet object opts = dai.PropertySet() opts["maxiter"] = str(maxiter) # Maximum number of iterations opts["tol"] = str(tol) # Tolerance for convergence opts["verbose"] = str(verb) # Verbosity (amount of output generated)
def build_libdaiFactorGraph_from_SpinGlassModel(sg_model, fixed_variables={}): ''' copied from https://github.com/jkuck/mrf_nesting_ub/blob/master/Factor_Graphs/libdai_ising_model.py Inputs: - sg_model: (SG_model) - fixed_variables: (dictionary) key: (int) 0 to N-1 variable index value: (int) -1 or 1, the value the variable is fixed to Outputs: - sg_FactorGraph: (dai.FactorGraph) ''' N = sg_model.lcl_fld_params.shape[0] assert (N == sg_model.lcl_fld_params.shape[1]) # accumulator_var_idx = None # if len(fixed_variables) > 0: # assert(len(fixed_variables) < N**2) # for var_idx in range(N**2): # if var_idx not in fixed_variables: # accumulator_var_idx = var_idx #this variable gets all the fixed factors multiplied into its single node factor # break # assert(accumulator_var_idx is not None) # Define binary variables in the factor graph variables = [] for var_idx in range(N**2): if var_idx in fixed_variables: variables.append(dai.Var(var_idx, 1)) #variable can take 1 values if var_idx not in fixed_variables: variables.append(dai.Var(var_idx, 2)) #variable can take 2 values factors = [] # Define factors for each single variable factor for var_idx in range(N**2): r = var_idx // N c = var_idx % N factors.append( build_single_node_factor(variables, fixed_variables, var_idx, f=sg_model.lcl_fld_params[r, c])) # Define pairwise factors for var_idx in range(N**2): r = var_idx // N c = var_idx % N if r < N - 1: factors.append( build_pairwise_factor(variables, fixed_variables, var_idx1=var_idx, var_idx2=var_idx + N, c=sg_model.cpl_params_v[r, c])) if (c < N - 1) and (r == 0): factors.append( build_pairwise_factor(variables, fixed_variables, var_idx1=var_idx, var_idx2=var_idx + 1, c=sg_model.cpl_params_h[r, c])) assert (len(factors) == N**2 + (N - 1) + N * (N - 1)) # Build factor graph sg_Factors = dai.VecFactor() for factor in factors: sg_Factors.append(factor) sg_FactorGraph = dai.FactorGraph(sg_Factors) # bp_z_est = run_loopyBP(sg_model, maxiter=1000) # exact_z = libdai_utils.junction_tree(sg_FactorGraph) # print("bp_z_est =", bp_z_est) # print("exact_z =", exact_z) return sg_FactorGraph