Exemplo n.º 1
0
 def getRTTGraph(self):
     graph = Graph(self.conf.getNumNodes());
     for i, node1 in enumerate(self.nodes):
         for j, node2 in enumerate(self.nodes):
             rtt = getNorm(getVet(node1, node2))
             graph.addVertex(i, j, rtt)
     return graph
Exemplo n.º 2
0
def PathTestMashUp(startPt, endPt, targetDis):

    startCor = GeoCode(startPt);
    endCor = GeoCode(endPt)
    
    miniGraph = Graph()
    bounds = createMiniWorld(miniGraph, startCor, endCor)
    
    startNode = [0, 0]
    dist = miniGraph.findNearestNode(startCor, startNode)
    print 'the closest node found to startPt is '+ str(startNode) +', with dist '+str(dist)
    endNode = [0, 0]
    dist = miniGraph.findNearestNode(endCor, endNode)
    print 'the closest node found to endPt is '+str(endNode) +', with dist '+str(dist)
    
    startNode = cor2ID(startNode)
    endNode = cor2ID(endNode)
   
    myPath = miniGraph.MonteCarloBestPath(startNode, endNode, targetDis)
    
    print 'The actual path dis is '+ str(myPath['dist'])
    return {'miniGraph': miniGraph, 
            'startPt':startCor, 
            'endPt':endCor, 
            'startNode':startNode,
            'endNode':endNode,
            'dist': myPath['dist'],
            'path': myPath['path']}
Exemplo n.º 3
0
def PathTestMashUp(startPt, endPt, runDis, ):

    startCor = GeoCode(startPt);
    endCor = GeoCode(endPt)
    
    miniGraph = Graph()
    bounds = createMiniWorld(miniGraph, startCor, endCor)
    
    startNode = [0, 0]
    dist = miniGraph.findNearestNode(startCor, startNode)
    print 'the closest node found to startPt is '+ str(startNode) +', with dist '+str(dist)
    endNode = [0, 0]
    dist = miniGraph.findNearestNode(endCor, endNode)
    print 'the closest node found to endPt is '+str(endNode) +', with dist '+str(dist)
    
    startNode = cor2ID(startNode)
    endNode = cor2ID(endNode)
    K=5
    pathDict = miniGraph.findPath(startNode, endNode, runDis, K)
    for k in range(0, K):
        print 'The actual path dis is '+ str(pathDict[k]['cost'])
        #print pathDict[k]['path']
    return {'miniGraph': miniGraph, 
            'startPt':startCor, 
            'endPt':endCor, 
            'startNode':startNode,
            'endNode':endNode,
            'pathDict':pathDict}
 def __init__(self, vs, k, p):
     Graph.__init__(self, vs, [])
     self.add_regular_edges(k)
     self.rewire(p)
     self.assign_edge_lengths()
     self.clust = self.clustering_coefficient()
     self.length = self.average_length()
Exemplo n.º 5
0
 def NewGraph(self, Directed=1, Euclidean=1, IntegerVertexWeights=0, VertexWeights='None',
              IntegerEdgeWeights=0, EdgeWeights='One', Grid=1):
     if self.dirty == 1:
         if not askokcancel("New Graph","Graph changed since last saved. Do you want to overwrite it?"):
             return
     G=None
     self.SetGraphMenuDirected(Directed)
     self.SetGraphMenuEuclidean(Euclidean)
     self.SetGraphMenuIntegerVertexWeights(IntegerVertexWeights)
     self.SetGraphMenuVertexWeights(VertexWeights)
     self.SetGraphMenuIntegerEdgeWeights(IntegerEdgeWeights)
     self.SetGraphMenuEdgeWeights(EdgeWeights)
     self.SetGraphMenuGrid(Grid)
     self.defaultButton.select()
     
     G = Graph()
     G.directed = Directed
     G.euclidian = Euclidean
     self.graphName = "New"
     self.ShowGraph(G,self.graphName)
     self.RegisterGraphInformer(WeightedGraphInformer(G,"weight"))
     self.fileName = None
     self.makeDirty()
     self.dirty = 0
     self.SetTitle("Gred %s - New Graph" % gatoVersion)
def buildGraph(wordFile):
    # algorithm connects words (vertices) by placing them in a bucket whose name is a (wildcard)+string of letters(n-1)...
    # ... that way only one letter varies 
    bucketDictionary = {}
    # create the graph
    g = Graph()
    fileObject = open(wordFile)
    
    # create buckets of words that differ by a letter
    for line in fileObject:
        word = line[:-1]            # strip off '\n' character
        for index in range(len(word)):
            # _ indicates the wildcard character
            bucket = word[:index] + '_' + word[index+1:]
            # check if bucket has already been created..
            # yes..-> append the word to the correct bucket
            if bucket in bucketDictionary:
                bucketDictionary[bucket].append(word)
            else:
                bucketDictionary[bucket]= [word]
            
    # connect words in a bucket by creating an edge between them
    for bucket in bucketDictionary.keys():
        for word1 in bucket:
            for word2 in bucket:
                # do not check for one way relationship because this is a non-directed graph
                if word1 != word2:
                    # add edge method creates vertices if they do not already exist
                    g.addEdge(word1, word2, 0)
    
    fileObject.close()
    return g                
Exemplo n.º 7
0
def parseGraphFromFile(fileName):
    file = open(fileName, 'r')
    line = file.readline()
    
    graph = Graph()
    # take out any extra whitespace, such as 1   $  2  , 3...
    line = re.sub("\s*", "", line)
    # partition returns a 3-tuple of the string before the
    # specified delimiter, the delimiter, and the string after
    # the delimiter
    parts = line.partition('$')
    # the first part contains the list of nodes
    # add each node to the graph
    numNodes = parts[0]
    for i in range(int(numNodes)):
        graph.addNode()

    # each edge has the form node1, node2, cost
    edgeList = parts[2].split(';')
    for edge in edgeList:
        n1, n2, cost = edge.split(',')
        n1 = int(n1)
        n2 = int(n2)
        cost = int(cost)
        graph.addEdge(n1, n2, cost)
        
    return graph
Exemplo n.º 8
0
 def test_add_edge(self):
     graph1 = Graph("Graphec")
     graph1.add_edge("A", "B")
     self.assertEqual(graph1.Nodes["A"].name, "A")
     self.assertEqual(graph1.Nodes["B"].name, "B")
     self.assertEqual(graph1.Edges[0].froms, graph1.Nodes["A"])
     self.assertEqual(graph1.Edges[0].to, graph1.Nodes["B"])
Exemplo n.º 9
0
 def addEdge(u, v, weight):
     Graph.addEdge(u, v);
     queues[u].add(WeightedEdge(u, v, weight))
     n = [u, v, weight]
     self.edges.append([])
     for i in n:
         self.edges[len(self.edges) - 1].append(i)
Exemplo n.º 10
0
def repaint():
    canvas.delete("point")
    
    if len(circles) == 0: return # Nothing to paint

    # Build the edges
    edges = []
    for i in range(len(circles)):
        for j in range(i + 1, len(circles)):
            if distance(circles[i], circles[j]) <= 2 * radius:
                edges.append([i, j])
                edges.append([j, i])

    graph = Graph(circles, edges)
    tree = graph.dfs(0)
    isAllCirclesConnected = \
        len(circles) == tree.getNumberOfVerticesFound()

    for [x, y] in circles:
        if isAllCirclesConnected: # All circles are connected
            canvas.create_oval(x - radius, y - radius, x + radius, 
                y + radius, fill = "red", tags = "point")
        else:
            canvas.create_oval(x - radius, y - radius, x + radius, 
                y + radius, tags = "point")            
Exemplo n.º 11
0
def main(script, n='5', *args):

    # create n Vertices
    n = int(n)
    #labels = string.ascii_lowercase + string.ascii_uppercase
    #vs = [Vertex(c) for c in labels[:n]]

    v = Vertex('v')
    v.pos = (1110,-100)

    w = Vertex('w')
    w.pos = (20000,40)

    x = Vertex('x')
    x.pos = (100,-2000)

    y = Vertex('y')
    y.pos = (-15,15000)

    # create a graph and a layout
    g = Graph([v, w, x, y])
    g.add_all_edges()
    # layout = CircleLayout(g)
    # layout = RandomLayout(g)
    layout = CartesianLayout(g)

    # draw the graph
    gw = GraphWorld()
    gw.show_graph(g, layout)
    gw.mainloop()
Exemplo n.º 12
0
class GraphTest(unittest.TestCase):

    def setUp(self):
        self.v = Vertex('v')
        self.w = Vertex('w')
        self.x = Vertex('x')
        self.y = Vertex('y')
        self.z = Vertex('z')
        self.e = Edge(self.v, self.w)
        self.e2 = Edge(self.v, self.x)
        self.g = Graph([self.v, self.w ,self.x, self.y],[self.e, self.e2])

    def test_get_edge_not_exist(self):
        edge = self.g.get_edge(self.v, self.y)
        self.assertIsNone(edge)

    def test_get_edge_exist(self):
        edge = self.g.get_edge(self.v, self.w)
        self.assertEqual(edge, self.e)

    def test_remove_edge_is_removed( self ):
        '''
        La prueba checa si el Edge esta por ahi.

        Depende de la funcion de get_edge
        '''
        edge = self.g.remove_edge( self.e )
        self.assertIsNone( self.g.get_edge( self.v, self.w ) )
Exemplo n.º 13
0
 def bfs(self):
     self.lines = True
     graph = Graph(self.point, self.edge)
     bfs = graph.bfs(eval(self.v1.get()))
     order = bfs.getSearchOrders()
     for i in range( 1, len(order)):
         parent = bfs.getParent(i)
         self.canvas.create_line(self.node[parent][0], self.node[parent][1], self.node[order[i]][0], self.node[order[i]][1], arrow = LAST, fill = "red")
Exemplo n.º 14
0
  def test_add_vertex(self):
    g = Graph()
    # Tests that a label is used only once.
    g.add_vertex(Vertex('label1'))
    g.add_vertex(Vertex('label2'))
    g.add_vertex(Vertex('label2'))

    self.assertEqual(g, {Vertex('label1'):{}, Vertex('label2'):{}})
Exemplo n.º 15
0
def create_Graph_from_file(file_name):
    graph = Graph()
    with open(file_name) as inputfile:
        next(inputfile)
        for line in inputfile:
            print line
            graph.add_node_to_Graph(line)
    return graph
Exemplo n.º 16
0
    def __init__(self):
        edges = getEdges()

        # Create a graph
        vertices = [x for x in range(NUMBER_OF_NODES)]
        graph = Graph(vertices, edges)

        # Obtain a BSF tree rooted at the target node
        self.tree = graph.bfs(511)
Exemplo n.º 17
0
def main(script, n='5', p='0.5', *args):
    import string
    n=int(n)
    p=float(p)
    labels = string.ascii_lowercase + string.ascii_uppercase
    vs = [Vertex(c) for c in labels[:n]]
    g = Graph(vs)
    g.add_random_edges(p)
    print(g)
Exemplo n.º 18
0
def buildgraph(rows):
	g = Graph(len(rows))
	for node in range(len(rows)):
		arr = rows[node].strip().split(" ")
		rtts = [float(x) for x in arr if len(x) > 0]
		for neighbor in range(len(rtts)):
			g.addVertex(node,neighbor,rtts[neighbor])
	
	return g
Exemplo n.º 19
0
    def test_get_edge(self):

        v = Vertex(1)
        v2 = Vertex(2)
        e = Edge(v, v2)

        g = Graph(vs=[v,v2], es=[e])

        self.assertEqual(g.get_edge(v, v), None)
        self.assertEqual(g.get_edge(v, v2), e)
Exemplo n.º 20
0
def randomTree(n):
    """
    constructs a random tree by sequentially adding new edges to a random
    vertex already part of the tree
    """
    G = Graph(V=[0], E=[])
    for i in range(1, n):
        G.add_edge((choice(G.V), i))
        G.add_vertex(i)
    return G
Exemplo n.º 21
0
class testGraph(unittest.TestCase):
  
    def setUp(self):
        self.graph = Graph()
    
    # @unittest.skip("jeszcze nie mamb")
    def testCreateSpecyficGraphFromFile(self):
        readFromFileMock = mock.Mock(return_value = """ 
            0 1 3\n
            0 4 3\n
            1 2 1\n
            2 3 3\n
            2 5 1\n
            3 1 3\n
            4 5 2\n
            5 3 1\n
            5 1 6""") #zakladanie werifikatora
        readFromFileMock("testGraf.txt") #gen
        readFromFileMock.assert_called_once_with("testGraf.txt") #sciaganie werifikatora
        self.graph.createGraphFromStr(readFromFileMock.return_value)
        self.assertEqual(6, self.graph.getNumberOfVertex())
        self.assertEqual(9, self.graph.getNumberOfEdges())

    # @unittest.skip("jeszcze nie mamb")
    def testAddEdge(self):
        s = [1, 2, 3]
        self.graph.addEdge(s)
        self.assertEqual([1], self.graph.getVertex())
        self.assertEqual([[2]], self.graph.getConnectFromVertex(1))
        self.assertEqual([3], self.graph.getEdgeFromVToVx(1, 2))
Exemplo n.º 22
0
def main():
	rows = read_file()
	orders = {}

	for row in rows:
		if row['Order__c'] not in orders:
			orders[row['Order__c']] = []
		orders[row['Order__c']].append({'Id': row['Id'], 'Shipper':row['Revenova_Shipper__c'],'Consignee':row['Revenova_Consignee__c'],'Carrier':row['Carrier__c']})

	for name in orders:
		try:
			graph = Graph()
			for load in orders[name]:
				shipper = str(load['Shipper'])
				consignee = str(load['Consignee'])
				graph.addVertex(shipper,{'ship':load['Id']})
				graph.addVertex(consignee,{'cons':load['Id']})
				graph.addEdge(shipper, consignee, str(load['Carrier']))

			custResults[name] = graph.flattenCustomerLoads()
			carrResults[name] = graph.flattenCarrierLoads()

		except RuntimeError:
			errors.append(name)
			print 'Recursion Error'

	print 'Successes: '+str(len(orders))
	print 'Errors: '+str(len(errors))

	custLoads = [{'Order':n, 'Shipper':i['Shipper'], 'Consignee':i['Consignee']} for n in custResults for i in custResults[n]]
	write_file(custLoads,'cust-loads.csv')

	carrLoads = [{'Order':n, 'Shipper':i['Shipper'], 'Consignee':i['Consignee'], 'Carrier':i['Carrier']} for n in carrResults for i in carrResults[n]]
	write_file(carrLoads,'carr-loads.csv')
Exemplo n.º 23
0
def erdos_renyi(n, p=1/2):
    """
    constructs erdos-renyi random graph on n vertices with probability p
    (default p=1/2)
    """
    G = Graph(V=range(n), E=[], normalize=False)
    for i in G.V:
        for j in G.V:
            if i < j and random() < p:
                G.add_edge((i, j))
    return G
Exemplo n.º 24
0
def main(script, n='10', *args):

    six_letters = [c for c in string.ascii_lowercase][:6]
    vertices = [Vertex(l) for l in six_letters]
    g = Graph(vertices, [])
    g.add_regular_edges()
    layout = CircleLayout(g)

    # draw the graph
    gw = GraphWorld()
    gw.show_graph(g, layout)
    gw.mainloop()
Exemplo n.º 25
0
    def test_remove_edge(self):

        v = Vertex(1)
        v2 = Vertex(2)
        e = Edge(v, v2)

        g = Graph(vs=[v, v2], es=[e])

        g.remove_edge(e)

        self.assertEqual(g[v], {})
        self.assertEqual(g[v2], {})
def buildKnightTourGraph(boardSize):
    ktGraph = Graph()
    for row in range(boardSize):
        for column in range(boardSize):
            nodeID = positionToNodeID(row, column, boardSize)
            newPositions = generateLegalMoves(row, column, boardSize)
            for moveVector in newPositions:
                # create edges between current node and all it's possible move combinations
                validMoveID = positionToNodeID(moveVector[0], moveVector[1], boardSize)
                # creates the nodes for us
                ktGraph.addEdge(nodeID, validMoveID, 0)
    return ktGraph
Exemplo n.º 27
0
    def test_add_vertex(self):
        v1 = Vertex('1')
        v2 = Vertex('2')
        v3 = Vertex('3')

        g = Graph(vs=[v1, v2])
        self.assertTrue(v1 in g)
        self.assertTrue(v2 in g)

        g.add_vertex(v3)

        self.assertTrue(v3 in g)
Exemplo n.º 28
0
    def test_list_vertices(self):

        v = Vertex(1)
        v2 = Vertex(2)
        v3 = Vertex(3)

        g = Graph(vs=[v, v2, v3], es=[])

        vertices = g.vertices()

        self.assertTrue(v in vertices)
        self.assertTrue(v2 in vertices)
        self.assertTrue(v3 in vertices)
Exemplo n.º 29
0
    def test_add_all_edges(self):

        v = Vertex(1)
        v2 = Vertex(2)

        g = Graph([v, v2])

        self.assertEqual(g.edges(), [])

        g.add_all_edges()

        self.assertEqual(g[v][v2], Edge(v2, v))
        self.assertEqual(g[v2][v], Edge(v2, v))
Exemplo n.º 30
0
    def __init__(self, newickStr, afTrait=None, translate=None, debug=False):
        Graph.__init__(self)

        self.newickStr = newickStr
        self.translateMap = translate

        # Initialise dictionary for recording ancestral
        # sequence fragment information
        self.afTrait = afTrait
        if afTrait != None:
            self.ancestralFragments = {}

        self.doParse(debug=debug)
Exemplo n.º 31
0
    user = user.split(';')
    user[1] = user[1].split(',')
    users_.append({
        "id": count,
        "mome": user[0],
        "latitude": float(user[1][0]),
        "longitude": float(user[1][1]),
        "profissao": user[2],
        "disponibilidade": user[3]
    })
    count += 1

users = users_[:]
del users_, count

graph = Graph(len(users))
for user in users:
    for user_ in users:
        if (user['id'] is not user_['id']):
            user_['dist'] = distanceCalc(user['latitude'], user['longitude'],
                                         user_['latitude'], user_['longitude'])
            graph.GRAPHInsert(user, user_)

print("\n********************************")
print("********** PROJETO 02 **********")
print("**********   FINDER   **********")
print("********************************")

lat = -15.836073
lng = -47.912019
print(f"\nLatitude atual {lat} \nLongitude atual {lng}")
Exemplo n.º 32
0
"""
This contains some sample code showing how to work with my Graph class
"""

from Graph import Graph



g1 = Graph(5, ['A', 'B', 'C', 'D', 'E'])

g1.addEdge(0, 1, 25)    # Edge from A to B
g1.addEdge(0, 2, 12)    # Edge from A to C
g1.addEdge(1, 3, 16)    # Edge from B to D
g1.addEdge(1, 4, 22)    # Edge from B to E
g1.addEdge(2, 4, 31)    # Edge from C to E
g1.addEdge(2, 3, 10)    # Edge from C to D


print(g1.adjList)

print("A's neighbors:", g1.getNeighbors(0))
print("Are A and C adjacent?", g1.areNeighbors(0, 2))
print("Weight between C and E:", g1.getWeight(2, 4))
print("Size:", g1.getSize())
print("GetData:", g1.getData(4))
print("Index for B:", g1.findNode('B'))
print("Vertices:", g1.getVertices())

g1.removeEdge(1, 4)
print("Are B and E neighbors?", g1.areNeighbors(1, 4))
print(g1.adjList)
Exemplo n.º 33
0
from Graph import Graph
from Node import Node
from Queue import Queue
#import random

graph = Graph()

node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node6 = Node(6)
node7 = Node(7)
node8 = Node(8)

node1.addNeighbor(node2)
node1.addNeighbor(node3)

node2.addNeighbor(node4)

node3.addNeighbor(node4)
node3.addNeighbor(node5)

node4.addNeighbor(node6)

node5.addNeighbor(node6)

node7.addNeighbor(node8)

node8.addNeighbor(node7)
Exemplo n.º 34
0
    for u in g.vertices:
        if u not in seen:
            dfs(g, u)

    gt = transpose(g)
    seen = set()
    conns = []
    for u in verts:
        if u not in seen:
            conns.append([])
            dfs_gt(gt, u)
    return conns


if __name__ == '__main__':
    g = Graph()
    g.add_edges_from([('a', 'b'), ('a', 'c'), ('b', 'c'), ('b', 'd'),
                      ('e', 'f'), ('e', 'g'), ('h', 'i')])
    g.add_vertex('j')
    print(f'connected: {is_connected(g)}')
    # print(connected_components_dj(g))
    print(connected_components(g))
    assert connected_components(g) == [['a', 'b', 'c', 'd'], ['e', 'f', 'g'], ['h', 'i'], ['j']]

    g = Graph()  # clrs Figure B.2(b)
    g.add_edges_from([(1, 2), (1, 5), (2, 5), (3, 6)])
    g.add_vertex(4)
    print(f'connected: {is_connected(g)}')
    # print(connected_components_dj(g))
    print(connected_components(g))
    print(connected_components_bfs(g))
Exemplo n.º 35
0
                    b = stack.pop()
                    b.f = time
                    b.color = 'black'


# Display result of DFS
def display(G):
    for v in G.V:
        s = str(v.id) + ": " + str(v.d) + " " + str(v.f)
        print(s)


if __name__ == '__main__':

    # Road network example from the lecture
    G = Graph()
    # Create vertices
    for i in range(0, 27):
        G.add_node()
    # Create horizontal edges
    G.add_edge_using_ids(0, 1)
    G.add_edge_using_ids(1, 2)
    G.add_edge_using_ids(2, 3)
    G.add_edge_using_ids(3, 4)
    G.add_edge_using_ids(4, 5)
    G.add_edge_using_ids(6, 7)
    G.add_edge_using_ids(7, 8)
    G.add_edge_using_ids(9, 10)
    G.add_edge_using_ids(10, 11)
    G.add_edge_using_ids(11, 12)
    G.add_edge_using_ids(13, 14)
from Graph import Graph as g
import sys

path = sys.argv[1]
f = open(path, "r")
vertices, edges, startNode = f.readline().split(" ")
vertices = int(vertices)
edges = int(edges)
startNode = int(startNode)
graph = {}
for j in range(1, vertices + 1):
    graph[j] = {}
for j in range(1, edges + 1):
    start, end, weight = f.readline().split(" ")
    start = int(start)
    end = int(end)
    weight = int(weight)
    graph[start][end] = weight
f.close()


def utils(dictionary, start):
    newline = "\n"
    result = ""
    for keys in dictionary:
        result += str(keys) + " " + str(dictionary[keys]) + newline
    return result


print(utils(g.Graph(graph).Dijkstra(startNode), startNode))
Exemplo n.º 37
0
from Graph import Graph
from networkx_adapter import *

'''

    Alunos: Draylon Lopes e Victor Bernardes

'''


grafo = Graph("Questao 1",True)
#pos = {0: (0, 1), 1: (1, 1), 2: (2,0), 3: (2, 2),4:(3,1),5:(4,1),6:(5,1)}
s = grafo.add_node("S",position=(0,1))
v1 = grafo.add_node("V1",position=(1,1))
v2 = grafo.add_node("V2",position=(2,0))
v3 = grafo.add_node("V3",position=(2,2))
v4 = grafo.add_node("V4",position=(3,1))
v5 = grafo.add_node("V5",position=(4,1))
t = grafo.add_node("T",position=(5,1))

grafo.add_edge(s, v1,'8/8',8,0)

grafo.add_edge(s, v2,'5/4',5,0)
grafo.add_edge(v1, v2,'10/2',10,0)

grafo.add_edge(s, v3,'10/3',10,0)
grafo.add_edge(v1, v3,'3/3',3,0)

grafo.add_edge(v1, v4,'5/3',5,0)
grafo.add_edge(v2, v4,'3/0',3,0)
grafo.add_edge(v3, v4,'5/3',5,0)
Exemplo n.º 38
0
def test_bfs():
    arr = [0, 1, 2, 3, 4, 5, 6, 7, 8]
    g = Graph(arr)
    g.add_edge(0, 1)
    g.add_edge(1, 2)
    g.add_edge(1, 3)
    g.add_edge(2, 4)
    g.add_edge(2, 3)
    g.add_edge(3, 5)
    g.add_edge(5, 6)
    g.add_edge(5, 7)
    g.add_edge(6, 8)

    g.bfs(0)
Exemplo n.º 39
0
# Create an edge list for graph in Figure 16.1
edges = [
    [0, 1], [0, 3], [0, 5],
    [1, 0], [1, 2], [1, 3],
    [2, 1], [2, 3], [2, 4], [2, 10],
    [3, 0], [3, 1], [3, 2], [3, 4], [3, 5],
    [4, 2], [4, 3], [4, 5], [4, 7], [4, 8], [4, 10],
    [5, 0], [5, 3], [5, 4], [5, 6], [5, 7],
    [6, 5], [6, 7],
    [7, 4], [7, 5], [7, 6], [7, 8],
    [8, 4], [8, 7], [8, 9], [8, 10], [8, 11],
    [9, 8], [9, 11],
    [10, 2], [10, 4], [10, 8], [10, 11],
    [11, 8], [11, 9], [11, 10]
  ]

graph = Graph(vertices, edges)
bfs = graph.bfs(graph.getIndex("Chicago")) 

searchOrders = bfs.getSearchOrders()
print(str(bfs.getNumberOfVerticesFound()) +
    " vertices are searched in this order:")
for i in range(len(searchOrders)):
    print(graph.getVertex(searchOrders[i]), end = " ")
print()

for i in range(len(searchOrders)):
    if bfs.getParent(i) != -1:
        print("parent of " + graph.getVertex(i) + 
          " is " + graph.getVertex(bfs.getParent(i)))
Exemplo n.º 40
0
    while not stack.is_empty():
        current_node = stack.pop()
        temp = g.array[current_node].head_node
        while temp is not None:
            if not visited[temp.data]:
                stack.push(temp.data)
                visited[temp.data] = True
                vertices_reached += 1
            temp = temp.next_element

    return vertices_reached + 1


def find_mother_vertex(g):

    for vertex in range(g.vertices):
        num_of_vertices_reached = dfs(g, vertex)
        if num_of_vertices_reached == g.vertices:
            return vertex
    return -1


if __name__ == "__main__":

    g = Graph(4)
    g.add_edge(0, 1)
    g.add_edge(1, 2)
    g.add_edge(3, 0)
    g.add_edge(3, 1)
    print(find_mother_vertex(g))
    pass
Exemplo n.º 41
0
pol5 = Cl.Politica(5)
pol6 = Cl.Politica(6)
pol7 = Cl.Politica(7)

# Lista de Politicas
pols = [pol0, pol1, pol2, pol3, pol4, pol5, pol6, pol7]
# for i in pols:
#     print(i)

# print("Pols listas")

for n in range(Nsimul):
    # Grafo de la vecindad entre agentes
    #G1 = Gr.Complete_Graph(N)
    p = 0.5
    G1 = Gr.Random_Graph(N, p)
    # G1 = Gr.Regular_Graph(N, 2)
    # G1 = Gr.Scale_Free_Graph() # Aun no
    # p = 0.5
    # G1 = Gr.Small_World_Graph(N, p)
    # G1 = Gr.Ring_Graph(N)
    # G1 = Gr.Star_Graph(N)
    # G1 = Gr.Wheel_Graph(N, 2)

    G1.generate_edges()
    # print(G1)

    # Generar txts (archivos que describen la red
    G1.generate_txts()

    # Crear N agentes
Exemplo n.º 42
0
class PlateauDeJeu(object):
    """ Classe representant le plateau du jeu des aventuriers du rail """
    def __init__(self, joueur1, joueur2):
        """
        initialise le plateau de jeu et ses 2 joueur, dont les attribut sont:
        :self.graph: initialise un graph pour le faire correspondre a la map du plateau
        :self.carte_wagon_visibles: initialise les carte wagon face visible
        :self.pioche_carte_wagon: init la pile de carte wagon a piocher
        :self.pioche_carte_destination: init la pile de carte destination
        :self.joueur1: j1 passer en argument passe en attribut du plateau
        :self.joueur2: pareil que pour j1
        """
        self.map = Graph()
        self.map.open_graph()
        self.construction = Graph()
        self.construction.nodes = self.map.nodes
        self.construction_possible = []
        self.cartes_wagon_visibles = []
        self.pioche_carte_wagon = PiocheCartesWagon()
        self.pioche_carte_destination = PiocheCarteDestination()
        self.joueur1 = joueur1
        self.joueur2 = joueur2

        #def des attributs aux joueurs
        self.joueur1.plateau_de_jeu = self
        self.joueur2.plateau_de_jeu = self
        self.joueur1.adversaire = joueur2
        self.joueur2.adversaire = joueur1

        # On ajoute les cartes wagons visibles
        for dummy_i in range(5):
            self.cartes_wagon_visibles.append(
                self.pioche_carte_wagon.piocher())

        # On fait la liste des constructions de route possible
        for edge in self.map.edges:
            self.construction_possible.append((edge[0], edge[1]))

    def finir_partie(self):
        """ Fini la partie, calcule le score du gagnant et l'affiche """
        score_joueur_1 = self.joueur1.calculer_score_finale()
        score_joueur_2 = self.joueur2.calculer_score_finale()

        if score_joueur_1 > score_joueur_2:
            print("Le joueur 1 a gagne la partie !!! :)")
        elif score_joueur_1 < score_joueur_2:
            print("Le joueur 2 a gagne la partie !!! :)")
        else:
            print("Vous etes arrive a egalite !!!!")

    def piocher_cartes_wagon(self, indice_1, indice_2):

        carte_1 = self.cartes_wagon_visibles.pop(indice_1)
        carte_2 = self.cartes_wagon_visibles.pop(indice_2 - 1)

        self.cartes_wagon_visibles.append(self.pioche_carte_wagon.piocher())
        self.cartes_wagon_visibles.append(self.pioche_carte_wagon.piocher())

        return carte_1, carte_2

    def jouer(self):
        """ Lance la partie de jeu """

        #Les joueurs piochent 4 cartes wagons et 3 cartes destinations
        for dummy_i in range(4):
            self.joueur1.cartes_wagons.append(
                self.pioche_carte_wagon.piocher())
            self.joueur2.cartes_wagons.append(
                self.pioche_carte_wagon.piocher())

        for dummy_i in range(3):
            self.joueur1.cartes_destinations.append(
                self.pioche_carte_destination.piocher())
            self.joueur2.cartes_destinations.append(
                self.pioche_carte_destination.piocher())

        #On lance le tour du premier joueur
        self.joueur1.jouer()
Exemplo n.º 43
0
  def processVertexEarly(self, s):
    #print "Discovered vertex ", s
    return
    
  def processVertexLate(self, s):
    return
  
  def processEdge(self,s, n):
    #print "Processed Edge ", s, " -> ", n
    return

if __name__ == '__main__':
  inputFile = sys.argv[1]
  sourceId = int(sys.argv[2])
  g = Graph(inputFile)
  b = BreadthFirstSearch(g, sourceId)
  
  for vid in g.getVertexIds():
    print sourceId, "to", vid, ":", 
    if b.hasPathTo(vid):
      print b.pathTo(vid)
  
  print ""
  
  if b.getCount() == g.getNoOfVertices():
    print "connected"
  else:
    print "NOT connected"
  
Exemplo n.º 44
0
from Graph import Graph
from Node import Node

from BFS import BFS
from DFS import DFS
from AStar import AStar
from UCS import UCS

from time import time
from math import sqrt

if __name__ == "__main__":
    print("Enter the grid size: ")
    N = int(input())
    G = Graph(N)

    print("Enter initial state: ")
    init_state = list()
    for _ in range(int(sqrt(N + 1))):
        init_state.append(list(map(int, input().split())))

    print("Enter goal state: ")
    goal_state = list()
    for _ in range(int(sqrt(N + 1))):
        goal_state.append(list(map(int, input().split())))

    root = Node(init_state, 0, list(), None)
    target = Node(goal_state, 0, list(), None)

    while True:
        print("\n-------Menu-------\n"
import pandas as pd

import os, sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

from env import env

if __name__ == "__main__":
    hero = pd.read_csv(env['path_marvel'])

    hero1 = hero["hero1"]
    hero2 = hero["hero2"]

    myGraph = Graph()
    myGraph.addNode("Little Abner")
    # myGraph.show()
    # print('\n')
    myGraph.addNode("Princess")
    myGraph.addEdge("Little Abner", "Princess")
    myGraph.addEdge("Princess", "Little Abner")
    # myGraph.addEdge("Little Abner", "Princess")
    # myGraph.show()
    # print('\n')
    myGraph.addNode("Homem de Ferro")
    myGraph.addNode("Pantera Negra")
    myGraph.addNode("Homem Aranha")
    # myGraph.show()
    # print('\n')
    myGraph.addNode("Cap.")
Exemplo n.º 46
0
 def __init__(self, graph: Graph.Graph, s: int):
     self._graph = graph
     self._reached = [False] * graph.vertices()
     self._explore_reachable_vertices(s)
Exemplo n.º 47
0
def create_graph():
    graph = Graph(8, False)
    graph.add_weighted_edge(0, 1, 10)
    graph.add_weighted_edge(0, 2, 1)
    graph.add_weighted_edge(0, 3, 4)
    graph.add_weighted_edge(1, 2, 3)
    graph.add_weighted_edge(1, 4, 0)
    graph.add_weighted_edge(2, 3, 2)
    graph.add_weighted_edge(2, 5, 8)
    graph.add_weighted_edge(3, 5, 2)
    graph.add_weighted_edge(3, 6, 7)
    graph.add_weighted_edge(4, 5, 1)
    graph.add_weighted_edge(4, 7, 8)
    graph.add_weighted_edge(5, 6, 6)
    graph.add_weighted_edge(5, 7, 9)
    graph.add_weighted_edge(6, 7, 12)
    return graph
Exemplo n.º 48
0
 def __graph_update(self):
     self.graph = Graph.create_from_nodes([self.nodes[x] for x in self.nodes.keys()])
     self.__update_cons()
Exemplo n.º 49
0
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("-seed",help="seed for random.seed() [default = VxV]",type=int,default=-1)
arg_parser.add_argument("-routes",help="file with routes to test [deafult = '']",type=str,default="")
arg_parser.add_argument("-json",help="file for Graph [default = tramwaje.json]",type=str,default="tramwaje.json")
arg_parser.add_argument("-output",help="save routes [deafult = '']",type=str,default="")
arg_parser.add_argument("-directed",help="is digraph? [deafult = False]",type=bool,default=False)
arg_parser.add_argument("-saving",help="enable djikstra/bellman temp save? [deafult = T]",type=str,default='T')

args = arg_parser.parse_args()


data = json.load(open(args.json,"r",encoding='utf-8'))

if args.directed:
  graph = Graph()
else:
  graph = NonGraph()
 

# Kontrukcja grafu z wczytanego JSON'a
for t in data["tramwaje"]:
  przystanki = t['tprzystanki']
  for j in range(len(przystanki)-1):
    l1 = przystanki[j]['name']
    l2 = przystanki[j+1]['name']
    graph.addEdge(l1,l2,1)


if args.routes!="":
  f = open(args.routes,"r")
Exemplo n.º 50
0
    log_path = os.path.join(project_dir, os.path.relpath(args['log_file']))
    logger = logging.getLogger()
    hdlr = logging.FileHandler(log_path)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)

input_batch_path = os.path.join(project_dir,
                                os.path.relpath(args['input_batch']))
input_stream_path = os.path.join(project_dir,
                                 os.path.relpath(args['input_stream']))
distance_limit = int(args['distance_limit'])
output_path = os.path.join(project_dir, os.path.relpath(args['output']))
# Instanciate the graph object
connections = Graph()

i = 0
with open(input_batch_path, 'r') as f:
    for line in f:
        # skip header
        if i == 0:
            i += 1
            continue

        input_line = line.split(',')
        try:
            user_1 = int(input_line[0].strip())
        except:
            if args["log_file"]:
                logger.error('Could not parse {0} at line {1}'.format(
def find_min(g, source, destination):
    distance = [0] * g.vertices
    visited = [False] * g.vertices
    q = deque()
    q.append(source)

    while q:
        v = q.popleft()
        adjacency = g.array[v].get_head()
        visited[v] = True
        while adjacency:
            if not visited[adjacency.data]:
                distance[adjacency.data] = distance[v] + 1
                if adjacency.data == destination:
                    return distance[destination]
                q.append(adjacency.data)
            adjacency = adjacency.next_element
    return -1


if __name__ == '__main__':
    g = Graph(7)
    g.add_edge(1, 2)
    g.add_edge(1, 3)
    g.add_edge(2, 4)
    g.add_edge(4, 5)
    g.add_edge(2, 5)
    g.add_edge(5, 6)
    g.add_edge(3, 6)
    print(find_min(g, 1, 5))
Exemplo n.º 52
0
    def Tenzor(self, graph, rec_auto, heads):
        result = Graph()
        result.n_vertices = graph.n_vertices
        for label in graph.labels():
            result.get_by_label(label)
            result.label_matrices[label] = graph.label_matrices[label]
        result.start_vertices = graph.start_vertices
        result.final_vertices = graph.final_vertices

        result.get_by_label(self.start_symbol.value)
        if self.generate_epsilon():
            for i in range(graph.n_vertices):
                result.get_by_label(self.start_symbol)[i, i] = True
        changes = True
        intersection = Graph()
        intersection = intersect(result, rec_auto)
        transitive_closure = intersection.transitive_closure_1()
        n = intersection.n_vertices
        while changes:
            prev = transitive_closure.nvals
            for i in range(n):
                for j in range(n):
                    if (i, j) in transitive_closure:
                        s = i % rec_auto.n_vertices
                        f = j % rec_auto.n_vertices
                        if (s in rec_auto.start_vertices) and (
                                f in rec_auto.final_vertices):
                            x = i // rec_auto.n_vertices
                            y = j // rec_auto.n_vertices
                            result.get_by_label(heads[s, f])[x, y] = True
            intersection = intersect(result, rec_auto)
            transitive_closure = intersection.transitive_closure_1()
            if transitive_closure.nvals == prev:
                changes = False
        return list(
            zip(*result.label_matrices[self.start_symbol].to_lists()[:2]))
Exemplo n.º 53
0
    def cluster(self):
        '''Clustering. The first step is to construct a triple graph and produce canopies. The second step is to process the canopies.'''
        data = self.data
        noun_data = self.noun_data
        final_result=[]

        # Add '_id' to each single record (The self-generated datasets do not has id)
        count = 0
        for single_data in data:
            # pprint(single_data)
            count += 1
            if '_id' in single_data.keys():
                continue
            else:
                single_data.update({'_id': count})

        # Add id to each single record (make it convenient to check the clustering results )
        id = 0
        for single_data in data:
            single_data.update({"id":id})
            id +=1


        print("****************Construct Triple Graph****************")
        # create a triple-dictionary recording the ids of the triples
        triple_dict = {}
        count = 0
        for single_data in data:
            if single_data['_id'] not in triple_dict.values():
                triple_dict.update({count: single_data['_id']})
                count += 1
        print(triple_dict)

        triple_graph = Graph(len(triple_dict))

        for i in range(0, len(data)):
            for j in range(i + 1, len(data)):
                if self.canopy_noun_overlap(data[i]["triple_norm"][0],data[j]["triple_norm"][0]) or \
                        self.canopy_noun_overlap(data[i]["triple_norm"][2], data[j]["triple_norm"][2]):
                    #print(data[i]["triple_norm"][0], data[j]["triple_norm"][0], data[i]["triple_norm"][2], data[j]["triple_norm"][2])
                    triple_graph.addEdge(data[i]["id"], data[j]["id"])

        print("****************Find the Canopies****************")
        # Use DFS to find connected components
        triple_cc = triple_graph.connectedComponents()
        print(triple_cc)

        print("****************Construct Canopy Graph****************")
        for canopy in triple_cc:
            if len(canopy) == 1:
                continue
            else:
                print("+++++++++++++++One Canopy+++++++++++++")
                print(canopy)
                # find the real ids and contents of the triples
                canopy_data_list = []
                for canopy_id in canopy:
                    canopy_data_list.append(data[canopy_id])
                #print(canopy_data_list)

                # create a canopy-dictionary recording the ids of the triples
                canopy_dict = {}
                count = 0
                for single_data in canopy_data_list:
                    canopy_dict.update({count: single_data['_id']})
                    count += 1
                #print(canopy_dict)

                # build the canopy_graph
                canopy_graph = Graph(len(canopy_dict))

                for i in range(0, len(canopy_data_list)):
                    for j in range(i + 1, len(canopy_data_list)):
                        sys.stdout.write("\r" + str(canopy_data_list[i]['_id'])+' , '+str(canopy_data_list[j]['_id']))
                        sys.stdout.flush()
                        ([text_sim, idf_sim, relation_sim, entity_sim, type_sim, dm_sim], sist_sim) = self.sim(canopy_data_list[i], canopy_data_list[j], data, noun_data, beta)
                        if sist_sim >=theta:
                            single_node_1 = -1
                            single_node_2 = -1
                            for key, value in canopy_dict.items():
                                if value == canopy_data_list[i]['_id']:
                                    single_node_1 = key
                                if value == canopy_data_list[j]['_id']:
                                    single_node_2 = key
                            if single_node_1 != -1 and single_node_2 != -1:
                                canopy_graph.addEdge(single_node_1, single_node_2)

                # Use DFS to find connected components
                canopy_cc = canopy_graph.connectedComponents()
                #print(canopy_cc)
                print('\n')

                # find the real ids of the triples

                for cluster in canopy_cc:
                    cluster_list = []
                    for node in cluster:
                        cluster_list.append(canopy_dict[node])
                    print(cluster_list)
                    final_result.append(cluster_list)
        print("****************Final Results****************")
        print(final_result)
Exemplo n.º 54
0
from Graph import Graph
from thistory import mark_visited, mark_processed, mark_edge


# execfile approximating that in python2
def execfile(filename):
    with open(filename) as f:
        code = compile(f.read(), filename, 'exec')
        exec(code, None, None)


# execfile("thistory.py")

g = Graph()

g.add_node(label='A')
g.add_node(label='B')
g.add_node(label='C')
g.add_node(label='D')
g.add_node(label='E')
g.add_node(label='F')

g.add_edge(0, 1)
g.add_edge(0, 4)
g.add_edge(0, 5)
g.add_edge(1, 2)
g.add_edge(2, 3)
g.add_edge(3, 4)

print("Traversal history with BFS:")
ts0 = g.bfs(0, None, mark_visited, mark_processed, mark_edge)
Exemplo n.º 55
0
class Board:
    def __init__(self, rook='A', king='H', knight='W'):
        self.rook = COORDINATES[rook]
        self.king = COORDINATES[king]
        self.knight = COORDINATES[knight]
        if self.rook[0] != self.knight[0] and self.rook[1] != self.knight[1]:
            print(f'king: {king}, rook: {rook}, knight: {knight}')
            self.generate_graph('graph.txt')
            file = open('graph.txt', 'r').read()
            self.graph = Graph(file)
            self.graph.a_star()
        else:
            print('skoczek nie może startować z pola atakowanego przez wieżę')

# generuje plik z grafem w postaci:
# liczba_wierzchołków, wierzchołek_startowy, wierzchołek_celu
# wierzchołek_poczatkowy, wierzchołek_koncowy, waga

    def generate_graph(self, file_name):
        file = open(file_name, 'w')
        file.write(f'25, {INDEXES[self.knight]}, {INDEXES[self.king]}')

        for x in range(5):
            for y in range(5):
                if x != self.rook[0] and y != self.rook[1]:
                    if x > 1 and y > 0:
                        if x - 2 != self.rook[0] and y - 1 != self.rook[1]:
                            file.write(
                                f'\n{INDEXES[(x, y)]}, {INDEXES[(x - 2, y - 1)]}, {3}'
                            )
                    if x > 1 and y < 4:
                        if x - 2 != self.rook[0] and y + 1 != self.rook[1]:
                            file.write(
                                f'\n{INDEXES[(x, y)]}, {INDEXES[(x - 2, y + 1)]}, {3}'
                            )
                    if x > 0 and y > 1:
                        if x - 1 != self.rook[0] and y - 2 != self.rook[1]:
                            file.write(
                                f'\n{INDEXES[(x, y)]}, {INDEXES[(x - 1, y - 2)]}, {3}'
                            )
                    if x < 4 and y > 1:
                        if x + 1 != self.rook[0] and y - 2 != self.rook[1]:
                            file.write(
                                f'\n{INDEXES[(x, y)]}, {INDEXES[(x + 1, y - 2)]}, {3}'
                            )
                    if x > 0 and y < 3:
                        if x - 1 != self.rook[0] and y + 2 != self.rook[1]:
                            file.write(
                                f'\n{INDEXES[(x, y)]}, {INDEXES[(x - 1, y + 2)]}, {3}'
                            )
                    if x < 4 and y < 3:
                        if x + 1 != self.rook[0] and y + 2 != self.rook[1]:
                            file.write(
                                f'\n{INDEXES[(x, y)]}, {INDEXES[(x + 1, y + 2)]}, {3}'
                            )
                    if x < 3 and y > 0:
                        if x + 2 != self.rook[0] and y - 1 != self.rook[1]:
                            file.write(
                                f'\n{INDEXES[(x, y)]}, {INDEXES[(x + 2, y - 1)]}, {3}'
                            )
                    if x < 3 and y < 4:
                        if x + 2 != self.rook[0] and y + 1 != self.rook[1]:
                            file.write(
                                f'\n{INDEXES[(x, y)]}, {INDEXES[(x + 2, y + 1)]}, {3}'
                            )
        file.close()
Exemplo n.º 56
0
#
# ---Date: 
# 04/02/2020
#
# ---Objective: 
# Solve weighted graphs using Dijkstra's Algorithm
#
# ---Guide:
# -Instantiate the Graph class with "nodes" number of nodes
# -Use add_edge to build your graph's edges
# -Call dijkstra_solution to print the shortest path from "start" to "end" according to Dijkstra's Algorithm


from Graph import Graph
from collections import defaultdict 


if __name__ == '__main__':
    graph = Graph(nodes=6)

    graph.add_edge(_from=0, to=1, distance=5)
    graph.add_edge(_from=0, to=2, distance=4)
    graph.add_edge(_from=1, to=2, distance=4)
    graph.add_edge(_from=1, to=4, distance=7)
    graph.add_edge(_from=1, to=3, distance=1)
    graph.add_edge(_from=2, to=4, distance=8)
    graph.add_edge(_from=2, to=5, distance=10)
    graph.add_edge(_from=3, to=4, distance=1)
    graph.add_edge(_from=4, to=5, distance=2)

    graph.dijkstra_solution(start=0, end=5)
Exemplo n.º 57
0
from Graph import Graph
from GraphSolution import GraphSolution

stu = Graph()
w = (1,2)
x = (1,3)
y = (2,3)
z = (2,4)
a = (3,4)

stu.construct_edge(w)
stu.construct_edge(x)
stu.construct_edge(y)
stu.construct_edge(z)
stu.construct_edge(a)
print("Your Graph structure:")
for k, v in stu.adj_list.items():
    print(k, v, [repr(e) for e in v.edges])

print("\n")

solution = GraphSolution()
print("Solution Graph structure:")
solution.construct_edge(w)
solution.construct_edge(x)
solution.construct_edge(y)
solution.construct_edge(z)
solution.construct_edge(a)
for k, v in solution.adj_list.items():
    print(k, v, [repr(e) for e in v.edges])
    
Exemplo n.º 58
0
def test_dfs_recursive():
    arr = [0, 1, 2, 3, 4, 5, 6, 7, 8]
    g = Graph(arr)
    g.add_edge(0, 1)
    g.add_edge(1, 2)
    g.add_edge(1, 3)
    g.add_edge(2, 4)
    g.add_edge(2, 3)
    g.add_edge(3, 5)
    g.add_edge(5, 6)
    g.add_edge(5, 7)
    g.add_edge(6, 8)

    g.dfs_recursive_first(0)
Exemplo n.º 59
0
        self._parent[v] = v
        queue.append(v)
        while len(queue) > 0:
            curr = queue.popleft()
            for w in self._g.adj(curr):
                if not self._visited[w]:
                    self._visited[w] = True
                    self._parent[w] = curr
                    queue.append(w)
                elif w != self._parent[curr]:
                    return True

        return False

    def hasCycle(self):
        return self._hasCycle


if __name__ == "__main__":
    g = Graph("g.txt")
    cd = CycleDetection(g)
    print(cd.hasCycle())

    g = Graph("g2.txt")
    cd = CycleDetection(g)
    print(cd.hasCycle())

    g = Graph("g3.txt")
    cd = CycleDetection(g)
    print(cd.hasCycle())
        F(log_potential_fun=lphi_0, nb=[rvs[0]]),
        F(log_potential_fun=lphi_1, nb=[rvs[1]]),
        F(log_potential_fun=lpsi, nb=[rvs[0], rvs[1]]),
    ]

    from scipy.integrate import quad

    Z = 0
    for x0 in rvs[0].values:
        Z_, err = quad(
            lambda x1: np.exp(lphi_0([x0]) + lphi_1([x1]) + lpsi([x0, x1])),
            -B, B)
        Z += Z_
    print('true -log Z =', -np.log(Z))

g = Graph()
g.rvs = rvs
g.factors = factors
g.init_nb()
g.init_rv_indices()

from OneShot import OneShot

grad_check = False
if not grad_check:
    K = 4
    T = 30
    lr = 5e-1
    osi = OneShot(g=g, K=K, T=T, seed=seed)
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=lr)
    res = osi.run(lr=lr, optimizer=optimizer, its=1000)