Exemplo n.º 1
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.º 2
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.º 3
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.º 4
0
 def test_initialization(self):
     """Test public methods on an empty union."""
     # Create [].
     an_empty_graph = DirectedGraph()
     self.assertEqual(an_empty_graph.n_vertices(), 0)
     self.assertEqual(an_empty_graph.connected(0, 0), False)
     self.assertEqual(an_empty_graph.connected(0, 1), False)
     self.assertEqual(an_empty_graph.neighbors(0), set())
Exemplo n.º 5
0
def load_board(cities_filename, routes_filename):

    board = DirectedGraph()

    cities: dict[str, City] = _resolve_cities(cities_filename)

    for city in cities:
        board.add_node(cities[city].get_name())

    _resolve_routes(board, routes_filename)

    return board, cities
Exemplo n.º 6
0
 def test_linked_list(self):
     """Test public methods on a linked list."""
     # Build a linked list:
     #   0 -> 1 -> 2
     a_graph = DirectedGraph()
     a_graph.connect(0, 1)
     a_graph.connect(1, 2)
     # Sort.
     a_sorter = TopologicalSort(a_graph)
     sorted_vertices = a_sorter.sort()
     # Only one correct sequence.
     self.assertEqual(sorted_vertices, (2, 1, 0))
     # Check the result using a graph.Reachability object.
     a_checker = Reachability(a_graph)
     self.assertTrue(self._sorted(sorted_vertices, a_checker))
Exemplo n.º 7
0
def generate_rand_dawg(nchars, nwords, wordlenpdf=None):
    """
    Generate a random DAWG whose word lengths are distributed by function
    wordlenpdf, using gnerate_rand_lexicon above.
    input:
        nchars: number of characters in lexicon
        nwords: number of words in lexicon
        wordlenpdf: a function

    """
    rand_lex = generate_rand_lexicon(nchars, nwords, wordlenpdf)
    G = DirectedGraph()
    G.parselex(rand_lex)
    trie_to_dawg(G)
    return G
    def __init__(self,
                 vertex_nums: [int] = [],
                 edges_to_add: [(int, int)] = [],
                 course_list=[]):
        DirectedGraph.__init__(self, vertex_nums, edges_to_add)

        self.disjunctionCount = 0

        for i in range(len(course_list)):
            self.add_vertex(i, course_list[i])

        for i in range(len(course_list)):
            destination = self.get_vertex_by_data(course_list[i])
            #print("Course = {}. Destination = {}".format(course_list[i], destination.get_data()))
            self.add_prerequisite_list_to_graph(course_list[i].prerequisites,
                                                destination, False)
Exemplo n.º 9
0
def readFile(file):
    try:
        f = open(file, 'r')
        lines = f.readlines()
        mode = 'missing'
        vertices = []
        arestas = []
        arcos = []
        for l in lines:
            if ('*vertices' in l):
                mode = 'vertices'
            elif ('*arcs' in l):
                mode = 'arcs'
            elif ('*edges' in l):
                mode = 'edges'
            else:
                if (mode == 'vertices'):
                    vertices.append(l.replace('\n', ''))
                elif (mode == 'arcs'):
                    arcos.append(l.replace('\n', ''))
                elif (mode == 'edges'):
                    arestas.append(l.replace('\n', ''))
        if (mode == 'arcs'):
            return DirectedGraph(vertices, arcos)
        elif (mode == 'edges'):
            return NonDirectedGraph(vertices, arestas)
    finally:
        f.close()
Exemplo n.º 10
0
def johnson(g, w):
    vertexes_g = g.get_v()
    edges_g = g.get_e()
    s = NameVertex('s')
    vertexes_g1 = [s] + vertexes_g
    edges_g1 = edges_g.copy()
    for vertex in vertexes_g:
        edges_g1.append(Edge(s, vertex, 0))
    graph2 = DirectedGraph(vertexes_g1, edges_g1)
    if bellman_ford(graph2, w, s) == False:
        print("the in put graph contains a negative_weight cycle")
    else:
        h = dict()
        for vertex in vertexes_g1:
            h[vertex] = vertex.d
        def weight1(edge):
            return w(edge) + h[edge.u] - h[edge.v]
    n = len(vertexes_g)
    d = dict()
    for u in vertexes_g:
        dijkstra(g, weight1, u)
        d[u] = dict()
        for v in vertexes_g:
            d[u][v] = v.d + h[v] - h[u]
    return d
Exemplo n.º 11
0
 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)
Exemplo n.º 12
0
 def test_binary_tree(self):
     """Test public methods on a binary tree."""
     # Build a binary tree:
     #     0
     #    / \
     #   1   2
     a_graph = DirectedGraph()
     a_graph.connect(0, 1)
     a_graph.connect(0, 2)
     # Sort.
     a_sorter = TopologicalSort(a_graph)
     sorted_vertices = a_sorter.sort()
     # Either of the two sequences is correct.
     self.assertTrue(sorted_vertices in {(2, 1, 0), (1, 2, 0)})
     # Check the result using a graph.Reachability object.
     a_checker = Reachability(a_graph)
     self.assertTrue(self._sorted(sorted_vertices, a_checker))
Exemplo n.º 13
0
 def test_empty_graph(self):
     """Test public methods on an empty graph."""
     # Build an empty graph.
     a_graph = DirectedGraph()
     checker = Reachability(a_graph)
     # Non-existing vertex is always NOT reachable.
     self.assertFalse(checker.has_path(0, 0))
     self.assertFalse(checker.has_path(0, 1))
Exemplo n.º 14
0
 def test_neighbors(self):
     """Test root()."""
     # Create [{1, 2}, {2}, set()].
     a_graph = DirectedGraph()
     a_graph.connect(0, 1)
     a_graph.connect(0, 2)
     a_graph.connect(1, 2)
     # Check neighbors on existing vertices.
     self.assertEqual(a_graph.neighbors(0), {1, 2})
     self.assertEqual(a_graph.neighbors(1), {2})
     self.assertEqual(a_graph.neighbors(2), set())
     # Check neighbors on non-existing vertices.
     self.assertEqual(a_graph.neighbors(3), set())
     self.assertEqual(a_graph.neighbors(4), set())
Exemplo n.º 15
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.º 16
0
    def test_traverse(self):
        vertexes_names = []

        def traverse_visit_callback(vertex):
            vertexes_names.append(vertex.name)

        dg = DirectedGraph("A", "B", "C", "D")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("C", "D")

        # bfs
        dg.bfs_traverse("A", traverse_visit_callback)
        assert vertexes_names == ["A", "B", "C", "D"]
        vertexes_names = []
        # dfs
        dg.dfs_traverse("A", traverse_visit_callback)
        assert vertexes_names == ["A", "B", "C", "D"]
Exemplo n.º 17
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.º 18
0
 def test_binary_tree(self):
     """Test public methods on a binary tree."""
     # Build a binary tree:
     #     0
     #    / \
     #   1   2
     a_graph = DirectedGraph()
     a_graph.connect(0, 1)
     a_graph.connect(0, 2)
     checker = Reachability(a_graph)
     # All the vertices are reachable from the root.
     self.assertTrue(checker.has_path(0, 1))
     self.assertTrue(checker.has_path(0, 2))
     # Vertices in another subtree are NOT reachable.
     self.assertFalse(checker.has_path(1, 2))
     self.assertFalse(checker.has_path(2, 1))
     # Parent is NOT reachable.
     self.assertFalse(checker.has_path(1, 0))
     self.assertFalse(checker.has_path(2, 0))
Exemplo n.º 19
0
 def test_implicit_adding_by_connecting(self):
     """Test connect(), which implicitly calls add()."""
     # Create [].
     a_graph = DirectedGraph()
     # Implicitly add 0, 1, 2 to [], then connect 1 with 2,
     # which makes [set(), {2}, set()].
     a_graph.connect(1, 2)
     self.assertEqual(a_graph.n_vertices(), 3)
     # Trivially connected vertices.
     self.assertEqual(a_graph.connected(0, 0), True)
     self.assertEqual(a_graph.connected(1, 1), True)
     self.assertEqual(a_graph.connected(2, 2), True)
     # Uni-directional connection created by connect().
     self.assertEqual(a_graph.connected(1, 2), True)
     self.assertEqual(a_graph.connected(2, 1), False)
     # Disconnected vertices.
     self.assertEqual(a_graph.connected(0, 1), False)
     self.assertEqual(a_graph.connected(1, 0), False)
     self.assertEqual(a_graph.connected(0, 2), False)
     self.assertEqual(a_graph.connected(2, 0), False)
Exemplo n.º 20
0
class OpArgMngr(object):
    """Operator argument manager for storing operator workloads."""
    graph = DirectedGraph()
    ops = {}

    @staticmethod
    def add_workload(funcname, *args, **kwargs):
        key = funcname + "." + str(int(time.time()))
        OpArgMngr.ops[key] = {'args': args, 'kwargs': kwargs, 'funcname': funcname}

    def add_assignment(variable, assigned_value):
Exemplo n.º 21
0
 def test_linked_list(self):
     """Test public methods on a linked list."""
     # Build a linked list:
     #   0 -> 1 -> 2
     a_graph = DirectedGraph()
     a_graph.connect(0, 1)
     a_graph.connect(1, 2)
     checker = Reachability(a_graph)
     # A vertex is always reachable from/to itself.
     self.assertTrue(checker.has_path(0, 0))
     self.assertTrue(checker.has_path(1, 1))
     self.assertTrue(checker.has_path(2, 2))
     # A downstream vertex is reachable from an upstream vertex.
     self.assertTrue(checker.has_path(0, 1))
     self.assertTrue(checker.has_path(1, 2))
     self.assertTrue(checker.has_path(0, 2))
     # A upstream vertex is NOT reachable from an downstream vertex.
     self.assertFalse(checker.has_path(1, 0))
     self.assertFalse(checker.has_path(2, 0))
     self.assertFalse(checker.has_path(2, 1))
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.º 23
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.º 24
0
 def test_non_consecutive_adding(self):
     """Test adding vertices non-consecutively."""
     # Create [].
     a_graph = DirectedGraph()
     # Add 1 to [], which becomes [set(), set()].
     # Here 0 is added implicitly.
     a_graph.add(1)
     self.assertEqual(a_graph.n_vertices(), 2)
     self.assertEqual(a_graph.connected(0, 0), True)
     self.assertEqual(a_graph.connected(0, 1), False)
     self.assertEqual(a_graph.connected(1, 1), True)
Exemplo n.º 25
0
    def make_graph(cls, root, strategy):
        """Compute the graph implied by some GameState."""
        graph = DirectedGraph()

        queue = deque()
        visited = set()

        # Add root to queue
        visited.add(root)
        queue.append(root)

        while queue:
            node = queue.popleft()
            if not node.is_over:
                for next in strategy.get_next_states(node):
                    graph.add_arc(node, next)
                    if next not in visited:
                        # Add `next` to queue.
                        visited.add(next)
                        queue.append(next)

        return graph
Exemplo n.º 26
0
	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 = {}
Exemplo n.º 27
0
    def test_adjacency_matrix(self):
        dg = DirectedGraph("A", "B", "C", "D")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("C", "D")

        assert dg.adjacency_matrix == [[0, 1, 0, 0], [0, 0, 1, 0],
                                       [0, 0, 0, 1], [0, 0, 0, 0]]
Exemplo n.º 28
0
class Regex:

    symbols = {
        '?': zero_or_one,
        '*': zero_or_more, # Kleene star
        '+': one_or_more
    }

    def __init__(self, regex):
        self.regex = regex
        # Vertices labelled with booleans, edges labelled with character classes (sets of zero or more characters)
        self.graph = DirectedGraph()
        self.compile()

    def compile(self):
        pass

    def transition(self, state, char):
        # 0. Initialize a set of empty string transition destinations
        empty = set()
        # 1. Test all the non-empty string transitions
        #print(self.graph.edges[state])
        for dest, label in self.graph.edges[state]:
            #print(char)
            #print(label)
            if char == label or char in label:
                return dest
            elif label == '':
                empty.add(dest)
            else:
                #print('Not found')
                return -1
        # 2. Test all the empty string transitions
        else:
            destinations = [self.transition(dest, char) for dest in empty if dest >= 0]
            return destinations[0] if len(destinations) > 0 else -1

    def match(self, string):
        state = 0
        strindex = 0
        # Negative state number means we've left the graph
        while strindex < len(string):
            char = string[strindex]
            #print('state %d' % state)
            next_state = self.transition(state, char)
            if next_state < 0:
                break
            else:
                state = next_state
                strindex += 1
        return self.graph.vertex(state)
Exemplo n.º 29
0
    def __init__(self, dict_graph):
        self.graph = DirectedGraph(dict_graph)
        self.index = 0
        self.stack = []

        # Runs Tarjan
        # Set all node index to None
        for v in self.graph.nodes:
            v.index = None

        self.sccs = []
        for v in self.graph.nodes:
            if v.index == None:
                self.strongconnect(v, self.sccs)
Exemplo n.º 30
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.º 31
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
Exemplo n.º 32
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
def trans_dc_to_graph_and_calc(dc):
    vertexes = []
    temp_locals = locals()
    for i in range(dc.n + 1):
        vetex_name = 'v' + str(i)
        temp_locals[vetex_name] = NameVertex(vetex_name)
        vertexes.append(eval(vetex_name))
    edges = []
    for num in range(dc.m):
        i = a[num].index(-1) + 1
        j = a[num].index(1) + 1
        edge = Edge(eval('v' + str(i)), eval('v' + str(j)), b[num])
        edges.append(edge)
    for num in range(1, dc.n + 1):
        edge = Edge(eval('v0'), eval('v' + str(num)), 0)
        edges.append(edge)
    graph1 = DirectedGraph(vertexes, edges)
    bf_result = bellman_ford(graph1, weight, eval('v0'))
    result = None
    if bf_result:
        result = []
        for i in range(1, dc1.n + 1):
            result.append(getattr(eval('v' + str(i)), 'd'))
    return result
Exemplo n.º 34
0
Arquivo: pgm.py Projeto: manofdale/hmm
 def __init__(self, config_path, transitions=None, emissions=None, start_id='B', end_id='E',
              convert_zero=0.000000000001):
     """
     :param config_path: to initialize the model path, sample format is available in ../data/hmm.cfg
     :param transitions: a list of triplets (from_id, to_id, probability), where from_id and to_id are state labels
     :param emissions: a list of triplets (emitter_id, emission_id, probability), where emitter_id is a state label
     :param start_id: label for the initial state, (can not emit obs), used for getting the starting probabilities
     :param end_id: label for the final state (can not emit obs), only required for the simulations
     :param convert_zero: a small number to handle missing or zero entries in the emission and transition data,
          if convert_zero is 0 and there is a missing or zero entry in the probabilities, an exception will be raised
     """
     self.graph = DirectedGraph(node_t=EmitterNode)
     self.emitters = []
     self.convert_zero = convert_zero
     self.start_id = start_id
     self.end_id = end_id
     if isinstance(config_path, basestring):
         transitions, emissions = load_config(path=config_path)  # load from data
     else:
         assert (transitions is not None and emissions is not None)
     self.set_transitions(transitions)  # (re)init emitters here
     self.starting_ps = {child.id: w for [w, child] in self.graph.nodes[self.start_id].children.values()}
     self.set_emissions(emissions)
     self.update_emitters()
Exemplo n.º 35
0
    paths = astar(graph, initial_node, goal_node, h)
    route = [goal_node]
    
    while goal_node != initial_node:
        route.append(paths[goal_node])
        goal_node = paths[goal_node]
 
    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)]
 
Exemplo n.º 36
0
"""
    Example Single Source Shortest Path. These are drawn from
    "Algorithms in a Nutshell (1ed)", pp. 154 and 155

    Author: George Heineman    
"""
from dijkstra import *
from graph import DirectedGraph

d = DirectedGraph()
d.addEdge(0,1,2)
d.addEdge(0,4,4)
d.addEdge(1,2,3)
d.addEdge(2,4,1)
d.addEdge(2,3,5)
d.addEdge(3,0,8)
d.addEdge(4,3,7)

print (d)

dist = singleSourceShortest(d, 0)

print (dist)

d = DirectedGraph()
d.addEdge(0,1,6)
d.addEdge(0,3,18)
d.addEdge(0,2,8)
d.addEdge(1,4,11)
d.addEdge(4,5,3)
d.addEdge(2,3,9)
Exemplo n.º 37
0
    def write_link_graph(self, link_graph: graph.DirectedGraph) -> str:
        with open(self.link_graph_dot, "w") as output_stream:
            link_graph.write_dot(output_stream)

        return self.link_graph_dot
Exemplo n.º 38
0
 def setUp(self):
     self.graph = DirectedGraph()
Exemplo n.º 39
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.º 40
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.º 41
0
    def setUp(self):

        self.my_graph = DirectedGraph("My 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))
Exemplo n.º 43
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.º 44
0
Arquivo: pgm.py Projeto: manofdale/hmm
class HiddenMarkov(object):
    def __init__(self, config_path, transitions=None, emissions=None, start_id='B', end_id='E',
                 convert_zero=0.000000000001):
        """
        :param config_path: to initialize the model path, sample format is available in ../data/hmm.cfg
        :param transitions: a list of triplets (from_id, to_id, probability), where from_id and to_id are state labels
        :param emissions: a list of triplets (emitter_id, emission_id, probability), where emitter_id is a state label
        :param start_id: label for the initial state, (can not emit obs), used for getting the starting probabilities
        :param end_id: label for the final state (can not emit obs), only required for the simulations
        :param convert_zero: a small number to handle missing or zero entries in the emission and transition data,
             if convert_zero is 0 and there is a missing or zero entry in the probabilities, an exception will be raised
        """
        self.graph = DirectedGraph(node_t=EmitterNode)
        self.emitters = []
        self.convert_zero = convert_zero
        self.start_id = start_id
        self.end_id = end_id
        if isinstance(config_path, basestring):
            transitions, emissions = load_config(path=config_path)  # load from data
        else:
            assert (transitions is not None and emissions is not None)
        self.set_transitions(transitions)  # (re)init emitters here
        self.starting_ps = {child.id: w for [w, child] in self.graph.nodes[self.start_id].children.values()}
        self.set_emissions(emissions)
        self.update_emitters()

    def set_transitions(self, transitions):
        for from_id, to_id, p in transitions:
            log_p, converted = try_to_log(p, convert_zero=self.convert_zero)  # use log probabilities
            if converted:
                self.graph.add_vertex(from_id, to_id, log_p)
            else:
                raise Exception("transition log probability conversion failed for %s" % str(p))

    def update_emitters(self):
        self.emitters = [state for state_id, state in self.graph.nodes.items() if
                         len(state.emission_ps.items()) != 0]  # list of emitter nodes

    def set_emissions(self, emissions):
        for node_id, obs_id, p in emissions:
            log_p, converted = try_to_log(p, convert_zero=self.convert_zero)  # use log probabilities
            if converted:
                if node_id in self.graph.nodes:
                    self.graph.nodes[node_id].emission_ps[obs_id] = log_p
            else:
                raise Exception("emission log probability conversion failed for %s" % str(p))

    def is_valid(self):
        valid = (self.emitters is not None and len(self.emitters) > 0 and self.starting_ps is not None and len(
            self.starting_ps) > 0)
        #print(self.emitters is not None, len(self.emitters) > 0, self.starting_ps is not None, len(
        #    self.starting_ps) > 0)
        # valid = valid and other_checks()  # Can do more checks here
        return valid

    def might_not_stop(self, stop_p=0.0000001):
        needy_nodes = set()
        end_id = self.end_id  # end node
        for state in self.emitters:
            if end_id not in state.children or state.children[end_id][0] < stop_p:  # need another node to end
                needy_nodes.add(state.id)
        for state_id in needy_nodes:
            all_needy = True
            for p, child in self.graph.nodes[state_id].children.values():  # if all kids are needy, then possible infinite loop
                if child.id not in needy_nodes:
                    all_needy = False
                    break
            if all_needy:
                return True
        return False

    def simulate(self, limit):
        if not self.is_valid():
            logging.error("The model configuration is not valid, can not simulate..")
        if self.might_not_stop():
            inp = raw_input("This simulation might get into an infinite loop, continue anyway? (y/n)")
            if inp.lower() != 'y':
                print("Smart choice!")
                return
            else:
                print("Alright, let's burn some cpu!")

        states = self.emitters
        p_ranges = [exp(self.starting_ps[s.id]) for s in states]

        ix = random_pick(p_ranges)
        print(ix)
        node = states[ix]
        emitted_seq = []
        for i in range(limit):
            if node.id != self.end_id:
                e = node.emit()
                print(i, node.id, e)
                emitted_seq.append(e)
            else:
                break
            candidates = node.children.values()
            p_ranges = [exp(w) for w, _ in candidates]
            ix = random_pick(p_ranges)
            node = candidates[ix][1]
        return emitted_seq
Exemplo n.º 45
0
    return j + 1


if __name__ == "__main__":
    clothing = [
        "undershorts", "pants", "belt", "shirt", "tie", "jacket", "socks",
        "shoes", "watch"
    ]
    vertexes = []
    for cloth in clothing:
        temp_locals = locals()
        temp_locals[cloth] = NameVertex(cloth)
        vertexes.append(eval(cloth))
    edges = [
        Edge(undershorts, pants),
        Edge(undershorts, shoes),
        Edge(pants, belt),
        Edge(pants, shoes),
        Edge(belt, jacket),
        Edge(shirt, tie),
        Edge(shirt, belt),
        Edge(tie, jacket),
        Edge(socks, shoes)
    ]
    g = DirectedGraph(vertexes, edges)
    results = topological_sort(g)
    for result in results:
        #print(result.name, result.d, result.f)
        print(result.name, end=', ')
    print()
Exemplo n.º 46
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"))
Exemplo n.º 47
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.º 48
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.º 49
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.º 50
0
 def __init__(self, username, depth):
     self.username = username
     self.depth = depth
     self.graph = DirectedGraph()
     self.following_users = []
Exemplo n.º 51
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.º 52
0
class TestGraph(unittest.TestCase):
    def setUp(self):
        self.my_graph = DirectedGraph()

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

    def test_addEdge(self):
        self.my_graph.addEdge("Emil", "Galin")
        self.assertEqual(self.my_graph.nodes, {"Emil": ["Galin"], "Galin": []})

    def test_getNEighbours(self):
        self.my_graph.addEdge("Emil", "Galin")
        self.my_graph.addEdge("Emil", "Pesho")
        self.my_graph.addEdge("Galin", "Atanas")
        self.my_graph.addEdge("Atanas", "Dimitrichka")
        self.assertEqual(self.my_graph.getNeighboursFor("Emil"), ["Galin", "Pesho"])

    def test_pathBetween_true(self):
        self.my_graph.addEdge("Emil", "Galin")
        self.my_graph.addEdge("Emil", "Pesho")
        self.my_graph.addEdge("Galin", "Atanas")
        self.my_graph.addEdge("Atanas", "Dimitrichka")
        self.assertTrue(self.my_graph.pathBetween("Emil", "Dimitrichka"))

    def test_pathBetween_false(self):
        self.my_graph.addEdge("Emil", "Galin")
        self.my_graph.addEdge("Emil", "Pesho")
        self.my_graph.addEdge("Galin", "Atanas")
        self.my_graph.addEdge("Atanas", "Dimitrichka")
        self.assertFalse(self.my_graph.pathBetween("Atanas", "Emil"))

    def test_pathBetween_cycle(self):
        self.my_graph.addEdge("Emil", "Galin")
        self.my_graph.addEdge("Emil", "Pesho")
        self.my_graph.addEdge("Galin", "Atanas")
        self.my_graph.addEdge("Atanas", "Dimitrichka")
        self.my_graph.addEdge("Dimitrichka", "Emil")
        print(self.my_graph)
        self.assertTrue(self.my_graph.pathBetween("Emil", "Dimitrichka"))
Exemplo n.º 53
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.º 54
0
 def __init__(self, regex):
     self.regex = regex
     # Vertices labelled with booleans, edges labelled with character classes (sets of zero or more characters)
     self.graph = DirectedGraph()
     self.compile()
Exemplo n.º 55
0
 def test_graph(self):
     graph = DirectedGraph()
     graph.loadGraph1("graph2.txt")
     graph.deleteVertex(0)
     graph.writeGraph1("graph1.txt")
Exemplo n.º 56
0
class Locator(object):

    def __init__(self, regions, outline=None):
        self.preprocess(regions, outline)

    def preprocess(self, regions, outline=None):
        def process_boundary(regions, outline=None):
            """
                Adds an outer triangle and triangulates the interior region. If an outline
                for the region is not provided, uses the convex hull (thus assuming that
                the region itself is convex.

                Arguments:
                regions -- a set of non-overlapping polygons that tile some part of the plane
                outline -- the polygonal outline of regions

                Returns: a bounding triangle for regions and a triangulation for the area between
                regions and the bounding triangle.
            """
            def add_bounding_triangle(poly):
                """
                    Calculates a bounding triangle for a polygon

                    Arguments:
                    poly -- a polygon to-be bound

                    Returns: a bounding polygon for 'poly'
                """

                bounding_tri = min_triangle.boundingTriangle(poly.points)
                bounding_regions = spatial.triangulatePolygon(
                    bounding_tri, hole=poly.points)
                return bounding_tri, bounding_regions

            if not outline:
                points = reduce(lambda ps, r: ps + r.points, regions, [])
                outline = spatial.convexHull(points)
            return add_bounding_triangle(outline)

        def triangulate_regions(regions):
            """
                Processes a set of regions (non-overlapping polygons tiling a portion of the plane),
                triangulating any region that is not already a triangle, and storing triangulated
                relationships in a DAG.

                Arguments:
                regions -- a set of non-overlapping polygons that tile some part of the plane

                Returns: a triangulation for each individual region in 'regions'
            """
            frontier = []

            for region in regions:
                self.dag.add_node(region)

                # If region is not a triangle, triangulate
                if region.n > 3:
                    triangles = spatial.triangulatePolygon(region)
                    for triangle in triangles:
                        # Connect DAG
                        self.dag.add_node(triangle)
                        self.dag.connect(triangle, region)
                        # Add to frontier
                        frontier.append(triangle)
                else:
                    frontier.append(region)

            return frontier

        def remove_independent_set(regions):
            """
                Processes a set of regions, detecting and removing an independent set
                of vertices from the regions' graph representation, and re-triangulating
                the resulting holes.

                Arguments:
                regions -- a set of non-overlapping polygons that tile some part of the plane

                Returns: a new set of regions covering the same subset of the plane, with fewer vertices
            """
            # Take note of which points are in which regions
            points_to_regions = {}
            for idx, region in enumerate(regions):
                for point in region.points:
                    if point in points_to_regions:
                        points_to_regions[point].add(idx)
                        continue

                    points_to_regions[point] = set([idx])

            # Connect graph
            g = UndirectedGraph()
            for region in regions:
                for idx in range(region.n):
                    u = region.points[idx % region.n]
                    v = region.points[(idx + 1) % region.n]
                    if not g.contains(u):
                        g.add_node(u)
                    if not g.contains(v):
                        g.add_node(v)
                    g.connect(u, v)

            # Avoid adding points from outer triangle
            removal = g.independent_set(8, avoid=bounding_triangle.points)

            # Track unaffected regions
            unaffected_regions = set([i for i in range(len(regions))])
            new_regions = []
            for p in removal:
                # Take note of affected regions
                affected_regions = points_to_regions[p]
                unaffected_regions.difference_update(points_to_regions[p])

                def calculate_bounding_polygon(p, affected_regions):
                    edges = []
                    point_locations = {}
                    for j, i in enumerate(affected_regions):
                        edge = set(regions[i].points)
                        edge.remove(p)
                        edges.append(edge)
                        for v in edge:
                            if v in point_locations:
                                point_locations[v].add(j)
                            else:
                                point_locations[v] = set([j])

                    boundary = []
                    edge = edges.pop()
                    for v in edge:
                        point_locations[v].remove(len(edges))
                        boundary.append(v)
                    for k in range(len(affected_regions) - 2):
                        v = boundary[-1]
                        i = point_locations[v].pop()
                        edge = edges[i]
                        edge.remove(v)
                        u = edge.pop()
                        point_locations[u].remove(i)
                        boundary.append(u)

                    return shapes.Polygon(boundary)

                # triangulate hole
                poly = calculate_bounding_polygon(p, affected_regions)
                triangles = spatial.triangulatePolygon(poly)
                for triangle in triangles:
                    self.dag.add_node(triangle)
                    for j in affected_regions:
                        region = regions[j]
                        self.dag.connect(triangle, region)
                    new_regions.append(triangle)

            for i in unaffected_regions:
                new_regions.append(regions[i])

            return new_regions

        self.dag = DirectedGraph()

        # Store copy of regions
        self.regions = regions

        # Calculate, triangulate bounding triangle
        bounding_triangle, boundary = process_boundary(regions, outline)

        # Store copy of boundary
        self.boundary = boundary

        # Iterate until only bounding triangle remains
        frontier = triangulate_regions(regions + boundary)
        while len(frontier) > 1:
            frontier = remove_independent_set(frontier)

    def locate(self, p):
        """Locates the point p in one of the initial regions"""
        polygon, valid = self.annotatedLocate(p)

        # Result might be valid polygon
        if not valid:
            return None

        return polygon

    def annotatedLocate(self, p):
        """
            Locates the point p, returning the region and whether or not
            the region was one of the initial regions (i.e., False if the
            region was a fabricated boundary region).
        """
        curr = self.dag.root()
        if not curr.contains(p):
            return None, False

        children = self.dag.e[curr]
        while children:
            for region in children:
                if region.contains(p):
                    curr = region
                    break

            children = self.dag.e[curr]

        # Is the final region an exterior region?
        return curr, curr in self.regions
Exemplo n.º 57
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.º 58
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"))