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
示例#3
0
def nash_propagation(model,iterations,epsilon,tau,query_node=(),order = None):

"""  Perform initialization of variable to factor nodes 
"""
    for n in order:
        if(n.type.value==1):
            for neighbor in nx.all_neighbors(model,n):
                table = rv.Discrete(np.ones([10,10]),n,neighbor)
                model[n][neighbor]['object'].set_table(n, neighbor, table)
        if(n.type.value == 2):
            for neighbor in nx.all_neighbors(model, n):
                table = rv.Discrete(np.ones([10, 10]),n,neighbor)
                model[n][neighbor]['object'].set_table(n, neighbor, table)
    step =0
    grid={}
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 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)
示例#6
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)
示例#7
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 GetBeliefs(fg, ni, q):  #ni:= number of iterations, q:=query node
    for n in fg.get_vnodes(
    ):  #initializing v-t-f msgs with value 1 for all states.
        for f in nx.all_neighbors(fg, n):
            msg = rv.Discrete(np.array([1, 1]), n)
            SetMsg(fg, n, f, msg)

    for i in range(ni):  # below is the parallel message updating:
        fg.get_fnodes()
        for f in fg.get_fnodes(
        ):  # updating the factor-to-variable msgs given the current v-t-f
            for n in nx.all_neighbors(fg, f):
                SetMsg(fg, f, n, SumProd(fg, f, n).normalize())
        for n in fg.get_vnodes(
        ):  #updating the v-t-f msgs given the current f-t-v
            for f in nx.all_neighbors(fg, n):
                SetMsg(fg, n, f,
                       SumProd(fg, n, f).normalize())  # here we normalize

    return [[n, n.belief()] for n in q]
示例#9
0
from random import choice
import networkx as nx

# Create factor graph
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 = [[3, 4],
           [3, 9]]
fa = nodes.FNode("fa", rv.Discrete(dist_fa, x1, x2))

dist_fb = [[3, 4],
           [5, 1]]
fb = nodes.FNode("fb", rv.Discrete(dist_fb, x2, x3))

dist_fc = [[7, 8],
           [3, 9]]
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)