Beispiel #1
0
    def setup_factor_graph(self):
        self.vecfac = dai.VecFactor()
        elem_map = {}
        for elem in self.variable_map:
            if elem.variable_name not in elem_map:
                elem_map[elem.variable_name] = {
                    elem.variable_type: elem.variable_id
                }
            else:
                elem_map[elem.variable_name][
                    elem.variable_type] = elem.variable_id
            #dai_var_map[elem.variable] = dai.Var(elem.variable, elem.dim)

        for cpt in sorted(self.cpt_map.keys(), key=lambda x: x.factor_id):
            cpt_value = self.cpt_map[cpt]
            var_list = dai.VarSet()
            v_list = list(cpt_value.variables)
            v_list.sort()
            for v_id in v_list:
                v = self.variable_map.get_variable_by_id(v_id)
                if v not in self.dai_variables:
                    self.dai_variables[v] = dai.Var(v.variable_id, v.dim)
                var_list.append(self.dai_variables[v])
            dai_factor = dai.Factor(var_list)
            for i, v in enumerate(cpt_value.cpt_linear_table()):
                dai_factor[i] = v
            self.vecfac.append(dai_factor)
Beispiel #2
0
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
Beispiel #3
0
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
# Define conditional probability of W given S and R
SRW = dai.VarSet(S, R)
SRW.append(W)
P_W_given_S_R = dai.Factor(SRW)
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
Beispiel #5
0
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