Ejemplo n.º 1
0
def earliest_ancestor(ancestors, starting_node):
    """
    given the dataset and the ID of an individual in the dataset, 
    returns their earliest known ancestor – 
    the one at the farthest distance from the input individual. 
    If there is more than one ancestor tied for "earliest", 
    return the one with the lowest numeric ID. 
    If the input individual has no parents, the function should return -1.
    """
    # Instantiate graph, count and way to track final vertex
    graph = Graph()
    final_v = 0
    total_counter = 0

    # for people in ancestors
    # add vertex and edge
    for people in ancestors:
        graph.add_vertex(people[0])
        graph.add_vertex(people[1])

    for people in ancestors:
        graph.add_edge(people[1], people[0])

    # Instantiate Stack() to hold nodes to visit
    to_visit = Stack()
    to_visit.push(starting_node)

    # set to hold visited
    visited = set()

    # if not ancestors return -1
    # no ancestors means no neighbors so it must be own ancestor
    # -1 for being your own ancestor ... lol hillbilly - I am my own grandpa
    if len(graph.get_neighbors(starting_node)) == 0:
        return -1

    count = 0
    # so long as we have vertex to visit start popping
    while to_visit.size() > 0:
        vertex = to_visit.pop()

        if len(graph.get_neighbors(vertex)) == 0:
            if count > total_counter:
                total_counter = count
                final_v = vertex
            if count == total_counter:
                if vertex < final_v:
                    final_v = vertex

        if vertex not in visited:
            visited.add(vertex)

            if len(graph.get_neighbors(vertex)) != 0:
                for next_v in graph.get_neighbors(vertex):
                    to_visit.push(next_v)
                count += 1
            else:
                if to_visit.size() == 0:
                    return final_v
Ejemplo n.º 2
0
def earliest_ancestor(ancestors, starting_node):
    '''
    Build the graph
    '''
    # instantiate a new graph object
    graph = Graph()
    # loop over all pairs in ancestors
    for pair in ancestors:
        # add pair[0] and pair[1] to the graph
        graph.add_vertex(pair[0])
        graph.add_vertex(pair[1])
        # build the edges in reverse
        graph.add_edge(pair[1], pair[0])
    '''
    BFS with paths to find the earliest known ancestor
    '''
    # create a queue
    queue = Queue()
    # enqueue starting node inside a list
    queue.enqueue([starting_node])
    # set a max path length to 1
    max_path_length = 1
    # set initial earliest ancestor
    earliest_ancestor = -1
    # while the queue is not empty
    while not queue.is_empty():
        # dequeue to the path
        path = queue.dequeue()
        # set a vertex to the last item in the path
        vertex = path[-1]
        # if path is longer or equal and the value is smaller, or if the path is longer
        if (len(path) >= max_path_length and
                vertex < earliest_ancestor) or (len(path) > max_path_length):
            # set the earliest ancestor to the vertex
            earliest_ancestor = vertex
            # set the max path length to the len of the path
            max_path_length = len(path)
        # loop over next vertex in the set of vertices for the current vertex
        for next_vertex in graph.vertices[vertex]:
            # set a new path equal to a new list of the path
            path_copy = list(path)
            # append next vertex to new path
            path_copy.append(next_vertex)
            # enqueue the new path
            queue.enqueue(path_copy)
    # return earliest ancestor
    return earliest_ancestor
Ejemplo n.º 3
0
def earliest_ancestor(ancestors, current_vertex):
    # create blank graph for ancestors
    current_graph = Graph()
    # loop through and add all ancestors
    for ancestor in ancestors:
        current_graph.add_vertex(ancestor[0])
        current_graph.add_vertex(ancestor[1])
    # loop through and add all edges
    for ancestor in ancestors:
        current_graph.add_edge(ancestor[1], ancestor[0])

    max_path = 1
    # if the input has no parents return -1
    earliest_ancestor = -1
    # create blank traversing path
    traversing_path = Stack()
    # Start traversing path with the first vertex
    traversing_path.push([current_vertex])

    # while traversing path not empty
    while traversing_path.size() > 0:
        # start traversed path
        traversed_path = traversing_path.pop()
        # get last vertex in the traversed path
        last_vertex = traversed_path[-1]
        # get length of traversed path
        tp_length = len(traversed_path)
        # (if traversed path is longer than or equal to max_path AND
        # if last vertex is smaller than current earliest ancestor )
        # ##### OR
        # if traversed path is longer than max_path
        if (tp_length >= max_path
                and last_vertex < earliest_ancestor) or (tp_length > max_path):
            # set earliest ancestor as last vertex
            # set max path as last item in traversed path
            earliest_ancestor = last_vertex
            max_path = len(traversed_path)
        # get neighbors of last vertex
        neighbors = current_graph.vertices[last_vertex]
        # loop through each neighbor
        for neighbor in neighbors:
            # get current path list, append neighbor to it, and add to traversing path
            new_path = list(traversed_path)
            new_path.append(neighbor)
            traversing_path.push(new_path)
    # return earliest ancestor
    return earliest_ancestor
Ejemplo n.º 4
0
def earliest_ancestor(ancestors, starting_node):
    ancestorTree = Graph()
    # Iterate through ancestors to find vertices
    # for (parent,child) in ancestors
    for ancestor in ancestors:
        for vert in ancestor:
            ancestorTree.add_vertex(vert)
    # print("Tree", ancestorTree.vertices)

    for ancestor in ancestors:
        ancestorTree.add_edge(ancestor[1], ancestor[0])
    # print("Tree", ancestorTree.vertices)

    # default length to check the length of path list against
    longest_path = 1
    # counter for storing storing the last node
    last_node = 0
    # passing the vertices by reference
    ancestor_vert = ancestorTree.vertices

    # Iterate through the vertices of the ancestorTree
    for i in ancestor_vert:
        # i = individual nodes/vertices added using add_vert()
        # returns a list of nodes and sets the list to the variable path
        path = ancestorTree.dfs(starting_node, i)
        # print("path list loop", path)

        # If path is not = to None and the length of the path list in greater that longest_path which defaults to the value integer 1
        if path is not None and len(path) > longest_path:
            # set longest_path = length of the path
            longest_path = len(path)
            print("longest_path", longest_path)
            # last node is = to last node/vertice of the longest_path
            last_node = i
            print("last_node", last_node)
        # I was missing that longest_path defaults to 1.
        # If path list is empty and longest_path is set to default of 1
        elif not path and longest_path == 1:
            # print("empty", path)
            # print("elif path", longest_path)
            # set last_node to -1
            last_node = -1

    # print("Out of for loop", last_node)
    return last_node
Ejemplo n.º 5
0
def earliest_ancestor(ancestors, starting_node):
    graph = Graph()

    # Add vertices
    for i in ancestors:
        if i[0] not in graph.vertices:
            graph.add_vertex(i[0])
        if i[1] not in graph.vertices:
            graph.add_vertex(i[1])

    # Add edges
    for i in ancestors:
        graph.add_edge(i[1], i[0])

    path = graph.bft(starting_node)
    oldest = path[-1]

    if starting_node == oldest:
        return -1
    else:
        return oldest
Ejemplo n.º 6
0
def earliest_ancestor(ancestors, starting_node):
    graph = Graph()
    for parent, child in ancestors:
        vertices = graph.vertices
        if parent not in vertices:
            graph.add_vertex(parent)
        if child not in vertices:
            graph.add_vertex(child)
        graph.add_edge(child, parent)

    s = Stack()
    s.push([starting_node])

    longest = [starting_node]
    visited = set()
    oldest = -1

    while s.size() > 0:
        path = s.pop()
        curr = path[-1]
        # breakpoint()
        if (len(path) > len(longest)) or (len(path) == len(longest)
                                          and curr < oldest):
            longest = path
            oldest = longest[-1]

        if curr not in visited:
            visited.add(curr)

            parents = graph.get_neighbors(curr)

            for parent in parents:
                new_path = path + [parent]
                s.push(new_path)

    return oldest
Ejemplo n.º 7
0
def earliest_ancestor(ancestors, starting_node):
    ancestor_tree = Graph()
    # Iterate through ancestors
    for (parent, child) in ancestors:
        # Add vertices to ancestor_tree
        ancestor_tree.add_vertex(parent)
        ancestor_tree.add_vertex(child)
    # print("ancestor tree", ancestor_tree.vertices)

    for (parent, child) in ancestors:
        # Add edges
        ancestor_tree.add_edge(child, parent)
    # print("neighbors", ancestor_tree.get_neighbors(5))
    # print("ancestor tree", ancestor_tree.vertices)

    longest_path = 1  # Keep track of # ancestors; highest means most ancestors
    earliest_ancestor = 0  # Store last node (as an integer)
    for i in ancestor_tree.vertices:
        # print("i", i)  # Print vertices
        # Call dfs function from Graph class
        path = ancestor_tree.dfs(
            i, starting_node)  # i is each vertex/node in graph
        # print("ancestor dfs", ancestor_tree.dfs(starting_node, i))
        print('path', path)
        if path:  # If there are items in list
            if len(
                    path
            ) > longest_path:  # If list length is greater than longest path
                longest_path = len(
                    path)  # Set longest path equal to list length
                earliest_ancestor = i  # Set earliest_ancestor equal to current node/vertex
        elif not path and longest_path == 1:  # If path is 'None' and 'longest_path' is our default of 1
            earliest_ancestor = -1

    print("earliest ancestor", earliest_ancestor)
    return earliest_ancestor
Ejemplo n.º 8
0
        return 's'
    if direction == 's':
        return 'n'
    if direction == 'e':
        return 'w'
    if direction == 'w':
        return 'e'

while True:
    room = player.currentRoom

    # Mark room down as visited and identified
    identified_rooms.add(room.id)
    visited_rooms.add(room.id)
    # path_by_ids.append(room.id)
    graph.add_vertex(room.id)

    # Make note of all of the exits of a room
    for direction in room.getExits():
        adjacent_room_id = room.getRoomInDirection(direction).id
        identified_rooms.add(adjacent_room_id)
        graph.add_vertex(adjacent_room_id)
        graph.add_edge(room.id, adjacent_room_id, direction)

    # If room has been visited before, stop
    if identified_rooms == visited_rooms:
        break

    # Search for all the directions to rooms we haven't visited yet.
    def findUnvisitedRooms(room_object):
        return [direction for direction, ID in graph.vertices[room_object.id].items() if ID not in visited_rooms]
import json
import requests
from urls import base, end, post, get
import os
from random import choice
from util import Queue, Stack, Graph, reverse_dirs

# importing token and init endpoint

# auth header

# init endpoint - loads current room
data = get(end['init'])

gr = Graph()
gr.add_vertex(data)
# print(gr.rooms)
# map_data = {}

# map_data[data['room_id']] = data

# print("map_data", map_data)
"""
{room_id: {title: "foo", terrain: "bar"}}
"""
visited = set()
while True:
    dfs = gr.dfs(data)
    curr_room = gr.rooms[dfs[-1]]
    for room_id in dfs:
        visited.add(room_id)
Ejemplo n.º 10
0
import os

global data
data = get(end['init'])

global snitch
snitch = False if data['room_id'] < 500 else True

gr = Graph()
map_file = 'map.json' if snitch == False else 'map2.json'
with open(map_file) as map:
    completed_map = json.load(map)
    for room in completed_map:
        if completed_map[room] == data['room_id']:
            data = completed_map[room]
        gr.add_vertex(completed_map[room])


def exits():
    global data
    all_exits = data['exits']
    print('Exits: [', end='')
    for i, x in enumerate(all_exits):
        room_id = gr.rooms[data['room_id']]['exits'][x]
        room_title = gr.rooms[room_id]['title']
        terrain = gr.rooms[room_id]['terrain']
        if i + 1 == len(all_exits):
            print(f'{x} ({room_id} - {room_title} [{terrain}])', end='')
        else:
            print(f'{x} ({room_id} - {room_title} [{terrain}])', end=', ')
    print(']')
Ejemplo n.º 11
0
    visited = set()
    while q.size:
        path = q.dequeue()
        curr_room = path[-1][0]
        if '?' in gr.rooms[curr_room].values():
            return [d for _, d in path][1:]
        elif curr_room not in visited:
            visited.add(curr_room)
            for direction in curr_room.get_exits():
                next_room = curr_room.get_room_in_direction(direction)
                q.enqueue(path + [(next_room, direction)])
    return None


gr = Graph()
gr.add_vertex()

while True:
    if not any('?' in d.values() for d in gr.rooms.values()):
        break
    linear_dir = gr.go_in_direction_until_dead_end(player.current_room)
    get_current_room(linear_dir)
    traversal_path += linear_dir
    path_to_unexplored_room = find_unexplored_room()
    if path_to_unexplored_room is not None:
        traversal_path += path_to_unexplored_room
        get_current_room(path_to_unexplored_room)

# TRAVERSAL TEST
visited_rooms = set()
player.current_room = world.starting_room
Ejemplo n.º 12
0
    while q.size:
        path = q.dequeue()
        curr_room = path[-1][0]
        if '?' in gr.rooms[curr_room].values():
            return [d for _, d in path][1:]
        elif curr_room not in visited:
            visited.add(curr_room)
            for direction in curr_room.get_exits():
                next_room = curr_room.get_room_in_direction(direction)
                q.enqueue(path + [(next_room, direction)])
    return None


gr = Graph()
for room in world.rooms.values():
    gr.add_vertex(room)

while any('?' in d.values() for d in gr.rooms.values()):
    linear_dir = gr.go_in_direction_until_dead_end(player.current_room)
    get_current_room(linear_dir)
    traversal_path += linear_dir
    path_to_unexplored_room = find_unexplored_room()
    if path_to_unexplored_room is not None:
        traversal_path += path_to_unexplored_room
        get_current_room(path_to_unexplored_room)

# TRAVERSAL TEST
visited_rooms = set()
player.current_room = world.starting_room
visited_rooms.add(player.current_room)
Ejemplo n.º 13
0
    import sys

    if len(sys.argv) < 2:
        print 'usage: infer_kmeans.py path_to_trips/'
        sys.exit(0)

    # load traces
    traces = read_traces(sys.argv[1])

    # get initial markers
    markers_by_trace = get_markers(traces, SEED_DISTANCE)
    flat_markers = [
        marker for trace_markers in markers_by_trace
        for marker in trace_markers
    ]

    # initialize clusters and run k-means
    initial_clusters = initialize_clusters(flat_markers, DISTANCE_THRESHOLD,
                                           BEARING_THRESHOLD)
    clusters = kmeans(flat_markers, initial_clusters, 2 * DISTANCE_THRESHOLD,
                      MOVEMENT_THRESHOLD)

    # extract road network
    graph = Graph()
    for cluster in clusters:
        cluster.vertex = graph.add_vertex(cluster.x, cluster.y)
    generate_edges(graph, markers_by_trace, clusters)

    # output graph
    graph.write('kmeans-inferred.graph')
Ejemplo n.º 14
0
# }

# FIRST: Explore all rooms and populate the graph
graph = Graph()
# Add starting room
starting_room = world.starting_room
# graph.add_vertex(starting_room.id)
stack = Stack()
stack.push(starting_room)
visited = set()
# Continue until we have seen all rooms and the stack is empty
while stack.size() > 0:
    room = stack.pop()  # returns a <Room> class instance, not a room id
    room_id = room.id
    if room_id not in graph.vertices:
        graph.add_vertex(room_id)
    # Get connected rooms
    connected_rooms = room.get_exits()  # returns an array of directions
    for direction in connected_rooms:
        connected_room = room.get_room_in_direction(
            direction)  # returns a <Room> class instance
        connected_room_id = connected_room.id
        if connected_room_id not in graph.vertices:
            graph.add_vertex(connected_room_id)
        graph.add_edge(room_id, connected_room_id, direction)
        # After making the connection in the graph add it to the stack
        if connected_room_id not in visited:
            stack.push(connected_room)
    visited.add(room_id)

Ejemplo n.º 15
0
    'Authorization': 'Token d3f3a0266824458c28f1e36c817636085dcc3106',
    'Content-Type': 'application/json'
}

node_headers = {'Content-Type': 'application/json'}

world_graph = Graph()

explored_rooms = set()

last_room_id = 0
world_graph.add_vertex(
    0, "A brightly lit room",
    "You are standing in the center of a brightly lit room. You notice a shop to the west and exits to the north, south and east.",
    "(60,60)", 0, "NORMAL", [], {
        'n': '?',
        'e': '?',
        's': '?',
        'w': '?'
    }, ["You have walked south."])
{explored_rooms.add(0)}
exits = {'n': '?', 'e': '?', 's': '?', 'w': '?'}
direction = 's'

dir_reverse = {"n": "s", "s": "n", "e": "w", "w": "e"}

while len(explored_rooms) < 500:

    contains_unexplored = False
    for i in exits:
        if exits[i] == '?':