Exemplo n.º 1
0
def test_tree_validate():
    g = PFactorGraph()
    n_nodes = 4
    arcs = [(h, m) for m in range(1, n_nodes) for h in range(n_nodes)
            if h != m]
    arc_vars = [g.create_binary_variable() for _ in arcs]

    tree = PFactorTree()
    g.declare_factor(tree, arc_vars)

    with pytest.raises(TypeError):
        tree.initialize(n_nodes, [-3 for _ in arcs])

    with pytest.raises(TypeError):
        tree.initialize(n_nodes, None)

    with pytest.raises(TypeError):
        tree.initialize(n_nodes, 42)

    with pytest.raises(ValueError):
        tree.initialize(n_nodes, [(100, 100) for _ in arcs])

    with pytest.raises(ValueError):
        tree.initialize(n_nodes, arcs + arcs)

    with pytest.raises(ValueError):
        tree.initialize(n_nodes, arcs[:3])
Exemplo n.º 2
0
 def build_factor(self):
     n_nodes = self.n_nodes
     g = PFactorGraph()
     self.arcs = [(h, m) for m in range(1, n_nodes + 1)
                  for h in range(n_nodes + 1) if h != m]
     arc_vars = [g.create_binary_variable() for _ in self.arcs]
     tree = PFactorTreeFast()
     g.declare_factor(tree, arc_vars)
     tree.initialize(n_nodes + 1)
     return tree
Exemplo n.º 3
0
 def build_factor(self, n_arcs):
     g = PFactorGraph()
     n_nodes = self.n_nodes
     arcs = self.arcs
     if n_arcs != len(arcs):
         raise ValueError("expected input dim of {:d} but got {:d}".format(len(arcs), n_arcs))
     arc_vars = [g.create_binary_variable() for _ in arcs]
     tree = PFactorTreeFast()
     g.declare_factor(tree, arc_vars)
     tree.initialize(n_nodes + 1)
     return tree
Exemplo n.º 4
0
def test_tree_factor():
    n_nodes = 10
    rng = np.random.RandomState(0)
    g = PFactorGraph()
    arcs = [(h, m) for m in range(1, n_nodes) for h in range(n_nodes)
            if h != m]
    potentials = rng.uniform(0, 1, size=len(arcs))
    arc_vars = [g.create_binary_variable() for _ in arcs]

    for var, potential in zip(arc_vars, potentials):
        var.set_log_potential(potential)

    tree = PFactorTree()
    g.declare_factor(tree, arc_vars)
    tree.initialize(n_nodes, arcs)

    _, posteriors, _, _ = g.solve()
    chosen_arcs = [arc for arc, post in zip(arcs, posteriors)
                   if post > 0.99]

    # check that it's a tree
    selected_nodes = set(a for arc in chosen_arcs for a in arc)
    assert selected_nodes == set(range(n_nodes))

    marked = list(range(n_nodes))
    for h, t in chosen_arcs:
        assert marked[t] != marked[h]
        marked[t] = marked[h]
Exemplo n.º 5
0
        nodes_to_process.insert(0, j)
        available_nodes.remove(j)

print("Randomly picked tree:", parents)

# Design number of states for each node.
num_states = rng.randint(1, max_num_states + 1, size=num_nodes)
print("States per node:", num_states)

# generate random potentials
var_log_potentials = [rng.randn(n) for n in num_states]
edge_log_potentials = [rng.randn(num_states[parents[i]] * num_states[i])
                       for i in range(1, num_nodes)]

# 1) Build a factor graph using DENSE factors.
pairwise_fg = PFactorGraph()
multi_variables = []
for i in range(num_nodes):
    var = pairwise_fg.create_multi_variable(num_states[i])
    var.set_log_potentials(var_log_potentials[i])
    multi_variables.append(var)

description = ''
num_factors = 0

for i in range(1, num_nodes):
    p = parents[i]
    edge_variables = [multi_variables[p], multi_variables[i]]
    pairwise_fg.create_factor_dense(edge_variables,
                                    edge_log_potentials[i - 1])
    num_factors += 1
Exemplo n.º 6
0
rng = np.random.RandomState(1)

# Decide bigram_positions.
bigram_positions = []
for i in range(-1, length):
    value = rng.uniform()
    if value < 0.4:
        bigram_positions.append(i)

# Decide whether each position counts for budget.
counts_for_budget = rng.uniform(size=length) < 0.1

var_log_potentials = rng.randn(length)

# 1) Build a factor graph using a SEQUENCE and a BUDGET factor.
factor_graph = PFactorGraph()
multi_variables = []
for i in range(length):
    multi_variable = factor_graph.create_multi_variable(2)
    multi_variable[0] = 0
    multi_variable[1] = var_log_potentials[i]
    multi_variables.append(multi_variable)

# generate sequence log potentials
initials = np.zeros(2)
finals = np.zeros(2)
transitions = np.zeros((length - 1, 2, 2))
transitions[:, 1, 1] = rng.randn(length - 1)
edge_log_potentials = np.concatenate([initials,
                                      transitions.ravel(),
                                      finals])
Exemplo n.º 7
0
import os
import itertools
from time import time
import numpy as np

from ad3 import PFactorGraph
from ad3.extensions import PFactorSequence

plot = False if os.environ.get('NOPLOT') else True
if plot:
    import matplotlib.pyplot as plt

grid_size = 20
num_states = 5

factor_graph = PFactorGraph()

multi_variables = []
random_grid = np.random.uniform(size=(grid_size, grid_size, num_states))
for i in range(grid_size):
    multi_variables.append([])
    for j in range(grid_size):
        new_variable = factor_graph.create_multi_variable(num_states)
        for state in range(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()
Exemplo n.º 8
0
print("Randomly picked tree:", parents)

# Design number of states for each node.
num_states = rng.randint(1, max_num_states + 1, size=num_nodes)
print("States per node:", num_states)

# generate random potentials
var_log_potentials = [rng.randn(n) for n in num_states]
edge_log_potentials = [
    rng.randn(num_states[parents[i]] * num_states[i])
    for i in range(1, num_nodes)
]

# 1) Build a factor graph using DENSE factors.
pairwise_fg = PFactorGraph()
multi_variables = []
for i in range(num_nodes):
    var = pairwise_fg.create_multi_variable(num_states[i])
    var.set_log_potentials(var_log_potentials[i])
    multi_variables.append(var)

description = ''
num_factors = 0

for i in range(1, num_nodes):
    p = parents[i]
    edge_variables = [multi_variables[p], multi_variables[i]]
    pairwise_fg.create_factor_dense(edge_variables, edge_log_potentials[i - 1])
    num_factors += 1
Exemplo n.º 9
0
import os
import itertools
from time import time
import numpy as np

from ad3 import PFactorGraph
from ad3.extensions import PFactorSequence

plot = False if os.environ.get('NOPLOT') else True
if plot:
    import matplotlib.pyplot as plt

grid_size = 20
num_states = 5

factor_graph = PFactorGraph()

multi_variables = []
random_grid = np.random.uniform(size=(grid_size, grid_size, num_states))
for i in range(grid_size):
    multi_variables.append([])
    for j in range(grid_size):
        new_variable = factor_graph.create_multi_variable(num_states)
        for state in range(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()
Exemplo n.º 10
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 = 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.