예제 #1
0
    def test_remove_edge_in_directed_graph(self):
        g = Graph(True)
        g.add_edge((1, 2, 10))
        g.add_edge((2, 3, 11))
        g.add_edge((3, 1, 12))

        g.remove_edge((2, 3))
        self.assertEqual(g.table[1][2], 10, 'should have kept the edge')
        self.assertEqual(g.table[3][1], 12, 'should have kept the edge')
        self.assertEqual(g.table[2], {}, 'should have removed the edge')
예제 #2
0
 def test_add_weight_no_edge(self):
     """
     Test addting the weight of an edge that does not exist.
     """
     g = Graph()
     g.add_node("A")
     g.add_node("B")
     with self.assertRaises(ValueError) as context:
         g.add_weight("A", "B", 1.51)
     self.assertIn("edge", str(context.exception))
예제 #3
0
 def test_repr(self):
     """
     Test the correctness of the __repr__ function.
     """
     correct = "{'A': {}, 'B': {}, 'C': {}}"
     g = Graph()
     g.add_node("A")
     g.add_node("B")
     g.add_node("C")
     self.assertEqual(repr(g), correct)
예제 #4
0
 def test_add_weight_invalid_end(self):
     """
     Test addting the weight of an edge where the end node does not exist.
     """
     g = Graph()
     g.add_node("A")
     g.add_node("B")
     with self.assertRaises(ValueError) as context:
         g.add_weight("A", "C", 44.43)
     self.assertIn("end", str(context.exception))
예제 #5
0
 def test_add_edge_default(self):
     """
     Test adding an edge to the graph.
     """
     correct = "{'A': {'B': 0.0}, 'B': {}}"
     g = Graph()
     g.add_node("A")
     g.add_node("B")
     g.add_edge("A", "B")
     self.assertEqual(str(g), correct)
예제 #6
0
    def test_get_vertices_for_undirected_graph(self):
        g = Graph(False)
        g.add_edge((1, 2))
        g.add_edge((2, 3))
        g.add_edge((3, 1))

        actual = g.get_edges()
        expected = [(1, 2, True), (1, 3, True), (2, 3, True)]

        self.assertEqual(actual, expected, 'should return only one way edges')
예제 #7
0
 def test_add_weight_invalid_start(self):
     """
     Test addting the weight of an edge where the start node does not exist.
     """
     g = Graph()
     g.add_node("A")
     g.add_node("B")
     with self.assertRaises(ValueError) as context:
         g.add_weight("C", "B", 20.00)
     self.assertIn("start", str(context.exception))
예제 #8
0
 def test_add_node_duplicate(self):
     """
     Test that an exception is thrown when adding two nodes with the same
     name.
     """
     g = Graph()
     self.assertEqual(g.size(), 0)
     g.add_node("A")
     with self.assertRaises(ValueError):
         g.add_node("A")
예제 #9
0
 def test_add_weight(self):
     """
     Test updating the weight of an edge between two nodes.
     """
     correct = "{'A': {'B': 3.14}, 'B': {}}"
     g = Graph()
     g.add_node("A")
     g.add_node("B")
     g.add_edge("A", "B")
     g.add_weight("A", "B", 3.14)
     self.assertEqual(str(g), correct)
예제 #10
0
 def test_set_weight(self):
     """
     Test setting the weight of an edge between two nodes.
     """
     g = Graph()
     g.add_node("A")
     g.add_node("B")
     g.add_edge("B", "A")
     self.assertEqual(g.get_weight("B", "A"), 0.0)
     g.set_weight("B", "A", 123.45)
     self.assertEqual(g.get_weight("B", "A"), 123.45)
예제 #11
0
 def test_add_node_size(self):
     """
     Test the success of adding a new node to the graph using the size
     of the graph.
     """
     g = Graph()
     self.assertEqual(g.size(), 0)
     g.add_node("A")
     self.assertEqual(g.size(), 1)
     g.add_node("B")
     self.assertEqual(g.size(), 2)
예제 #12
0
    def test_add_edge_for_directed_graph(self):
        g = Graph(True)
        g.add_edge((1, 2, 3))

        self.assertIn(1, g.table, 'should have stored a key for tail vertex')
        self.assertIn(2, g.table[1], 'should have stored the edge')
        self.assertEqual(g.table[1][2], 3, 'should have stored the edge value')

        self.assertIn(2, g.table, 'should not have stored the node')
        self.assertNotIn(1, g.table[2],
                         'should not have stored the reverse edge')
예제 #13
0
    def test_add_edge_for_undirected_graph(self):
        g = Graph(False)
        g.add_edge((1, 2, 3))

        self.assertIn(1, g.table, 'should have stored a key for tail vertex')
        self.assertIn(2, g.table[1], 'should have stored the edge')
        self.assertEqual(g.table[1][2], 3, 'should have stored the edge value')

        self.assertIn(2, g.table, 'should have stored a key for head vertex')
        self.assertIn(1, g.table[2], 'should have stored the reversed edge')
        self.assertEqual(g.table[2][1], 3, 'should have stored the edge value')
예제 #14
0
def test_remove_node_with_edges():
    graph = Graph()
    graph.graph[1] = {2, 3}
    graph.graph[2] = {4}
    graph.graph[3] = {3}
    graph.graph[4] = {1, 2}
    graph.remove_node(3)

    expected = {1: {2}, 2: {4}, 4: {1, 2}}
    output = graph.graph
    assert output == expected
예제 #15
0
def graph(scope='module'):
    # TODO: maybe randomness comes from here?
    d = {
        'A': graph._Point2D(0, 0),
        'B': graph._Point2D(0, 3),
        'C': graph._Point2D(4, 3),
        'D': graph._Point2D(4, 0)
    }
    g = Graph(d)

    return g
예제 #16
0
 def test_brute_force(self):
     graph1 = Graph()
     graph1.add_edge("A", "B", 1)
     graph1.add_edge("A", "C", 1)
     graph1.add_edge("B", "D", 9)
     graph1.add_edge("C", "D", 1)
     graph1.end = "D"
     graph1.start = "A"
     path = brute_force(graph1)
     self.assertListEqual(path[0], ["A", "C", "D"])
     self.assertEqual(path[1], 2)
예제 #17
0
 def test_add_node_str(self):
     """
     Test the success of adding a new node to the graph using
     the string representation of the graph.
     """
     correct = "{'A': {}, 'B': {}, 'C': {}}"
     g = Graph()
     g.add_node("A")
     g.add_node("B")
     g.add_node("C")
     self.assertEqual(str(g), correct)
예제 #18
0
    def test_get_weights2(self):
        self.graph = Graph(["text edge graph edge",
                            "text edge graph edge"], 3)
        df = self.graph.get_weights()

        assert df.loc["text", "graph"] == 2
        assert df.loc["graph", "text"] == 2
        assert df.loc["text", "edge"] == 2
        assert df.loc["edge", "text"] == 2
        assert df.loc["edge", "graph"] == 6
        assert df.loc["graph", "edge"] == 6
예제 #19
0
 def test_dijkstra(self):
     graph = Graph()
     graph.add_edge("A", "B", 1)
     graph.add_edge("A", "C", 1)
     graph.add_edge("B", "D", 9)
     graph.add_edge("C", "D", 1)
     path, distance = dijkstra(graph,"A", "D")
     self.assertListEqual(path, ["A", "C", "D"])
     self.assertEqual(distance, 2)
     self.assertRaises(ValueError, dijkstra, graph, "A", "X")
     self.assertRaises(TypeError, dijkstra, "A", 7)
    def test_get_edge_as_tuple(self):
        graph = Graph(True)
        v1 = graph.add_vertex("apple")
        v2 = graph.add_vertex("banana")
        v3 = graph.add_vertex("coconut")

        graph.add_edge("apple", "banana")
        graph.add_edge("apple", "coconut", 3)

        self.assertEqual(("apple", "banana"), graph.get_edge_as_tuple(v1, v2))
        self.assertEqual(("apple", "coconut", 3),
                         graph.get_edge_as_tuple(v1, v3))
예제 #21
0
    def add_maze(self,row,col,id=0, show = True, debug=False): # return a optimize graph instead of maze instance
        if id is not 0:
            self.mazes.append(Maze(row, col, id, show, debug))
        else:
            if len(self.mazes) < 1:
                self.mazes.append(Maze(row, col, 0, show, debug))
            else:
                self.mazes.append(Maze(row, col, len(self.mazes) + 1, show, debug))

        graph = Graph(self.mazes[-1],show,debug)
        self.graphs.append(graph)
        return self.graphs[-1]
예제 #22
0
def main():
    t1 = time.time()
    print('Load train set ID...')
    train_set = load_train_txt_file()
    train_set.remove('1a0a')
    graph_dict = {}
    train_dict = {}
    train_ID = 0
    for network_name in train_set:
        train_dict[train_ID] = network_name
        train_ID += 1
        print(
            str(train_ID) + " Read graph ..." + network_name +
            "'s edgelist_file!")
        g = Graph()
        Path_edgelist_file = windows_dir_pre + '/output/edgelist/edgelist_' + network_name + '.txt'
        g.read_edgelist_file(path=Path_edgelist_file,
                             weighted=True,
                             directed=False)

        print(
            str(train_ID) + ' Read graph ...' + network_name +
            "'s node_label_file!")
        Path_node_label_file = windows_dir_pre + '/output/residue_type/residue_type_' + network_name + '.txt'
        g.read_node_label_file(Path_node_label_file)
        print(
            str(train_ID) + ' Read graph ...' + network_name +
            "'s feature_file!")
        Path_node_feature_file = windows_dir_pre + '/output/feature/feature_' + network_name + '.txt'
        g.read_node_features_file(Path_node_feature_file)
        graph_dict[network_name] = g
        if train_ID == 200:
            break
    Protein_GCN_model = Protein_GCN(
        graph_dict=graph_dict,
        train_dict=train_dict,
        learning_rate=learning_rate,
        epochs=epochs,
        hidden1=hidden1,
        dropout=dropout,
        weight_decay=weight_decay,
        early_stopping=early_stopping,  #权值衰减
        max_degree=max_degree,
        clf_ratio=clf_ratio,
        Path_output=Path_output,
        batch_size=batch_size)
    # if args.graph_format == 'adjlist':
    #     g.read_adjlist(filename=args.input)
    # elif args.graph_format == 'edgelist':
    #     g.read_edgelist(filename=args.input, weighted=args.weighted,
    #                     directed=args.directed)

    t2 = time.time()
예제 #23
0
    def test_remove_vertex(self):
        g = Graph(False)
        g.add_edge((1, 2))
        g.add_edge((2, 3))
        g.add_edge((3, 1))

        g.remove_vertex(3)

        self.assertTrue(g.table[1][2], 'should keep edges not involving 3')
        self.assertTrue(g.table[2][1], 'should keep edges not involving 3')
        self.assertNotIn(3, g.table, 'vertex 3 disappeared')
        self.assertNotIn(3, g.table[1], 'edge from 3 to 1 dissappeared')
예제 #24
0
    def test_incident_vertices_are_correctly_maintained_after_remove_vertex(
            self):
        g = Graph(directed=True)
        g.add_edge((1, 2))
        g.add_edge((2, 3))
        g.add_edge((3, 1))
        # table: {1: {2: True}, 2: {3: True}, 3: {1: True}}
        # incident: {1: set([3]), 2: set([1]), 3: set([2])}
        g.remove_vertex(1)
        self.assertEqual(g.table, {2: {3: True}, 3: {}})
        self.assertEqual(g.incident_vertices, {2: set(), 3: set([2])})

        g = Graph(directed=False)
        g.add_edge((1, 2))
        g.add_edge((2, 3))
        g.add_edge((3, 1))
        # table: {1: {2: True, 3: True}, 2: {1: True, 3: True}, 3: {1: True, 2: True}}
        # incident: {1: set([2, 3]), 2: set([1, 3]), 3: set([1, 2])}
        g.remove_vertex(1)
        self.assertEqual(g.table, {2: {3: True}, 3: {2: True}})
        self.assertEqual(g.incident_vertices, {2: set([3]), 3: set([2])})
예제 #25
0
def test_remove_one_directed_edge():
    graph = Graph()
    graph.graph[1] = set()
    graph.graph[2] = set()
    graph.graph[1].add(2)
    graph.graph[1].add(3)
    graph.graph[2].add(3)
    graph.remove_edge(1, 2)

    expected = {1: {3}, 2: {3}}
    output = graph.graph
    assert output == expected
예제 #26
0
    def test_remove_edge_in_undirected_graph(self):
        g = Graph(False)
        g.add_edge((1, 2, 10))
        g.add_edge((2, 3, 11))
        g.add_edge((3, 1, 12))

        g.remove_edge((2, 3))

        self.assertEqual(g.table[1][2], 10, 'no removals')
        self.assertEqual(g.table[1][3], 12, 'no removals')
        self.assertEqual(g.table[2][1], 10, 'removed the edge from tail')
        self.assertEqual(g.table[3][1], 12, 'removed the edge from head')
예제 #27
0
    def test_neighbours_in_directed_graph(self):
        g = Graph(True)
        g.add_edge((1, 2))
        g.add_edge((1, 3))

        expected = [2, 3]
        actual = g.neighbours(1)
        self.assertEqual(actual, expected, 'should find neighbours of 1')

        expected = []
        actual = g.neighbours(2)
        self.assertEqual(actual, expected, '2 has no neighbours')
예제 #28
0
def create_graph(map_array):

    WEIGHT_SIDE = 1
    WEIGHT_DIAG = sqrt(2)

    G = Graph()

    # inserindo nos no grafo
    for i, row in enumerate(map_array):
        for j, value in enumerate(row):

            # '-' = nao eh um no
            # '*' = no normal
            # '#' = no inicial
            # '$' = no final
            name = G.node_name(map_array, (i, j))

            if value != '-':
                G.insert_node(name)

            if value == '#':
                if G.start_node == '':
                    G.set_start(name)
                else:
                    print("ERRO: Mapa contem mais de um ponto inicial.")
                    return None
            elif value == '$':
                if G.end_node == '':
                    G.set_end(name)
                else:
                    print("ERRO: Mapa contem mais de um ponto final.")
                    return None

    # inserindo arestas no gafo
    for i, row in enumerate(map_array):
        for j, value in enumerate(row):

            if value != '-':
                for a in side_adjacents(map_array, (i, j)):
                    ai = a[0]
                    aj = a[1]
                    if map_array[ai][aj] != '-':
                        G.insert_arc(G.node_name(map_array, (i, j)),
                                     G.node_name(map_array, a), WEIGHT_SIDE)

                for a in diag_adjacents(map_array, (i, j)):
                    ai = a[0]
                    aj = a[1]
                    if map_array[ai][aj] != '-':
                        G.insert_arc(G.node_name(map_array, (i, j)),
                                     G.node_name(map_array, a), WEIGHT_DIAG)

    return G
예제 #29
0
def main(
    arg_one_input="D:\\workspace\\pycharm\\paper_algorithm\\FindSimilarityCommunity\\src\\contrast\\data\\paper\\synthetic\\football_1.net",
    arg_one_feature_file="D:\\workspace\\pycharm\\paper_algorithm\\FindSimilarityCommunity\\src\\contrast\\data\\paper\\synthetic\\football_info_115_1",
    arg_two_input="D:\\workspace\\pycharm\\paper_algorithm\\FindSimilarityCommunity\\src\\contrast\\data\\paper\\synthetic\\football_1-0.05.net",
    arg_two_feature_file="D:\\workspace\\pycharm\\paper_algorithm\\FindSimilarityCommunity\\src\\contrast\\data\\paper\\synthetic\\football_info_115_2"
):
    warnings.filterwarnings("ignore", category=FutureWarning)
    t1 = time.time()
    # init graph
    arg_one = args.args()
    arg_one.input = arg_one_input
    arg_one.feature_file = arg_one_feature_file
    nx_graph_one = nx.read_edgelist(arg_one.input, nodetype=int, comments="%")
    adj_matrix_one = nx.adjacency_matrix(nx_graph_one).todense()
    g_one = Graph(adj_matrix_one)

    g_one.read_edgelist(filename=arg_one.input,
                        weighted=arg_one.weighted,
                        directed=arg_one.directed)
    g_one.read_node_features(arg_one.feature_file)

    arg_two = args.args()
    arg_two.input = arg_two_input
    arg_two.feature_file = arg_two_feature_file
    nx_graph_two = nx.read_edgelist(arg_two.input, nodetype=int, comments="%")
    adj_matrix_two = nx.adjacency_matrix(nx_graph_two).todense()
    g_two = Graph(adj_matrix_two)

    g_two.read_edgelist(filename=arg_two.input,
                        weighted=arg_two.weighted,
                        directed=arg_two.directed)
    g_two.read_node_features(arg_two.feature_file)
    # community detection
    # igraph.Graph.community_infomap()
    # SCAN
    algorithm_one = SCAN(g_one.G, 0.5, 3)
    communities_one = algorithm_one.execute()
    algorithm_two = SCAN(g_two.G, 0.5, 3)
    communities_two = algorithm_two.execute()
    return communities_one, communities_two, g_one, g_two
예제 #30
0
def test_add_edge_node_to_multiple_nodes():
    graph = Graph()
    graph.graph[1] = set()
    graph.graph[2] = set()
    graph.graph[3] = set()
    graph.add_edge(1, 2)
    graph.add_edge(2, 2)
    graph.add_edge(3, 2)
    graph.add_edge(1, 3)

    expected = {1: {2, 3}, 2: {1, 2, 3}, 3: {2, 1}}
    output = graph.graph
    assert output == expected