def make_debug_graph(num_nodes, graph_mat):
    # Create factor graph
    fg = graphs.FactorGraph()
    # Create variable nodes
    X = {}
    F = {}
    dist_fa = np.zeros([30, 2, 2])
    for k in range(30):
        dist_fa[k] = np.random.rand(2, 2)
    for i in range(num_nodes):
        X['x' + str(i + 1)] = nodes.VNode("x" + str(i + 1), rv.Discrete)

    fg.set_nodes(X.values())
    for i in range(len(graph_mat)):
        edge = graph_mat[i]
        nodez = [X["x" + str(edge[m])] for m in range(len(edge))]
        F['f' + str(i + 1)] = nodes.FNode("f" + str(i + 1),
                                          rv.Discrete(dist_fa[i], *nodez))
    fg.set_nodes(F.values())

    for i in range(len(graph_mat)):
        node_name = graph_mat[i]
        fg.set_edge(X['x' + str(node_name[0])], F['f' + str(i + 1)])
        fg.set_edge(F['f' + str(i + 1)], X['x' + str(node_name[1])])
    draw(fg, nx.circular_layout(fg))
    plt.show()
    print([attr["type"].value for (n, attr) in fg.nodes(data=True)])
    belief = inference.loopy_belief_propagation(
        fg, 1000, [*X.values()], order=[*F.values(), *X.values()])
    print(X['x1'].belief())
    print(X['x2'].belief())
    print(X['x3'].belief())
def make_debug_graph_new():
    fg = graphs.FactorGraph()
    x1 = nodes.VNode('x1', rv.Discrete)
    x2 = nodes.VNode('x2', rv.Discrete)
    x3 = nodes.VNode('x3', rv.Discrete)
    dist_fa = [[0.1, 0.7], [0.3, 0.2]]
    dist_f2 = [0.3, 0.7]
    f1 = nodes.FNode('f1', rv.Discrete(dist_f2, x1))
    f2 = nodes.FNode('f2', rv.Discrete(dist_fa, x1, x2))
    #f3 = nodes.FNode('f3', rv.Discrete(dist_fa, x1,x2 ))
    f4 = nodes.FNode('f4', rv.Discrete(dist_fa, x2, x3))
    print(f1.factor)
    fg.set_nodes([x1, x2, x3])
    fg.set_nodes([f1, f2, f4])
    # Add edges to factor graph
    fg.set_edge(f1, x1)
    fg.set_edge(x1, f2)
    fg.set_edge(f2, x2)
    #fg.set_edge(x2, f3)
    #fg.set_edge(f3, x1)
    fg.set_edge(x2, f4)
    fg.set_edge(x3, f4)
    draw(fg, nx.circular_layout(fg))
    plt.show()
    belief = inference.loopy_belief_propagation(fg,
                                                10, [x1, x2, x3],
                                                order=[f1, f2, f4, x1, x2, x3])
def make_debug_graph():

    # Create factor graph
    fg = graphs.FactorGraph()

    # Create variable nodes
    x1 = nodes.VNode("x1", rv.Discrete)
    x2 = nodes.VNode("x2", rv.Discrete)
    x3 = nodes.VNode("x3", rv.Discrete)
    x4 = nodes.VNode("x4", rv.Discrete)

    # Create factor nodes
    f12 = nodes.FNode("f12")
    f234 = nodes.FNode("f234")
    f3 = nodes.FNode("f3")
    f4 = nodes.FNode("f4")

    # Add nodes to factor graph
    fg.set_nodes([x1, x2, x3, x4])
    fg.set_nodes([f12, f234, f3, f4])

    # Add edges to factor graph
    fg.set_edge(x1, f12)
    fg.set_edge(f12, x2)
    fg.set_edge(x2, f234)
    fg.set_edge(f234, x3)
    fg.set_edge(f234, x4)
    fg.set_edge(x3, f3)
    fg.set_edge(x4, f4)

    #add potential for f_3: p(x3)
    dist_f3 = [0.5, 0.5]
    f3.factor = rv.Discrete(dist_f3, x3)

    #add potential for f_4: p(x4)
    dist_f4 = [0.4, 0.6]
    f4.factor = rv.Discrete(dist_f4, x4)

    # add potential for f_{234}: p(x2, x3, x4) = p(x2|x3,x4) p(x3,x4)
    px3x4 = np.outer(dist_f3, dist_f4)
    px3x4 = np.reshape(px3x4, np.shape(px3x4) + (1, ))
    px2_conditioned_x3x4 = [[
        [0.2, 0.8],
        [0.25, 0.75],
    ], [[0.7, 0.3], [0.3, 0.7]]]

    dist_f234 = px3x4 * px2_conditioned_x3x4
    f234.factor = rv.Discrete(dist_f234, x3, x4, x2)

    # add potential for f_{12}:  p (x1,x2) = p(x1 | x2) p(x2)
    px1_conditioned_x2 = [[0.5, 0.5], [0.7, 0.3]]
    px2 = np.sum(dist_f234, axis=(0, 1))
    dist_f12 = px2[:, np.newaxis] * px1_conditioned_x2
    f12.factor = rv.Discrete(dist_f12, x2, x1)

    #########_____________ PROBLEM 2_____________############
    fglib_beliefs = inference.belief_propagation(fg, query_node=x1)
    return fglib_beliefs, fg, x1
 def __call__(self, priorMean, priorVariance, userResponse):
 # Create factor graph
     fg = graphs.FactorGraph()
     
     # Create variable nodes
     x1 = nodes.VNode("x1", rv.Gaussian)
     x2 = nodes.VNode("x2", rv.Gaussian)
     
     # Create factor nodes (with joint distributions)
     priorMean = 3;
     priorVariance = 0.1;
     priorPrecision = 1/priorVariance;
     priorPrecisionMean = priorPrecision * priorMean;
     responsePrecision = 1/self.responseVariance;
     responsePrecisionMean = responsePrecision * userResponse;
     
     fa = nodes.FNode( "fa", rv.Gaussian.inf_form( [priorPrecision], [priorPrecisionMean], x1) )
     fb = nodes.FNode( "fb", rv.Gaussian.inf_form( [responsePrecision], [responsePrecisionMean], x1) )
     
     # Add nodes to factor graph
     fg.set_nodes([x1])
     fg.set_nodes([fa, fb])
     
     # Add edges to factor graph
     fg.set_edge(fa, x1)
     fg.set_edge(x1, fb)
     
     # Perform sum-product algorithm on factor graph
     # and request belief of variable node x4
     belief = inference.sum_product(fg, x1)
     
     # Print belief of variables
     #Belief of variable node x1
     variance = 1 / belief._W
     mean = belief._Wm / belief._W
     
     return [mean,variance]
     
     """The below will not work, because the procedure for 
     inverting the precision matrix checks that it has at 
     least 2 dimensions. Using the default constructor for 
     the Gaussian variable will not work for the same 
     reason.
     """
     #print("Belief of variable node x1:")
     #print(x1.belief())
     
     #print("Belief of variable node x1:")
     #print(x1.belief(normalize=True))
     
     #print("Unnormalized belief of variable node x1:")
     #print(x1.belief(normalize=False))
示例#5
0
def make_arbit_graph(num_nodes, graph_mat):
    # Create factor graph
    fg = graphs.FactorGraph()
    # Create variable nodes
    X = {}
    F = {}
    dist_fa = np.zeros([len(graph_mat), 2, 2])
    for k in range(len(graph_mat)):
        dist_fa[k] = np.random.rand(2, 2)
    for i in range(num_nodes):
        X['x' + str(i + 1)] = nodes.VNode("x" + str(i + 1), rv.Discrete, P)

    fg.set_nodes(X.values())
    for i in range(len(graph_mat)):
        edge = graph_mat[i]
        nodez = [X["x" + str(edge[m])] for m in range(len(edge))]
        F['f' + str(i + 1)] = nodes.FNode("f" + str(i + 1),
                                          rv.Discrete(dist_fa[i], *nodez))
    fg.set_nodes(F.values())

    for i in range(len(graph_mat)):
        node_name = graph_mat[i]
        fg.set_edge(X['x' + str(node_name[0])], F['f' + str(i + 1)])
        fg.set_edge(F['f' + str(i + 1)], X['x' + str(node_name[1])])

    print([attr["type"].value for (n, attr) in fg.nodes(data=True)])
    draw(fg, nx.spectral_layout(fg))
    plt.show()
    print([*F.values(), *X.values()])
    #belief = inference.loopy_belief_propagation(fg, 1000, [*X.values()], order=[*F.values(), *X.values()])
    grid = inference.nash_propagation(fg,
                                      10,
                                      epsilon,
                                      1 / 10, [*X.values()],
                                      order=[*F.values(), *X.values()])
    ## COmpute the mixed strategy
    prob = []
    prob_i = 0
    print(len(grid.keys()))
    length = 0
    for i in grid.keys():
        if (np.where(grid[str(i)] == 1) != []):
            length = length + 1

        prob_i = np.where(grid[str(i)] == 1)
        print('new')
        print(prob_i)
示例#6
0
def make_graph():
    G = graphs.FactorGraph()
    x1 = nodes.VNode('x1', rv.Discrete, P)
    x2 = nodes.VNode('x2', rv.Discrete, P)
    x3 = nodes.VNode('x3', rv.Discrete, P)
    x4 = nodes.VNode('x4', rv.Discrete, P)
    x5 = nodes.VNode('x5', rv.Discrete, P)
    dist_fa = np.array([[20, 10], [20, 80]])
    dist_fb = np.array([[40, 30], [30, 50]])
    dist_fc = np.array([[30, 50], [40, 30]])
    dist_fd = np.array([[70, 10], [10, 20]])
    dist_fe = np.array([[120, 50], [80, 100]])
    dist_ff = np.array([[40, 100], [70, 30]])
    dist_fg = np.array([[20, 10], [50, 30]])
    fa = nodes.FNode('f1', rv.Discrete(dist_fa, x1, x2))
    fb = nodes.FNode('f2', rv.Discrete(dist_fb, x2, x3))
    fc = nodes.FNode('f3', rv.Discrete(dist_fc, x3, x4))
    fd = nodes.FNode('f4', rv.Discrete(dist_fd, x4, x1))
    fe = nodes.FNode('f5', rv.Discrete(dist_fe, x4, x5))
    ff = nodes.FNode('f6', rv.Discrete(dist_ff, x5, x3))
    fg = nodes.FNode('f7', rv.Discrete(dist_fg, x1, x3))

    G.set_nodes([x1, x2, x3, x4, x5])
    G.set_nodes([fa, fb, fc, fd, fe, ff, fg])
    # Add edges to factor graph
    G.set_edge(x1, fa)
    G.set_edge(fa, x2)
    G.set_edge(x2, fb)
    G.set_edge(fb, x3)
    G.set_edge(x3, fc)
    G.set_edge(fc, x4)
    G.set_edge(x4, fd)
    G.set_edge(fd, x1)
    G.set_edge(fe, x4)
    G.set_edge(x5, fe)
    G.set_edge(ff, x5)
    G.set_edge(x3, ff)
    G.set_edge(fg, x1)
    G.set_edge(x3, fg)
    draw(G, nx.spectral_layout(G))
    plt.show()
    inference.nash_propagation(
        G,
        20,
        epsilon,
        1 / 30, [x1, x2, x3, x4, x5],
        order=[fa, fb, fc, fd, fe, ff, fg, x1, x2, x3, x4, x5])
def main():
    fg = graphs.FactorGraph()

    # Create variable nodes
    x1 = nodes.VNode("x1", rv.Discrete)  # with 2 states (Bernoulli)
    x2 = nodes.VNode("x2", rv.Discrete)  # with 3 states
    x3 = nodes.VNode("x3", rv.Discrete)
    x4 = nodes.VNode("x4", rv.Discrete)

    # Create factor nodes (with joint distributions)
    dist_fa = [[0.3, 0.2, 0.1],
               [0.3, 0.0, 0.1]]
    fa = nodes.FNode("fa", rv.Discrete(dist_fa, x1, x2))

    dist_fb = [[0.3, 0.2],
               [0.3, 0.0],
               [0.1, 0.1]]
    fb = nodes.FNode("fb", rv.Discrete(dist_fb, x2, x3))

    dist_fc = [[0.3, 0.2],
               [0.3, 0.0],
               [0.1, 0.1]]
    fc = nodes.FNode("fc", rv.Discrete(dist_fc, x2, x4))

    # Add nodes to factor graph
    fg.set_nodes([x1, x2, x3, x4])
    fg.set_nodes([fa, fb, fc])

    # Add edges to factor graph
    fg.set_edge(x1, fa)
    fg.set_edge(fa, x2)
    fg.set_edge(x2, fb)
    fg.set_edge(fb, x3)
    fg.set_edge(x2, fc)
    fg.set_edge(fc, x4)

    sum_product(fg)
示例#8
0
    length = 0
    for i in grid.keys():
        if (np.where(grid[str(i)] == 1) != []):
            length = length + 1

        prob_i = np.where(grid[str(i)] == 1)
        print('new')
        print(prob_i)

    ## Now assign values to the factors ?


Num_Of_Players = 50
max_degree = 5
epsilon = 0.26  ## To be tuned for every experiement
tau = epsilon / (np.power(2,
                          (max_degree + 1) * max_degree * np.log(max_degree)))
# Initialize tables for each Node in the graph
fg = graphs.FactorGraph()
P = np.ones([10, 10])

## Below create the links of the matrix
Mat_link = []
for i in range(1, 9):
    Mat_link.append((i, i % 9 + 1))
    Mat_link.append((i, np.random.randint(i + 1, 10)))

print(Mat_link)
#make_arbit_graph(10,graph_mat=Mat_link)
make_graph()