Пример #1
0
    def __getitem__(self, index):

        lops = np.random.uniform(0.0, 1.0, (self.chain_length, 2))
        pws = self.transition

        hk = self.hop_order // 2

        g = fg.PFactorGraph()
        var_list = []
        for i in range(self.chain_length):
            v = g.create_multi_variable(2)
            v.set_log_potentials(lops[i])
            var_list.append(v)

        for i in range(self.chain_length - 1):
            g.create_factor_dense([var_list[i], var_list[i + 1]], pws)

        for i in range(self.chain_length - self.hop_order + 1):
            v_list = [
                var_list[j].get_state(1) for j in range(i, i + self.hop_order)
            ]
            g.create_factor_budget(v_list, self.cap)

        val, post, _, stat = g.solve(tol=1e-6, branch_and_bound=True)

        post = np.reshape(np.asarray(post), [self.chain_length, 2])
        assign = np.argmax(post, axis=1)

        node_feature = np.transpose(lops.astype(np.float32), [1, 0])

        g = fg.PFactorGraph()
        var_list = []
        for i in range(self.chain_length):
            v = g.create_multi_variable(2)
            v.set_log_potentials(lops[i])
            var_list.append(v)

        for i in range(self.chain_length - 1):
            g.create_factor_dense([var_list[i], var_list[i + 1]], pws)

        for i in range(self.chain_length - self.hop_order + 1):
            v_list = [
                var_list[j].get_state(1) for j in range(i, i + self.hop_order)
            ]
            g.create_factor_budget(v_list, self.cap)

        val1, post1, _, status = g.solve(branch_and_bound=False)
        post1 = np.reshape(np.asarray(post1), [self.chain_length, 2])
        assign1 = np.argmax(post1, axis=1)

        return node_feature, assign, assign1
Пример #2
0
    def __init__(self, instance, parts, scores):
        self.left_siblings = None
        self.right_siblings = None
        self.left_grandparents = None
        self.right_grandparents = None
        self.left_grandsiblings = None
        self.right_grandsiblings = None

        self.use_siblings = parts.has_type(Target.NEXT_SIBLINGS)
        self.use_grandparents = parts.has_type(Target.GRANDPARENTS)
        self.use_grandsiblings = parts.has_type(Target.GRANDSIBLINGS)

        # arcs is a list of tuples (h, m)
        heads, modifiers = parts.get_arc_indices()
        self.arcs = list(zip(heads, modifiers))
        self.arc_index = parts.create_arc_index()

        # these indices keep track of the higher order parts added to the graph
        self.additional_indices = []

        self.graph = fg.PFactorGraph()
        variables = self.create_tree_factor(instance, parts, scores)

        self._index_parts_by_head(parts, instance, scores)

        if self.use_grandsiblings or \
                (self.use_siblings and self.use_grandparents):
            self.create_gp_head_automata(variables)
        elif self.use_grandparents:
            self.create_grandparent_factors(parts, scores, variables)
        elif self.use_siblings:
            self.create_head_automata(variables)
Пример #3
0
def test_logic_constraints():
    graph = fg.PFactorGraph()
    n_states = 3

    var_a = graph.create_multi_variable(n_states)
    var_b = graph.create_multi_variable(n_states)

    var_a.set_log_potential(0, 1)  # A = 0
    var_b.set_log_potential(1, 10)  # B = likely 1, possibly 2
    var_b.set_log_potential(2, 9.5)

    graph.fix_multi_variables_without_factors()

    value_unconstrained, marginals, _, _ = graph.solve()

    expected = [0, 1]
    obtained = np.array(marginals).reshape(2, -1).argmax(axis=1)
    assert_array_equal(expected, obtained)

    # add logic constraint: (A = 0) -> not (B = 1)
    graph.create_factor_logic('IMPLY', [var_a.get_state(0),
                                        var_b.get_state(1)],
                              [False, True])

    graph.fix_multi_variables_without_factors()  # need to run this again

    value_constrained, marginals, _, _ = graph.solve()

    expected = [0, 2]
    obtained = np.array(marginals).reshape(2, -1).argmax(axis=1)
    assert_array_equal(expected, obtained)

    # total score must be lower
    assert value_constrained < value_unconstrained
Пример #4
0
def test_pair():
    graph = fg.PFactorGraph()
    a = graph.create_binary_variable()
    b = graph.create_binary_variable()

    assert a.get_degree() == b.get_degree() == 0

    val = 100.0

    graph.create_factor_pair([a, b], val)
    assert a.get_degree() == b.get_degree() == 1

    graph.create_factor_pair([a, b], -val)
    assert a.get_degree() == b.get_degree() == 2

    with pytest.raises(TypeError):
        graph.create_factor_pair([a, b], None)

    with pytest.raises(TypeError):
        graph.create_factor_pair(None, val)

    with pytest.raises(TypeError):
        graph.create_factor_pair(-1, val)

    with pytest.raises(TypeError):
        graph.create_factor_pair([a, -1], val)

    with pytest.raises(AttributeError):
        graph.create_factor_pair([a, None], val)

    with pytest.raises(ValueError):
        graph.create_factor_pair([a, b, a], val)
def test_solve():
    rng = np.random.RandomState(0)
    graph = fg.PFactorGraph()

    a = graph.create_multi_variable(3)
    b = graph.create_multi_variable(3)
    c = graph.create_multi_variable(3)

    a.set_log_potentials(rng.randn(3))
    b.set_log_potentials(rng.randn(3))
    c.set_log_potentials(rng.randn(3))

    graph.create_factor_dense([a, b], rng.randn(3 * 3))
    graph.create_factor_dense([a, c], rng.randn(3 * 3))
    graph.create_factor_dense([b, c], rng.randn(3 * 3))

    val, _, _, status = graph.solve()
    assert status == 'integral'

    val_one_iter, _, _, status_one_iter = graph.solve(max_iter=1)
    assert status_one_iter == 'unsolved'
    assert val_one_iter < val

    val_lowtol, _, _, status_lowtol = graph.solve(tol=0.3)
    assert status_lowtol == 'fractional'
    assert val_lowtol > val

    val_lowtol_bb, _, _, status_lowtol_bb = graph.solve(tol=0.3,
                                                        branch_and_bound=True)
    assert status_lowtol_bb == 'integral'
    assert (val_lowtol_bb - val) ** 2 < 1e-8
Пример #6
0
def test_primal_dual_vars():
    g = fg.PFactorGraph()
    g.solve()
    assert g.get_dual_variables() == []
    assert g.get_local_primal_variables() == []
    assert g.get_global_primal_variables() == []

    g = fg.PFactorGraph()
    a = g.create_binary_variable()
    a.set_log_potential(0)
    b = g.create_binary_variable()
    b.set_log_potential(1)
    g.create_factor_pair([a, b], -2)
    g.create_factor_pair([a, b], -10)
    g.solve()
    assert len(g.get_dual_variables()) == 4
    assert len(g.get_local_primal_variables()) == 4
    assert len(g.get_global_primal_variables()) == 2
Пример #7
0
    def _generate_graph(self):
        g = fg.PFactorGraph()
        var_list = []
        for i in range(self.chain_length):
            v = g.create_multi_variable(2)
            v.set_log_potentials(self.lops[i])
            var_list.append(v)

        for i in range(self.chain_length - 1):
            g.create_factor_dense([var_list[i], var_list[i + 1]], self.pws)

        return g
Пример #8
0
def test_logic_negate():
    # not a & not b is equiv to not(a or b)
    rng = np.random.RandomState()

    for _ in range(10):
        potentials = rng.randn(3)
        graph = fg.PFactorGraph()
        variables = [graph.create_binary_variable() for _ in range(3)]
        for var, val in zip(variables, potentials):
            var.set_log_potential(val)
        graph.create_factor_logic('ANDOUT', variables, [True, True, False])
        val_1, (_, _, out_1), _, _ = graph.solve()

        graph = fg.PFactorGraph()
        variables = [graph.create_binary_variable() for _ in range(3)]
        for var, val in zip(variables, potentials):
            var.set_log_potential(val)
        graph.create_factor_logic('OROUT', variables, [False, False, True])
        val_2, (_, _, out_2), _, _ = graph.solve()

        assert val_1 == val_2
        assert out_1 == out_2
def test_budget():
    graph = fg.PFactorGraph()

    potentials = [100, 1, 100, 1, 100]

    for val in potentials:
        var = graph.create_binary_variable()
        var.set_log_potential(val)

    _, assign, _, _ = graph.solve()
    assert sum(assign) == 5

    budget = 3

    graph = fg.PFactorGraph()

    variables = [graph.create_binary_variable() for _ in potentials]
    for var, val in zip(variables, potentials):
        var.set_log_potential(val)

    graph.create_factor_budget(variables, budget=budget)
    _, assign, _, status = graph.solve()
    assert_array_almost_equal(assign, [1, 0, 1, 0, 1])
def test_knapsack():
    graph = fg.PFactorGraph()

    potentials = [100, 1, 100, 1, 100]
    costs = [3, 5, 5, 5, 2]

    for val in potentials:
        var = graph.create_binary_variable()
        var.set_log_potential(val)

    _, assign, _, _ = graph.solve()
    assert sum(assign) == 5

    budget = 5

    graph = fg.PFactorGraph()
    variables = [graph.create_binary_variable() for _ in potentials]
    for var, val in zip(variables, potentials):
        var.set_log_potential(val)

    graph.create_factor_knapsack(variables, costs, budget)
    _, assign, _, status = graph.solve(branch_and_bound=True)
    assert_array_almost_equal(assign, [1, 0, 0, 0, 1])
Пример #11
0
def test_smoke_logic(factor_type):
    graph = fg.PFactorGraph()
    variables = [graph.create_binary_variable() for _ in range(3)]

    for var in variables:
        assert var.get_degree() == 0

    graph.create_factor_logic(factor_type, variables)

    for var in variables:
        assert var.get_degree() == 1

    # check that we find a feasible solution
    val, _, _, _ = graph.solve()
    assert val == 0
Пример #12
0
def solve_lp_knapsack_ad3(scores, costs, budget):
    factor_graph = fg.PFactorGraph()
    binary_variables = []
    for i in range(len(scores)):
        binary_variable = factor_graph.create_binary_variable()
        binary_variable.set_log_potential(scores[i])
        binary_variables.append(binary_variable)

    factor_graph.create_factor_knapsack(binary_variables,
                                        costs=costs,
                                        budget=budget)

    # Run AD3.
    _, posteriors, _, _ = factor_graph.solve()
    return posteriors
Пример #13
0
def test_logic_validate():
    graph = fg.PFactorGraph()
    variables = [graph.create_binary_variable() for _ in range(3)]
    with pytest.raises(NotImplementedError) as e:
        graph.create_factor_logic('foo', variables)

    assert 'unknown' in str(e.value).lower()

    with pytest.raises(ValueError):
        graph.create_factor_logic('OR', variables, negated=[True])

    with pytest.raises(ValueError):
        graph.create_factor_logic('OR', variables, negated=[True] * 10)

    with pytest.raises(TypeError):
        graph.create_factor_logic('OR', variables, negated=42)
Пример #14
0
def test_dense():
    graph = fg.PFactorGraph()

    n_a = 2
    a = graph.create_multi_variable(n_a)

    n_b = 3
    b = graph.create_multi_variable(n_b)

    vals = np.arange(n_a * n_b)

    def check_degree_all(degree):

        for i in range(n_a):
            assert a.get_state(i).get_degree() == degree

        for i in range(n_b):
            assert b.get_state(i).get_degree() == degree

    check_degree_all(0)
    graph.create_factor_dense([a, b], vals)
    check_degree_all(1)
    graph.create_factor_dense([a, b], vals)
    check_degree_all(2)

    with pytest.raises(TypeError):
        graph.create_factor_dense(None, vals)

    with pytest.raises(TypeError):
        graph.create_factor_dense(-1, vals)

    with pytest.raises(TypeError):
        graph.create_factor_dense([a, -1], vals)

    with pytest.raises(AttributeError):
        graph.create_factor_dense([a, None], vals)

    with pytest.raises(ValueError):
        graph.create_factor_dense([a, b], vals[:-1])

    with pytest.raises(ValueError):
        graph.create_factor_dense([a, b], np.concatenate([vals, vals]))

    with pytest.raises(TypeError):
        graph.create_factor_dense([a, b], None)
Пример #15
0
    def _generate_graph(self):
        g = fg.PFactorGraph()
        var_list = []
        for i in range(self.chain_length):
            v = g.create_multi_variable(2)
            v.set_log_potentials(self.lops[i])
            var_list.append(v)

        for i in range(self.chain_length - 1):
            g.create_factor_dense([var_list[i], var_list[i + 1]],
                                  self.pws[i][0])

        for i in range(self.chain_length - self.hop_order + 1):
            v_list = [
                var_list[j].get_state(1) for j in range(i, i + self.hop_order)
            ]
            g.create_factor_budget(v_list, self.cap[i + self.half_hop])

        return g
Пример #16
0
def solve_lp_knapsack_ad3(scores, costs, budget):
  factor_graph = fg.PFactorGraph()
  binary_variables = []
  for i in xrange(len(scores)):
      binary_variable = factor_graph.create_binary_variable()
      binary_variable.set_log_potential(scores[i])
      binary_variables.append(binary_variable) 

  negated = [False] * len(binary_variables)
  factor_graph.create_factor_knapsack(binary_variables, negated, costs, budget)

  #pdb.set_trace()
  # Run AD3.        
  factor_graph.set_verbosity(1)
  factor_graph.set_eta_ad3(.1)
  factor_graph.adapt_eta_ad3(True)
  factor_graph.set_max_iterations_ad3(1000)
  value, posteriors, additional_posteriors, status = factor_graph.solve_lp_map_ad3()

  return posteriors  
def test_sequence_dense():

    n_states = 3
    transition = np.eye(n_states).ravel()
    graph = fg.PFactorGraph()

    vars_expected = [0, 1, None, None, 1]
    variables = [graph.create_multi_variable(n_states) for _ in vars_expected]
    for prev, curr in zip(variables, variables[1:]):
        graph.create_factor_dense([prev, curr], transition)
    for var, ix in zip(variables, vars_expected):
        if ix is not None:
            var.set_log_potential(ix, 1)

    value, marginals, additionals, status = graph.solve()
    # 3 points for "observed" values, 3 points for consecutive equal vals
    assert value == 6

    expected = [0, 1, 1, 1, 1]
    obtained = np.array(marginals).reshape(5, -1).argmax(axis=1)
    assert_array_equal(expected, obtained)
def test_knapsack_wrong_cost_size():
    graph = fg.PFactorGraph()
    n_vars = 50
    variables = [graph.create_binary_variable() for _ in range(n_vars)]
    budget = 1

    with pytest.raises(ValueError):
        small_cost = [17]
        graph.create_factor_knapsack(variables,
                                     costs=small_cost,
                                     budget=budget)

    with pytest.raises(ValueError):
        big_cost = [17] * (n_vars + 1)
        graph.create_factor_knapsack(variables, costs=big_cost, budget=budget)

    with pytest.raises(TypeError):
        graph.create_factor_knapsack(variables, costs=42, budget=budget)

    with pytest.raises(TypeError):
        graph.create_factor_knapsack(variables, costs=None, budget=budget)
Пример #19
0
def test_dense_at_most_one():
    # check that dense factor enforces one-of-k

    graph = fg.PFactorGraph()
    n = 3
    a = graph.create_multi_variable(n)
    b = graph.create_multi_variable(n)

    a.set_log_potentials(-100 * np.ones(3))
    b.set_log_potentials(np.ones(3))

    dense_vals = np.zeros((3, 3))
    dense_vals[0, 0] = 1
    dense_vals[1, 2] = 10
    # (0, 0, 0) / (0, 0, 0) would be highest if allowed
    # (1, 1, 0) / (1, 0, 1) would be highest otherwise, if allowed
    # (0, 1, 0) / (0, 0, 1) is the highest allowable.

    graph.create_factor_dense([a, b], dense_vals.ravel())
    _, assignments, _, _ = graph.solve()
    expected = np.array([0, 1, 0, 0, 0, 1])
    assert_array_equal(expected, assignments)
def test_multi_variable():
    graph = fg.PFactorGraph()
    five = graph.create_multi_variable(5)
    assert len(five) == 5
    vals = np.arange(5).astype(np.double)

    five[1] = vals[1]
    assert five[1] == vals[1]

    five.set_log_potentials(vals)
    for i in range(5):
        assert five[i] == vals[i]

    state = five.get_state(1)
    assert state.get_log_potential() == vals[1]

    with pytest.raises(IndexError):
        five.get_state(6)

    with pytest.raises(IndexError):
        five[6]

    with pytest.raises(IndexError):
        five[6] = 1.1
Пример #21
0
    def _inference(self,
                   x,
                   potentials,
                   exact=False,
                   relaxed=True,
                   return_energy=False,
                   constraints=None,
                   eta=0.1,
                   adapt=True,
                   max_iter=5000,
                   verbose=False):

        (prop_potentials, link_potentials, compat_potentials,
         coparent_potentials, grandparent_potentials,
         sibling_potentials) = potentials

        n_props, n_prop_classes = prop_potentials.shape
        n_links, n_link_classes = link_potentials.shape

        g = fg.PFactorGraph()
        g.set_verbosity(verbose)

        prop_vars = [
            g.create_multi_variable(n_prop_classes) for _ in range(n_props)
        ]
        link_vars = [
            g.create_multi_variable(n_link_classes) for _ in range(n_links)
        ]

        for var, scores in zip(prop_vars, prop_potentials):
            for state, score in enumerate(scores):
                var.set_log_potential(state, score)

        for var, scores in zip(link_vars, link_potentials):
            for state, score in enumerate(scores):
                var.set_log_potential(state, score)

        # compatibility trigram factors
        compat_factors = []
        link_vars_dict = {}

        link_on, link_off = self.link_encoder_.transform([True, False])

        # account for compat features
        if self.compat_features:
            assert compat_potentials.shape[0] == n_links
            compats = compat_potentials
        else:
            compats = (compat_potentials for _ in range(n_links))

        for (src, trg), link_v, compat in zip(x.link_to_prop, link_vars,
                                              compats):
            src_v = prop_vars[src]
            trg_v = prop_vars[trg]
            compat_factors.append(
                g.create_factor_dense([src_v, trg_v, link_v], compat.ravel()))

            # keep track of binary link variables, for constraints.
            # we need .get_state() to get the underlaying PBinaryVariable
            link_vars_dict[src, trg] = link_v.get_state(link_on)

        # second-order factors
        coparent_factors = []
        grandparent_factors = []
        sibling_factors = []

        for score, (a, b, c) in zip(coparent_potentials, x.second_order):
            # a -> b <- c
            vars = [link_vars_dict[a, b], link_vars_dict[c, b]]
            coparent_factors.append(g.create_factor_pair(vars, score))

        for score, (a, b, c) in zip(grandparent_potentials, x.second_order):
            # a -> b -> c
            vars = [link_vars_dict[a, b], link_vars_dict[b, c]]
            grandparent_factors.append(g.create_factor_pair(vars, score))

        for score, (a, b, c) in zip(sibling_potentials, x.second_order):
            # a <- b -> c
            vars = [link_vars_dict[b, a], link_vars_dict[b, c]]
            sibling_factors.append(g.create_factor_pair(vars, score))

        # domain-specific constraints
        if constraints and 'cdcp' in constraints:

            # antisymmetry: if a -> b, then b cannot -> a
            for src in range(n_props):
                for trg in range(src):
                    fwd_link_v = link_vars_dict[src, trg]
                    rev_link_v = link_vars_dict[trg, src]
                    g.create_factor_logic('ATMOSTONE',
                                          [fwd_link_v, rev_link_v],
                                          [False, False])

            # transitivity.
            # forall a != b != c: a->b and b->c imply a->c
            for a, b, c in permutations(range(n_props), 3):
                ab_link_v = link_vars_dict[a, b]
                bc_link_v = link_vars_dict[b, c]
                ac_link_v = link_vars_dict[a, c]
                g.create_factor_logic('IMPLY',
                                      [ab_link_v, bc_link_v, ac_link_v],
                                      [False, False, False])

            # standard model:
            if 'strict' in constraints:
                for src, trg in x.link_to_prop:
                    src_v = prop_vars[src]
                    trg_v = prop_vars[trg]

                    for types in CDCP_ILLEGAL_LINKS:
                        src_ix, trg_ix = self.prop_encoder_.transform(types)
                        g.create_factor_logic('IMPLY', [
                            src_v.get_state(src_ix),
                            trg_v.get_state(trg_ix), link_vars_dict[src, trg]
                        ], [False, False, True])

        elif constraints and 'ukp' in constraints:

            # Tree constraints using AD3 MST factor for each paragraph.
            # First, identify paragraphs
            prop_para = np.array(x.prop_para)
            link_para = prop_para[x.link_to_prop[:, 0]]
            tree_factors = []

            for para_ix in np.unique(link_para):
                props = np.where(prop_para == para_ix)[0]
                offset = props.min()
                para_vars = []
                para_arcs = []  # call them arcs, semantics differ from links

                # add a new head node pointing to every possible variable
                for relative_ix, prop_ix in enumerate(props, 1):
                    para_vars.append(g.create_binary_variable())
                    para_arcs.append((0, relative_ix))

                # add an MST arc for each link
                for src, trg in x.link_to_prop[link_para == para_ix]:
                    relative_src = src - offset + 1
                    relative_trg = trg - offset + 1
                    para_vars.append(link_vars_dict[src, trg])
                    # MST arcs have opposite direction from argument links!
                    # because each prop can have multiple supports but not
                    # the other way around
                    para_arcs.append((relative_trg, relative_src))

                tree = fg.PFactorTree()
                g.declare_factor(tree, para_vars, True)
                tree.initialize(1 + len(props), para_arcs)
                tree_factors.append(tree)

            if 'strict' in constraints:
                # further domain-specific constraints
                mclaim_ix, claim_ix, premise_ix = self.prop_encoder_.transform(
                    ['MajorClaim', 'Claim', 'Premise'])

                # a -> b implies a = 'premise'
                for (src, trg), link_v in zip(x.link_to_prop, link_vars):
                    src_v = prop_vars[src]
                    g.create_factor_logic('IMPLY', [
                        link_v.get_state(link_on),
                        src_v.get_state(premise_ix)
                    ], [False, False])

        g.fix_multi_variables_without_factors()
        g.set_eta_ad3(eta)
        g.adapt_eta_ad3(adapt)
        g.set_max_iterations_ad3(max_iter)

        if exact:
            val, posteriors, additionals, status = g.solve_exact_map_ad3()
        else:
            val, posteriors, additionals, status = g.solve_lp_map_ad3()

        status = ["integer", "fractional", "infeasible", "not solved"][status]

        prop_marg = posteriors[:n_props * n_prop_classes]
        prop_marg = np.array(prop_marg).reshape(n_props, -1)

        link_marg = posteriors[n_props * n_prop_classes:]
        # remaining posteriors are for artificial root nodes for MST factors
        link_marg = link_marg[:n_links * n_link_classes]
        link_marg = np.array(link_marg).reshape(n_links, -1)

        n_compat = n_links * n_link_classes * n_prop_classes**2
        compat_marg = additionals[:n_compat]
        compat_marg = np.array(compat_marg).reshape(
            (n_links, n_prop_classes, n_prop_classes, n_link_classes))

        second_ordermarg = np.array(additionals[n_compat:])

        posteriors = (prop_marg, link_marg)
        additionals = (compat_marg, second_ordermarg)

        if relaxed:
            y_hat = posteriors, additionals
        else:
            y_hat = self._round(prop_marg, link_marg, prop_potentials,
                                link_potentials)

        if return_energy:
            return y_hat, status, -val
        else:
            return y_hat, status
Пример #22
0
    num_children = rng.randint(1, max_available + 1)
    ind_children = rng.permutation(num_available)[:num_children]
    children = [available_nodes[j] for j in ind_children]
    for j in children:
        parents[j] = i
        nodes_to_process.insert(0, j)
        available_nodes.remove(j)

print(parents)

# generate random potentials
var_log_potentials = rng.randn(num_nodes)
edge_log_potentials = rng.randn(num_nodes - 1, 4)

# 1) Build a factor graph using DENSE factors.
pairwise_fg = fg.PFactorGraph()
multi_variables = []
for i in range(num_nodes):
    multi_variable = pairwise_fg.create_multi_variable(2)
    multi_variable[0] = 0
    multi_variable[1] = var_log_potentials[i]
    multi_variables.append(multi_variable)


# random edge potentials
for i in range(1, num_nodes):
    var = multi_variables[i]
    parent = multi_variables[parents[i]]
    pairwise_fg.create_factor_dense([parent, var], edge_log_potentials[i - 1])

# If there are upper/lower bounds, add budget factors.
Пример #23
0
import itertools
import numpy as np
import matplotlib.pyplot as plt
import pdb

import ad3.factor_graph as fg

grid_size = 20
num_states = 5

factor_graph = fg.PFactorGraph()

multi_variables = []
random_grid = np.random.uniform(size=(grid_size, grid_size, num_states))
for i in xrange(grid_size):
    multi_variables.append([])
    for j in xrange(grid_size):
        new_variable = factor_graph.create_multi_variable(num_states)
        for state in xrange(num_states):
            new_variable.set_log_potential(state, random_grid[i, j, state])
        multi_variables[i].append(new_variable)

alpha = .3
potts_matrix = alpha * np.eye(num_states)
potts_potentials = potts_matrix.ravel().tolist()

for i, j in itertools.product(xrange(grid_size), repeat=2):
    if (j > 0):
        #horizontal edge
        edge_variables = [multi_variables[i][j - 1], multi_variables[i][j]]
        factor_graph.create_factor_dense(edge_variables, potts_potentials)
Пример #24
0
    value = np.random.uniform()
    if value < 0.4:
        bigram_positions.append(i)

# Decide whether each position counts for budget.
counts_for_budget = []
for i in xrange(length):
    value = np.random.uniform()
    if value < 0.1:
        counts_for_budget.append(False)
    else:
        counts_for_budget.append(True)


# 1) Build a factor graph using a SEQUENCE and a BUDGET factor.
factor_graph = fg.PFactorGraph()
multi_variables = []
for i in xrange(length):
    multi_variable = factor_graph.create_multi_variable(2)
    multi_variable.set_log_potential(0, 0.0)
    value = np.random.normal()
    multi_variable.set_log_potential(1, value)
    multi_variables.append(multi_variable)

edge_log_potentials = []
for i in xrange(length+1):
    if i == 0:
        num_previous_states = 1
    else:
        num_previous_states = 2
    if i == length:
Пример #25
0
import itertools
import numpy as np
import matplotlib.pyplot as plt
import pdb

import ad3.factor_graph as fg

grid_size = 10
num_states = 5
num_diverse_outputs = 4  # Number of diverse outputs to generate.
min_hamming_cost = 32  # Minimum Hamming cost between any pair of outputs.

factor_graph = fg.PFactorGraph()

description = ''
num_factors = 0

multi_variables = []
random_grid = np.random.uniform(size=(grid_size, grid_size, num_states))
for i in xrange(grid_size):
    multi_variables.append([])
    for j in xrange(grid_size):
        new_variable = factor_graph.create_multi_variable(num_states)
        for state in xrange(num_states):
            new_variable.set_log_potential(state, random_grid[i, j, state])
        multi_variables[i].append(new_variable)

alpha = .3
potts_matrix = alpha * np.eye(num_states)
potts_potentials = potts_matrix.ravel().tolist()
Пример #26
0
    if num_children > len(available_nodes):
        num_children = len(available_nodes)
    ind_children = np.random.permutation(len(available_nodes))[0:num_children]
    children = []
    for ind in ind_children:
        children.append(available_nodes[ind])
    for j in children:
        parents[j] = i
        nodes_to_process.insert(0, j)
        available_nodes.remove(j)        
#parents = range(-1, num_nodes-1)
print parents


# 1) Build a factor graph using DENSE factors.
pairwise_factor_graph = fg.PFactorGraph()
multi_variables = []
for i in xrange(num_nodes):
    multi_variable = pairwise_factor_graph.create_multi_variable(2)
    value = np.random.normal()
    multi_variable.set_log_potential(0, 0.0)
    multi_variable.set_log_potential(1, value)
    multi_variables.append(multi_variable)

description = ''
num_factors = 0

edge_log_potentials = []
edge_log_potentials.append([])
for i in xrange(1, num_nodes):
    p = parents[i]
def test_binary_variable():
    graph = fg.PFactorGraph()
    var = graph.create_binary_variable()
    var.set_log_potential(0.5)
    assert var.get_log_potential() == 0.5