示例#1
0
 def load_graph(self, dmp):
     """
     Receives a graphs and appends it at self.graphs.
     :param dmp: A pickle dump that contains the edge list of a graph.
     """
     edges = pickle.loads(dmp)
     self.graphs.append(Graphs.Graph(edges))
示例#2
0
def ReadGraphFromFile( fileName ):

    print "Name of the file: ", fileName
    first_header_line = True

    for line in open(fileName):
        print line
        edge = line.split()

        if first_header_line:
            first_header_line = False
            maxSize = int(edge[0])
            graphFromFile = Graphs.Graph(maxSize+1)
        else:
            vertex = int(edge[0])
            for next_vertex in edge:
                adjacent_vertex = next_vertex.split(',')
                #debug_var = (adjacent_vertex[0])
                if int(adjacent_vertex[0]) != vertex:
                    # Note, althought this graph isn't directed, each vertex has an adjacency list,
                    # so to prevent duplicates we call insert edge with directed = True to prevent
                    # that function from doing it both ways.

                    graphFromFile.InsertEdge(vertex, int(adjacent_vertex[0]), True, int(adjacent_vertex[1]) )

    return graphFromFile, maxSize
示例#3
0
def play(player):
    """
    Handles the game turns. This function should be invoked after init(), connect() and share_graphs().
    :param player: The player object.
    :return:
    """
    srv_req = player.receive()
    is_over = False
    game_result = None
    if srv_req == RPSNetwork.TURN_NEED:

        # Asks for rock, paper or scissor.
        choice = ask_for_graph(player)
        my_g = player.get_graph(choice)

        # A isomorphic copy of the chosen graph will be sent to the opponent.
        my_iso_g, iso = my_g.isomorphic_copy()
        dmp = pickle.dumps(my_iso_g)
        player.send(dmp)

        # Receives the opponents chosen graph.
        op_g = oppon_turn(player)

        # Send the isomorphism
        player.send(pickle.dumps(iso))

        # Check if the game is over and determine the winner.
        game_result = finish_turn(player, choice, op_g)

    elif srv_req == RPSNetwork.TURN_SEND:

        # Receives the opponents chosen graph.
        op_g = oppon_turn(player)

        # Asks for rock, paper or scissor.
        choice = ask_for_graph(player)
        my_g = player.get_graph(choice)
        dmp = pickle.dumps(my_g)
        player.send(dmp)

        # Receives the opponents isomorphism
        op_iso = oppon_turn(player)

        # Calculates the opponents graph back.
        inv_func = Graphs.inv_permut_function(op_iso)
        op_edges = Graphs.apply_isomorphism(op_g.edges, inv_func)
        op_g = Graphs.Graph(op_edges)

        # Check if the game is over and determine the winner.
        game_result = finish_turn(player, choice, op_g)

    if game_result != RES_DRAW:
        is_over = True

    player.send(str(game_result))

    return is_over
示例#4
0
def ReadGraphFromFile(fileName, maxSize):

    print "Name of the file: ", fileName
    graphFromFile = Graphs.Graph(maxSize)
    for line in open(fileName):
        print line
        edge = line.split()
        graphFromFile.InsertEdge(int(edge[0]), int(edge[1]))

    return graphFromFile
def ReadWeightedGraphFromFile(fileName):

    print "Name of the file: ", fileName
    firstLine = True

    for line in open(fileName):
        if (firstLine):
            print line
            edge = line.split()
            numberOfVertices = int(edge[0]) + 1
            graphFromFile = Graphs.Graph(numberOfVertices)
            firstLine = False
        else:
            print line
            edge = line.split()
            graphFromFile.InsertEdge(int(edge[0]), int(edge[1]), False,
                                     int(edge[2]))

    return graphFromFile
示例#6
0
def Prims(graph, start):
    ''' Creates a minimum  spanning tree using Prims algorithm
    '''
    print "Start vertex = ", start

    spanningTree = Graphs.Graph(graph.maxVertices, False)
    inTree = [False] * graph.maxVertices
    inTree[start] = True
    spanningVertices = []  #[0]*graph.maxVertices
    spanningVertices.append(start)

    # Initialize the heap (PriorityQueue) with the min edge of the first
    # vertex for its key, and ininity for all other keys (vertexs).
    heapQueue = PriorityQueue()
    #for vertex in range(0, len(graph.vertices)):
    #    if( not (graph.vertices[vertex]).empty ):
    #        heapQueue.add_task(vertex, 35850023)    #sys.maxint)

    startEdges = (graph.vertices[start]).priorityEdges
    nextVertex, minWeight, noMoreValidEdges = startEdges.pop_task()
    heapQueue.add_task((start, nextVertex), minWeight)
    totalCost = 0

    while (not noMoreValidEdges):

        # Pop the next cheapest edge off the list off the heap (prioirty queue) (this will remove it)
        nextEdge, cheapestWeight, noMoreValidEdges = heapQueue.pop_task()

        if (not noMoreValidEdges):
            nextVertex = nextEdge[1]
            vertexInTreeGettingUpdate = nextEdge[0]
            if (not inTree[nextVertex]):
                #print "Next vertex, weight, total = ", nextVertex, cheapestWeight, totalCost
                totalCost += cheapestWeight
                inTree[nextVertex] = True
                spanningVertices.append(nextVertex)
                spanningTree.InsertEdge(vertexInTreeGettingUpdate, nextVertex,
                                        False, cheapestWeight)

                # Need to find the cheapest edges for both vertex's on the next edge that is
                # coming into the spanning tree.
                # Note that the edge that led to this vertex being selected has now been
                # removed from the "priorityEdges" for that vertex by the "pop_task()" function below
                nextEdges = (graph.vertices[nextVertex]).priorityEdges
                edgesEmpty = False
                cheapestEdgeVertex = nextVertex
                # We keep popping the edges until we find one that's not already in the tree.
                while ((not edgesEmpty) and (inTree[cheapestEdgeVertex])):
                    cheapestEdgeVertex, cheapestEdgeWeight, edgesEmpty = nextEdges.pop_task(
                    )
                    #if( (not edgesEmpty) and (inTree[cheapestEdgeVertex])):
                    #    print "edge discarded because already in tree = ", cheapestEdgeVertex, cheapestEdgeWeight
                if (not edgesEmpty):
                    heapQueue.remove_task((nextVertex, cheapestEdgeVertex))
                    heapQueue.add_task((nextVertex, cheapestEdgeVertex),
                                       cheapestEdgeWeight)

                nextEdges = (
                    graph.vertices[vertexInTreeGettingUpdate]).priorityEdges
                edgesEmpty = False
                cheapestEdgeVertex = vertexInTreeGettingUpdate
                # We keep popping the edges until we find one that's not already in the tree.
                while ((not edgesEmpty) and (inTree[cheapestEdgeVertex])):
                    cheapestEdgeVertex, cheapestEdgeWeight, edgesEmpty = nextEdges.pop_task(
                    )
                    #if( (not edgesEmpty) and (inTree[cheapestEdgeVertex])):
                    #    print "edge discarded because already in tree = ", cheapestEdgeVertex, cheapestEdgeWeight
                if (not edgesEmpty):
                    heapQueue.remove_task(
                        (vertexInTreeGettingUpdate, cheapestEdgeVertex))
                    heapQueue.add_task(
                        (vertexInTreeGettingUpdate, cheapestEdgeVertex),
                        cheapestEdgeWeight)

    return totalCost