Exemplo n.º 1
0
def load_linqs_data(content_file, cites_file):
    '''
    Create a DirectedGraph object and add Nodes and Edges
    This is specific to the data files provided at http://linqs.cs.umd.edu/projects/projects/lbc/index.html
    Return two items 1. graph object, 2. the list of domain labels (e.g., ['AI', 'IR'])
    '''
    linqs_graph = DirectedGraph()
    domain_labels = []
    id_obj_map = {}

    with open(content_file, 'r') as node_file:
        for line in node_file:
            line_info = line.split('\n')[0].split('\t')
            n = Node(line_info[0], map(float, line_info[1:-1]),
                     line_info[-1])  # id, feature vector, label
            linqs_graph.add_node(n)
            if line_info[-1] not in domain_labels:
                domain_labels.append(line_info[-1])
            id_obj_map[line_info[0]] = n

    with open(cites_file, 'r') as edge_file:
        for line in edge_file:
            line_info = line.split('\n')[0].split('\t')
            if line_info[0] in id_obj_map.keys(
            ) and line_info[1] in id_obj_map.keys():
                from_node = id_obj_map[line_info[1]]
                to_node = id_obj_map[line_info[0]]
                linqs_graph.add_edge(Edge(from_node, to_node))

    print "domain labels"
    print domain_labels

    return linqs_graph, domain_labels
Exemplo n.º 2
0
class GitHubAPI:
    def __init__(self, username, depth):
        self.username = username
        self.depth = depth
        self.graph = DirectedGraph()
        self.following_users = []

    def get_following_for(self, name):
        self.following_users = requests.get("https://api.github.com/users/{}/following".format(name))
        print(self.following_users.json())
        return self.following_users

    def following(self, name):
        following_users = self.get_following_for(name)
        following_names = []
        for i in range(len(following_users.json())):
            print(len(following_users.json()))
            following_names.append(following_users.json()[i]["login"])
        return following_names

    def build_graph(self, name):
        neighbors = self.following(name)
        for neighbor in neighbors:
            self.graph.add_edge(name, neighbor)
        print(self.graph)
Exemplo n.º 3
0
def invert_graph(G):
    _G = DirectedGraph()
    for u in G.all_vertexes():
        connections = [(u.data, v) for u, v in G.get_vertex(u).items()]
        for v, w in connections:
            _G.add_edge(v, u, w)
    return _G
Exemplo n.º 4
0
def load_linqs_data(content_file, cites_file):
    '''
    Create a DirectedGraph object and add Nodes and Edges
    This is specific to the data files provided at http://linqs.cs.umd.edu/projects/projects/lbc/index.html
    Return two items 1. graph object, 2. the list of domain labels (e.g., ['AI', 'IR'])
    '''
    linqs_graph=DirectedGraph()
    domain_labels=[]
    id_obj_map={}

    with open(content_file, 'r') as node_file:
        for line in node_file:
            line_info=line.split('\n')[0].split('\t')
            n=Node(line_info[0],map(float,line_info[1:-1]),line_info[-1])# id, feature vector, label
            linqs_graph.add_node(n)
            if line_info[-1] not in domain_labels:
                domain_labels.append(line_info[-1])
            id_obj_map[line_info[0]]=n

    with open(cites_file,'r') as edge_file:
        for line in edge_file:
            line_info=line.split('\n')[0].split('\t')
            if line_info[0] in id_obj_map.keys() and line_info[1] in id_obj_map.keys():
                from_node=id_obj_map[line_info[1]]
                to_node=id_obj_map[line_info[0]]
                linqs_graph.add_edge(Edge(from_node,to_node))

    return linqs_graph,domain_labels
Exemplo n.º 5
0
	def init_map(self):
		graph = DirectedGraph()
		orientations = [Orientation.up, Orientation.left, Orientation.down, Orientation.right]
		
		if self.debug:
			print '> Mapper::init_map Adding all nodes'

		# Add all nodes to graph
		for r in xrange(0, self.max_rows):
			for c in xrange(0, self.max_cols):
				for o in orientations:
					graph.add_node((r,c,o))

		# Add turn right and left to all node. 
		# Add move to all posible nodes
		for node in graph.nodes:
			graph.add_edge(node, (node[0], node[1], (node[2]+1)%4))
			graph.add_edge(node, (node[0], node[1], (node[2]-1)%4))

			if node[2] == Orientation.up and (node[0]+1, node[1], node[2]) in graph.nodes:
				graph.add_edge(node, (node[0]+1, node[1], node[2]))
			elif node[2] == Orientation.left and (node[0], node[1]-1, node[2]) in graph.nodes:
				graph.add_edge(node, (node[0], node[1]-1, node[2]))
			elif node[2] == Orientation.down and (node[0]-1, node[1], node[2]) in graph.nodes: 
				graph.add_edge(node, (node[0]-1, node[1], node[2]))
			elif node[2] == Orientation.right and (node[0], node[1]+1, node[2]) in graph.nodes:
				graph.add_edge(node, (node[0], node[1]+1, node[2]))
		return graph
Exemplo n.º 6
0
def main():
    G = DirectedGraph()
    G.add_vertex('A')
    G.add_vertex('B')
    G.add_vertex('C')
    G.add_vertex('D')
    G.add_vertex('E')
    G.add_edge('A', 'B')
    G.add_edge('B', 'C')
    G.add_edge('B', 'D')
    G.add_edge('A', 'E')
    print(strongly_connected(G))
Exemplo n.º 7
0
def generate_directed_subgraph(original_graph, nodes_subset) -> DirectedGraph:

    new_graph = DirectedGraph()

    for node in original_graph.get_nodes():
        if node in nodes_subset:
            new_graph.add_node(node)

    for edge in original_graph.get_edges():
        if edge[0] in nodes_subset and edge[1] in nodes_subset:
            new_graph.add_edge(edge[0], edge[1], edge[2])

    return new_graph
Exemplo n.º 8
0
class GitHubModule:

    URL_PATTERN = "https://api.github.com/users/{}/follow\
ers?client_id={}&client_secret={}"

    CLIENT_ID = "6fd2017ecf6841cd6666"
    CLIENT_SECRET = "19e84bb54b28974bbc2260a778b28c1139f91360"

    def __init__(self, parent):
        self.parent = parent
        self.graph = DirectedGraph()
        self.fill_graph(self.parent)

    def fill_graph_for_user(self, user):
        url = self.URL_PATTERN.format(user, self.CLIENT_ID, self.CLIENT_SECRET)
        user_followers = requests.get(url)
        followers_dict = user_followers.json()

        for follower in followers_dict:
            self.graph.add_edge(user, follower["login"])

    def fill_graph(self, user):
        self.fill_graph_for_user(user)
        followers = set(self.graph.nodes[user])
        temp = set()  # use set to prevent repetitions

        for i in range(2):  # two more levels of depth
            for follower in followers:
                self.fill_graph_for_user(follower)
                for name in self.graph.nodes[follower]:
                    temp.add(name)
            followers = temp.copy()
            temp = set()

    def following(self):
        users_the_parent_follows = []
        for user in self.graph.nodes.keys():
            if self.parent in self.graph.nodes[user]:
                users_the_parent_follows.append(user)
        return users_the_parent_follows

    def is_following(self, user):
        if user in self.graph.nodes.keys():
            return self.parent in self.graph.nodes[user]
        return False
Exemplo n.º 9
0
class GitHubModule:

    URL_PATTERN = "https://api.github.com/users/{}/follow\
ers?client_id={}&client_secret={}"
    CLIENT_ID = "6fd2017ecf6841cd6666"
    CLIENT_SECRET = "19e84bb54b28974bbc2260a778b28c1139f91360"

    def __init__(self, parent):
        self.parent = parent
        self.graph = DirectedGraph()
        self.fill_graph(self.parent)

    def fill_graph_for_user(self, user):
        url = self.URL_PATTERN.format(user, self.CLIENT_ID, self.CLIENT_SECRET)
        user_followers = requests.get(url)
        followers_dict = user_followers.json()

        for follower in followers_dict:
            self.graph.add_edge(user, follower["login"])

    def fill_graph(self, user):
        self.fill_graph_for_user(user)
        followers = set(self.graph.nodes[user])
        temp = set()            # use set to prevent repetitions

        for i in range(2):      # two more levels of depth
            for follower in followers:
                self.fill_graph_for_user(follower)
                for name in self.graph.nodes[follower]:
                    temp.add(name)
            followers = temp.copy()
            temp = set()

    def following(self):
        users_the_parent_follows = []
        for user in self.graph.nodes.keys():
            if self.parent in self.graph.nodes[user]:
                users_the_parent_follows.append(user)
        return users_the_parent_follows

    def is_following(self, user):
        if user in self.graph.nodes.keys():
            return self.parent in self.graph.nodes[user]
        return False
Exemplo n.º 10
0
class TaskTemplateResolver():
  def __init__(self, task_templates=[]):
    self.template_graph = DirectedGraph()
    self.templates = {}
    self.template_parameters = {}
    self.namespaces = {}
    for template in task_templates:
      self.add_task_template(template)

  def add_task_template(self, template):
    template_id = _ns_template_id(template.namespace, template.id)
    self.templates[template_id] = template
    self.template_parameters[template_id] = dict(template.parameters)
    self.template_graph.add_node(template_id)
    self.namespaces[template.namespace] = True
    for task_id in template.dependencies:
      qualified_task_id = _ns_template_id(template.namespace, task_id)
      if '.' in task_id:
        self.template_graph.add_edge(task_id, template_id)
      else:
        self.template_graph.add_edge(qualified_task_id, template_id)

  def resolve_task_graph(self, template_id):
    if template_id not in self.templates:
      raise KeyError(template_id)

    reverse_graph = self.template_graph.reverse()
    nodes = reverse_graph.bfs_walk_graph(template_id)
    for node in nodes:
      template = self.templates[node]
      for parent_node in reverse_graph[node]:
        inherited_params = self.template_parameters[parent_node]
        params = self.template_parameters[node]
        inherited_params.update(params)

    task_graph = self.template_graph.subgraph(nodes)
    for node in nodes:
      template = self.templates[node]
      params = self.template_parameters[node]
      task = template.resolve_task(params)
      task_graph.node[node]['task'] = task
    return task_graph
class GraphTest(unittest.TestCase):
    def setUp(self):
        self.graph = DirectedGraph()

    def test_add_edge(self):
        self.graph.add_edge('A', 'B')
        self.assertTrue(('A', 'B') in self.graph.edges)

    def test_get_neighbours(self):
        self.graph.add_edge('A', 'B')
        self.graph.add_edge('A', 'C')
        self.graph.add_edge('D', 'A')
        self.assertEqual(self.graph.get_neighbours('A'), {'B', 'C'})

    def test_path_between(self):
        self.graph.add_edge('A', 'B')
        self.graph.add_edge('C', 'B')
        self.graph.add_edge('D', 'A')
        self.assertEqual(self.graph.path_between('D', 'B'), (True, 2))
        self.assertEqual(self.graph.path_between('D', 'C'), (False, 0))
def load_linqs_data(content_file, cites_file):
    
    if not os.path.isfile(content_file):
        raise IOError('No content file')
        return
    
    if not os.path.isfile(cites_file):
        raise IOError('No cites file')
        return
        
    graph = DirectedGraph()
    domain_labels = []


    content_file_reader = open(content_file, 'r')


    for line_str in content_file_reader:
        tokens = line_str.split('\t')
        
        node_id = tokens[0]
        feature_vector = tokens[1:-1]
        label = tokens[-1].strip()
        
        new_node = Node(node_id, feature_vector, label)
        graph.add_node(new_node)

        domain_labels.append(tokens[-1].strip())
    
    cites_file_reader = open(cites_file, 'r')
    citations = dict()

    for line in cites_file_reader:
        tokens2 = line.split('\t')

        from_node = tokens2[1].strip()
        to_node = tokens2[0].strip()
        endge = Edge(from_node, to_node)
        graph.add_edge(endge)    

    return graph, set(domain_labels)
Exemplo n.º 13
0
class GraphTests(unittest.TestCase):
    def setUp(self):
        self.graph = DirectedGraph()

    def test_add_node(self):
        self.graph.add_node("Rado")
        self.assertTrue(self.graph.has_node("Rado"))

    def test_add_edge(self):
        self.graph.add_edge("Rado", "Ivo")
        self.assertEqual(self.graph.info, {"Rado": ["Ivo"], "Ivo": []})

    def test_get_neighbors_for(self):
        self.graph.add_edge("Rado", "Gosho")
        self.assertEqual(self.graph.get_neighbors_for("Rado"), ["Gosho"])

    def test_path_between(self):
        self.graph.add_edge("Rado", "Gosho")
        self.graph.add_edge("Rado", "Ani")
        self.graph.add_edge("Gosho", "Ivo")
        self.assertTrue(self.graph.path_between("Rado", "Ani"))
        self.assertFalse(self.graph.path_between("Ani", "Ivo"))
        self.assertTrue(self.graph.path_between("Rado", "Ivo"))
Exemplo n.º 14
0
class GitHubNetwork:

    def __init__(self, username, depth):
        self.username = username
        self.depth = depth
        self.request = requests.get(
            'https://api.github.com/users/' + self.username + '/followers')
        self.social_graph = DirectedGraph()

    def following(self):

        request_json = self.request.json()
        for each_person in request_json:
            self.social_graph.add_edge(self.username, each_person['login'])

        return self.social_graph.nodes

    def is_following(self, user):
        if self.social_graph.path_between(self.username, user):
            return True
        return False

    def steps_to(self, username):
        pass
Exemplo n.º 15
0
 def test_path_between_true(self):
     newGraph = DirectedGraph()
     newGraph.add_edge("1", "2")
     newGraph.add_edge("2", "3")
     newGraph.add_edge("3", "4")
     self.assertTrue(newGraph.path_between("1", "4"))
Exemplo n.º 16
0
 def test_addEdge_two_node_not_exists(self):
     newGraph = DirectedGraph()
     newGraph.add_edge("1", "2")
     self.assertTrue(("1", "2") in newGraph.links)
     self.assertTrue("1" in newGraph.nodes)
     self.assertTrue("2" in newGraph.nodes)
Exemplo n.º 17
0
 def test_addEdge_one_node_not_exist(self):
     newGraph = DirectedGraph()
     newGraph.nodes.append("1")
     newGraph.add_edge("1", "2")
     self.assertTrue(("1", "2") in newGraph.links)
     print(newGraph)
Exemplo n.º 18
0
 def test_get_neighbours_for_not_empty(self):
     newGraph = DirectedGraph()
     newGraph.add_edge("1", "2")
     newGraph.add_edge("1", "3")
     self.assertEqual(["2", "3"], newGraph.get_neighbours_for("1"))
Exemplo n.º 19
0
def main():
    n = 10
    edges = [((1, 2), 5)]
    g = DirectedGraph()
    for i in range(9):
        g.add_vertex(i)
    g.add_edge(0, 1, 4)
    g.add_edge(0, 7, 8)
    g.add_edge(1, 2, 8)
    g.add_edge(1, 7, 11)

    g.add_edge(2, 3, 7)
    g.add_edge(2, 8, 2)
    g.add_edge(2, 5, 4)
    g.add_edge(3, 4, 9)

    g.add_edge(3, 5, 14)
    g.add_edge(4, 5, 10)
    g.add_edge(5, 6, 2)
    g.add_edge(6, 7, 1)
    g.add_edge(6, 8, 6)
    g.add_edge(7, 8, 7)

    print(bidirectional(g, 0, 8))
Exemplo n.º 20
0
class TestGraph(unittest.TestCase):
    def setUp(self):
        self.my_graph = DirectedGraph()

    def test_init(self):
        self.assertEqual(self.my_graph.nodes, {})

    def test_add_edge(self):
        self.my_graph.add_edge("modzozo", "RadoRado")
        self.assertEqual(self.my_graph.nodes, {"modzozo": ["RadoRado"], "RadoRado": []})

    def test_get_neighbours(self):
        self.my_graph.add_edge("modzozo", "RadoRado")
        self.my_graph.add_edge("modzozo", "mod")
        self.assertEqual(self.my_graph.get_neighbours_for("modzozo"), ["RadoRado", "mod"])

    def test_path_between_true(self):
        self.my_graph.add_edge("modzozo", "RadoRado")
        self.my_graph.add_edge("modzozo", "mod")
        self.my_graph.add_edge("RadoRado", "Rado")
        self.my_graph.add_edge("Rado", "zozo")
        self.assertTrue(self.my_graph.path_between("modzozo", "zozo"))

    def test_path_between_false(self):
        self.my_graph.add_edge("modzozo", "RadoRado")
        self.my_graph.add_edge("modzozo", "mod")
        self.my_graph.add_edge("RadoRado", "Rado")
        self.my_graph.add_edge("Rado", "zozo")
        self.assertFalse(self.my_graph.path_between("Rado", "modzozo"))

    def test_path_between_cycle(self):
        self.my_graph.add_edge("modzozo", "RadoRado")
        self.my_graph.add_edge("modzozo", "mod")
        self.my_graph.add_edge("RadoRado", "Rado")
        self.my_graph.add_edge("Rado", "zozo")
        self.my_graph.add_edge("zozo", "modzozo")
        self.assertTrue(self.my_graph.path_between("modzozo", "zozo"))
Exemplo n.º 21
0
def test_ford_fulkerson():

    graph = DirectedGraph()

    graph.add_node('s')
    graph.add_node('a')
    graph.add_node('b')
    graph.add_node('c')
    graph.add_node('d')
    graph.add_node('t')

    graph.add_edge('s', 'a', 10)
    graph.add_edge('s', 'c', 10)
    graph.add_edge('a', 'b', 4)
    graph.add_edge('a', 'c', 2)
    graph.add_edge('a', 'd', 8)
    graph.add_edge('b', 't', 10)
    graph.add_edge('c', 'd', 9)
    graph.add_edge('d', 'b', 6)
    graph.add_edge('d', 't', 10)

    flux = ford_fulkerson(graph, 's', 't')
    assert flux == 19, 'Flux expected was 19, found: {}'.format(flux)
Exemplo n.º 22
0
class DirectedGraphTests(unittest.TestCase):
    def setUp(self):
        self.graph = DirectedGraph()

    def test_add_edge_non_existing_nodes(self):
        self.graph.add_edge("Ionko", "Dingo")
        self.assertEqual(self.graph.nodes, {"Ionko": ["Dingo"], "Dingo": []})

    def test_add_edge_only_one_existing_node(self):
        self.graph.add_edge("Ionko", "Dingo")
        self.graph.add_edge("Dingo", "Penka")
        self.assertEqual(self.graph.nodes, {
            "Ionko": ["Dingo"],
            "Dingo": ["Penka"],
            "Penka": []
        })

    def test_add_edge_existing_nodes(self):
        self.graph.add_edge("Ionko", "Dingo")
        self.graph.add_edge("Dingo", "Ionko")
        self.assertEqual(self.graph.nodes, {
            "Ionko": ["Dingo"],
            "Dingo": ["Ionko"]
        })

    def test_get_neighbours_for_existing_nodes(self):
        self.graph.add_edge("Ionko", "Dingo")
        self.assertEqual(self.graph.get_neighbours_for("Ionko"), ["Dingo"])

    def test_get_neighbours_for_non_existing_nodes(self):
        self.assertEqual(self.graph.get_neighbours_for("ASDF"), [])

    def test_path_between_direct_neighbours(self):
        self.graph.add_edge("Ionko", "Dingo")
        self.assertTrue(self.graph.path_between("Ionko", "Dingo"))
        self.assertFalse(self.graph.path_between("Dingo", "Ionko"))

    def test_path_between_cyclic_neighbours(self):
        self.graph.add_edge("1", "2")
        self.graph.add_edge("2", "3")
        self.graph.add_edge("2", "4")
        self.graph.add_edge("4", "5")
        self.graph.add_edge("4", "6")

        self.graph.add_edge("3", "2")

        self.assertTrue(self.graph.path_between("2", "6"))
        self.assertFalse(self.graph.path_between("6", "2"))

    def test_path_between_indirect_neighbours(self):
        self.graph.add_edge("1", "2")
        self.graph.add_edge("2", "3")
        self.graph.add_edge("2", "4")
        self.graph.add_edge("4", "5")
        self.graph.add_edge("4", "6")

        self.assertTrue(self.graph.path_between("1", "6"))
        self.assertFalse(self.graph.path_between("6", "5"))
Exemplo n.º 23
0
def test_ford_fulkerson_multiple_sources_two_sources_with_limit():

    graph = DirectedGraph()

    graph.add_node('s')
    graph.add_node('s2')
    graph.add_node('a')
    graph.add_node('b')
    graph.add_node('c')
    graph.add_node('d')
    graph.add_node('t')

    graph.add_edge('s', 'a', 10)
    graph.add_edge('s', 'c', 10)
    graph.add_edge('a', 'b', 4)
    graph.add_edge('a', 'c', 2)
    graph.add_edge('a', 'd', 8)
    graph.add_edge('b', 't', 10)
    graph.add_edge('c', 'd', 9)
    graph.add_edge('d', 'b', 6)
    graph.add_edge('d', 't', 10)

    graph.add_edge('s2', 'b', 5)

    sources_limit = {'s': 14, 's2': 1}

    flux = ford_fulkerson_multiple_sources_and_limits(graph, ['s', 's2'], 't',
                                                      sources_limit)
    assert flux == 15, 'Flux expected was 15, found: {}'.format(flux)
Exemplo n.º 24
0
def test_ford_fulkerson_multiple_sources_two_sources():

    graph = DirectedGraph()

    graph.add_node('s')
    graph.add_node('s2')
    graph.add_node('a')
    graph.add_node('b')
    graph.add_node('c')
    graph.add_node('d')
    graph.add_node('t')

    graph.add_edge('s', 'a', 10)
    graph.add_edge('s', 'c', 10)
    graph.add_edge('a', 'b', 4)
    graph.add_edge('a', 'c', 2)
    graph.add_edge('a', 'd', 8)
    graph.add_edge('b', 't', 10)
    graph.add_edge('c', 'd', 9)
    graph.add_edge('d', 'b', 6)
    graph.add_edge('d', 't', 10)

    graph.add_edge('s2', 'b', 5)

    flux = ford_fulkerson_multiple_sources(graph, ['s', 's2'], 't')
    assert flux == 20, 'Flux expected was 19, found: {}'.format(flux)
Exemplo n.º 25
0
class GraphTest (unittest.TestCase):

    def setUp(self):
        self.sample_graph = DirectedGraph()

    def test_graph_init(self):
        self.assertEqual(self.sample_graph.graph, {})

    def test_add_edge(self):
        self.sample_graph.add_edge("A", "B")
        self.assertIn("A", self.sample_graph.graph)
        self.assertIn("B", self.sample_graph.graph["A"])

        self.sample_graph.add_edge("A", "D")
        self.assertIn("A", self.sample_graph.graph)
        self.assertIn("D", self.sample_graph.graph["A"])

        self.sample_graph.add_edge("B", "C")
        self.assertIn("A", self.sample_graph.graph)
        self.assertIn("B", self.sample_graph.graph["A"])
        self.assertIn("B", self.sample_graph.graph)
        self.assertIn("C", self.sample_graph.graph["B"])

    def test_get_neighbours_for(self):
        self.sample_graph.add_edge("A", "B")
        self.sample_graph.add_edge("A", "D")
        self.assertEqual(["B", "D"], self.sample_graph.get_neighbours_for("A"))

    def test_path_between(self):
        self.sample_graph.add_edge("A", "B")
        self.sample_graph.add_edge("B", "C")
        self.assertTrue(self.sample_graph.path_between("A", "C"))
        self.assertFalse(self.sample_graph.path_between("A", "D"))
        self.assertFalse(self.sample_graph.path_between("A", "E"))

    def test_to_str(self):
        self.sample_graph.add_edge("A", "B")
        self.assertEqual(self.sample_graph.to_str(), "A ---> ['B']")
Exemplo n.º 26
0
class FileLoader(object):
	def __init__(self):
		self.walls  = {}
		self.starts = []
		self.goals  = []
		self.keys   = []

		self.max_cols = None
		self.max_rows = None

		self.undirected_graph = UndirectedGraph()
		self.directed_graph = DirectedGraph()
		self.distance_node = {}
		self.node_distance = {}


	def read_map(self, file_name):
		print 'Reading File'
		f = open(file_name, 'r')

		# Reading walls: [row, col, up, left, down, right]
		print '\t> Parsing walls'

		[self.max_rows, self.max_cols] = f.readline().split(' ')
		self.max_rows = int(self.max_rows)
		self.max_cols = int(self.max_cols)

		for i in range(0, self.max_rows*self.max_cols):
			data = f.readline().split(' ')
			print 'data: ', data
			data = map(int, data)
			self.walls[(data[0],data[1])] = (data[2],data[3],data[4], data[5])

		# Reading starts
		print '\t> Parsing ', f.readline()
		MAX_START = int(f.readline())

		for i in range(0, MAX_START):
			data = f.readline().split(' ')
			if data[2][0] == 'u':
				orientation = 0
			elif data[2][0] == 'l':
				orientation = 1
			elif data[2][0] == 'd':
				orientation = 2
			else:
				orientation = 3
			self.starts.append((int(data[0]),int(data[1]),orientation))

		# Reading Goals
		print '\t> Parsing ', f.readline()
		MAX_GOALS = int(f.readline())

		for i in range(0, MAX_GOALS):
			data = f.readline().split(' ')
			row = int(data[0])
			col = int(data[1])
			self.goals.append((row,col))

		# Reading Keys
		print '\t> Parsing ', f.readline()
		MAX_KEYS = int(f.readline())

		for i in range(0, MAX_KEYS):
			data = f.readline().split(' ')
			row = int(data[0])
			col = int(data[1])
			self.keys.append((row,col))

		f.close()

	def generate_undirected_graph(self):
		orientations = [Orientation.up, Orientation.left, Orientation.down, Orientation.right]

		for w in self.walls.keys():
			row = w[0]
			col = w[1]

			for o in orientations:
				self.undirected_graph.add_node((row,col,o))

			self.undirected_graph.add_edge((row,col,Orientation.up),    (row,col,Orientation.left))
			self.undirected_graph.add_edge((row,col,Orientation.left),  (row,col,Orientation.down))
			self.undirected_graph.add_edge((row,col,Orientation.down),  (row,col,Orientation.right))
			self.undirected_graph.add_edge((row,col,Orientation.right), (row,col,Orientation.up))

		for node, ws in self.walls.items():
			if ws[0] == 0:
				self.undirected_graph.add_edge((node[0],node[1],Orientation.up), (node[0]+1,node[1],Orientation.up))
			if ws[1] == 0:
				self.undirected_graph.add_edge((node[0],node[1],Orientation.left), (node[0],node[1]-1,Orientation.left))
			if ws[2] == 0:
				self.undirected_graph.add_edge((node[0],node[1],Orientation.down), (node[0]-1,node[1],Orientation.down))
			if ws[3] == 0:
				self.undirected_graph.add_edge((node[0],node[1],Orientation.right), (node[0],node[1]+1,Orientation.right))

	def generate_directed_graph(self):
		orientations = [Orientation.up, Orientation.left, Orientation.down, Orientation.right]

		for w in self.walls.keys():
			row = w[0]
			col = w[1]

			for o in orientations:
				self.directed_graph.add_node((row,col,o))

			self.directed_graph.add_edge((row,col,Orientation.up),    (row,col,Orientation.left))
			self.directed_graph.add_edge((row,col,Orientation.left),    (row,col,Orientation.up))

			self.directed_graph.add_edge((row,col,Orientation.left),  (row,col,Orientation.down))
			self.directed_graph.add_edge((row,col,Orientation.down),  (row,col,Orientation.left))

			self.directed_graph.add_edge((row,col,Orientation.down),  (row,col,Orientation.right))
			self.directed_graph.add_edge((row,col,Orientation.right),  (row,col,Orientation.down))

			self.directed_graph.add_edge((row,col,Orientation.right), (row,col,Orientation.up))
			self.directed_graph.add_edge((row,col,Orientation.up), (row,col,Orientation.right))

		for node, ws in self.walls.items():
			if ws[0] == 0:
				self.directed_graph.add_edge((node[0],node[1],Orientation.up), (node[0]+1,node[1],Orientation.up))
			if ws[1] == 0:
				self.directed_graph.add_edge((node[0],node[1],Orientation.left), (node[0],node[1]-1,Orientation.left))
			if ws[2] == 0:
				self.directed_graph.add_edge((node[0],node[1],Orientation.down), (node[0]-1,node[1],Orientation.down))
			if ws[3] == 0:
				self.directed_graph.add_edge((node[0],node[1],Orientation.right), (node[0],node[1]+1,Orientation.right))

	def estimate_distances(self):
		#print '> Exploring distances'
		nodes = self.undirected_graph.nodes

		for node in nodes:
			#print '\t>>Localization::estimate_distances Node ', node
			distance = 0
			orientation = node[2]
			aux_node  = node
			test_node = node

			while True:
				if orientation == Orientation.up:
					test_node = (aux_node[0] + 1, aux_node[1], aux_node[2])
				elif orientation == Orientation.left:
					test_node = (aux_node[0], aux_node[1] - 1, aux_node[2])
				elif orientation == Orientation.down:
					test_node = (aux_node[0] - 1, aux_node[1], aux_node[2])
				elif orientation == Orientation.right:
					test_node = (aux_node[0], aux_node[1] + 1, aux_node[2])

				if not test_node in self.undirected_graph.edges[aux_node]: #BUG
					break
				aux_node = test_node
				distance = distance + 1

			self.distance_node.setdefault(distance, [])
			self.distance_node[distance].append(node)
			self.node_distance[node] = distance
Exemplo n.º 27
0
class DirectedGraphTests(unittest.TestCase):

    def setUp(self):
        self.graph = DirectedGraph()

    def test_add_edge_non_existing_nodes(self):
        self.graph.add_edge("Ionko", "Dingo")
        self.assertEqual(self.graph.nodes, {"Ionko": ["Dingo"], "Dingo": []})

    def test_add_edge_only_one_existing_node(self):
        self.graph.add_edge("Ionko", "Dingo")
        self.graph.add_edge("Dingo", "Penka")
        self.assertEqual(self.graph.nodes,
                         {"Ionko": ["Dingo"], "Dingo": ["Penka"], "Penka": []})

    def test_add_edge_existing_nodes(self):
        self.graph.add_edge("Ionko", "Dingo")
        self.graph.add_edge("Dingo", "Ionko")
        self.assertEqual(self.graph.nodes,
                         {"Ionko": ["Dingo"], "Dingo": ["Ionko"]})

    def test_get_neighbours_for_existing_nodes(self):
        self.graph.add_edge("Ionko", "Dingo")
        self.assertEqual(self.graph.get_neighbours_for("Ionko"),
                         ["Dingo"])

    def test_get_neighbours_for_non_existing_nodes(self):
        self.assertEqual(self.graph.get_neighbours_for("ASDF"), [])

    def test_path_between_direct_neighbours(self):
        self.graph.add_edge("Ionko", "Dingo")
        self.assertTrue(self.graph.path_between("Ionko", "Dingo"))
        self.assertFalse(self.graph.path_between("Dingo", "Ionko"))

    def test_path_between_cyclic_neighbours(self):
        self.graph.add_edge("1", "2")
        self.graph.add_edge("2", "3")
        self.graph.add_edge("2", "4")
        self.graph.add_edge("4", "5")
        self.graph.add_edge("4", "6")

        self.graph.add_edge("3", "2")

        self.assertTrue(self.graph.path_between("2", "6"))
        self.assertFalse(self.graph.path_between("6", "2"))

    def test_path_between_indirect_neighbours(self):
        self.graph.add_edge("1", "2")
        self.graph.add_edge("2", "3")
        self.graph.add_edge("2", "4")
        self.graph.add_edge("4", "5")
        self.graph.add_edge("4", "6")

        self.assertTrue(self.graph.path_between("1", "6"))
        self.assertFalse(self.graph.path_between("6", "5"))
Exemplo n.º 28
0
class GraphTest(unittest.TestCase):
    def setUp(self):
        self.sample_graph = DirectedGraph()

    def test_graph_init(self):
        self.assertEqual(self.sample_graph.graph, {})

    def test_add_edge(self):
        self.sample_graph.add_edge("A", "B")
        self.assertIn("A", self.sample_graph.graph)
        self.assertIn("B", self.sample_graph.graph["A"])

        self.sample_graph.add_edge("A", "D")
        self.assertIn("A", self.sample_graph.graph)
        self.assertIn("D", self.sample_graph.graph["A"])

        self.sample_graph.add_edge("B", "C")
        self.assertIn("A", self.sample_graph.graph)
        self.assertIn("B", self.sample_graph.graph["A"])
        self.assertIn("B", self.sample_graph.graph)
        self.assertIn("C", self.sample_graph.graph["B"])

    def test_get_neighbours_for(self):
        self.sample_graph.add_edge("A", "B")
        self.sample_graph.add_edge("A", "D")
        self.assertEqual(["B", "D"], self.sample_graph.get_neighbours_for("A"))

    def test_path_between(self):
        self.sample_graph.add_edge("A", "B")
        self.sample_graph.add_edge("B", "C")
        self.assertTrue(self.sample_graph.path_between("A", "C"))
        self.assertFalse(self.sample_graph.path_between("A", "D"))
        self.assertFalse(self.sample_graph.path_between("A", "E"))

    def test_to_str(self):
        self.sample_graph.add_edge("A", "B")
        self.assertEqual(self.sample_graph.to_str(), "A ---> ['B']")
Exemplo n.º 29
0
    route.reverse()
    return route
 
 
 # Testing algorithm
if __name__ == '__main__':
    import math
    sldist = lambda c1, c2: math.sqrt((c2[0] - c1[0])**2 + (c2[1] - c1[1])**2)
    g = DirectedGraph()
    g.add_node((0, 0))
    g.add_node((1, 1))
    g.add_node((1, 0))
    g.add_node((0, 1))
    g.add_node((2, 2))
 
    g.add_edge((0, 0), (1, 1), 1.5)
    g.add_edge((0, 0), (0, 1), 1.2)
    g.add_edge((0, 0), (1, 0), 1)
    g.add_edge((1, 0), (2, 2), 2)
    g.add_edge((0, 1), (2, 2), 2)
    g.add_edge((1, 1), (2, 2), 1.5)
 
    assert shortest_path(g, (0, 0), (2, 2), sldist) == [(0, 0), (1, 1), (2, 2)]
 
    g.distances[((0, 0), (1, 1))] = 2
    g.distances[((1, 1), (0, 0))] = 2
 
    assert shortest_path(g, (0, 0), (2, 2), sldist) == [(0, 0), (1, 0), (2, 2)]
 
    g.distances[((0, 0), (1, 0))] = 1.3
    g.distances[((1, 0), (0, 0))] = 1.3
Exemplo n.º 30
0
Arquivo: prim.py Projeto: lalitzz/DS
def main():
  g = DirectedGraph()
  for i in range(9):
    g.add_vertex(i)
  g.add_edge(0, 1, 4)
  g.add_edge(0, 7, 8)
  g.add_edge(1, 2, 8)
  g.add_edge(1, 7, 11)

  g.add_edge(2, 3, 7)
  g.add_edge(2, 8, 2)
  g.add_edge(2, 5, 4)
  g.add_edge(3, 4, 9)
  
  g.add_edge(3, 5, 14)
  g.add_edge(4, 5, 10)
  g.add_edge(5, 6, 2)
  g.add_edge(6, 7, 1)
  g.add_edge(6, 8, 6)
  g.add_edge(7, 8, 7)

  print(g)
  prim(g)
Exemplo n.º 31
0
class TestGraph(unittest.TestCase):

    def setUp(self):

        self.my_graph = DirectedGraph("My Graph")

    def test_init(self):

        self.assertEqual(self.my_graph.name, "My Graph")
        self.assertEqual(self.my_graph.edges, {})

    def test_add_edge(self):

        self.my_graph.add_edge("Ivo", "Boqn")
        self.assertIn("Ivo", self.my_graph.edges.keys())
        self.assertIn("Boqn", self.my_graph.edges["Ivo"])

    def test_get_neighbors_for(self):

        self.my_graph.add_edge("Ivo", "Djihad")
        self.my_graph.add_edge("Ivo", "Ahmed")
        self.assertEqual(["Djihad", "Ahmed"], self.my_graph.get_neighbors_for("Ivo"))


    def test_str(self):

        self.my_graph.add_edge("Ivo", "Djihad")
        self.my_graph.add_edge("Ivo", "Ahmed")
        self.my_graph.__str__()

    def test_path_between(self):

        self.my_graph.add_edge("misho", 'pesho')
        self.my_graph.add_edge("pesho", 'mitko')
        self.my_graph.add_edge("mitko", 'stefcho')

        self.assertTrue(self.my_graph.path_between("misho", "stefcho"))