Exemplo n.º 1
0
class TestPrimitives(object):
    def __init__(self):
        self.graph = NXGraph()
        add_node(self.graph, '1', {'name': 'EGFR', 'state': 'p'})
        add_node(self.graph, '2', {'name': 'BND'})
        add_node(self.graph, '3', {'name': 'Grb2', 'aa': 'S', 'loc': 90})
        add_node(self.graph, '4', {'name': 'SH2'})
        add_node(self.graph, '5', {'name': 'EGFR'})
        add_node(self.graph, '6', {'name': 'BND'})
        add_node(self.graph, '7', {'name': 'Grb2'})
        add_node(self.graph, '8', {'name': 'WAF1'})
        add_node(self.graph, '9', {'name': 'BND'})
        add_node(self.graph, '10', {'name': 'G1-S/CDK', 'state': 'p'})
        add_node(self.graph, '11')
        add_node(self.graph, '12')
        add_node(self.graph, '13')

        edges = [('1', '2', {
            's': 'p'
        }), ('4', '2', {
            's': 'u'
        }), ('4', '3'), ('5', '6', {
            's': 'p'
        }), ('7', '6', {
            's': 'u'
        }), ('8', '9'), ('9', '8'), ('10', '8', {
            "a": {1}
        }), ('10', '9', {
            "a": {2}
        }), ('11', '12'), ('12', '11'), ('12', '13'), ('13', '12'),
                 ('11', '13'), ('13', '11'), ('5', '2', {
                     's': 'u'
                 })]

        add_edges_from(self.graph, edges)

    def test_add_node(self):
        attrs = {"a": {1}}
        add_node(self.graph, "a", attrs)
        assert ("a" in self.graph.nodes())
        normalize_attrs(attrs)
        assert (self.graph.get_node("a") == attrs)
        assert (id(attrs) != id(self.graph.get_node("a")))

    def test_remove_node(self):
        try:
            remove_node(self.graph, "b")
            raise ValueError()
        except:
            pass
        node_to_remove = '13'
        in_edges = list(self.graph.in_edges(node_to_remove))
        out_edges = list(self.graph.out_edges(node_to_remove))
        remove_node(self.graph, node_to_remove)
        assert (node_to_remove not in self.graph.nodes())
        for edge in in_edges + out_edges:
            assert (edge not in self.graph.edges())

    def test_add_edge(self):
        try:
            add_edge(self.graph, '1', '2')
            raise ValueError("")
        except:
            pass

        s = '1'
        t = '5'
        attrs = {"a": {1}}
        add_edge(self.graph, s, t, attrs)
        normalize_attrs(attrs)
        assert ((s, t) in self.graph.edges())
        assert (self.graph.get_edge(s, t) == attrs)
        assert (id(self.graph.get_edge(s, t)) != id(attrs))

    def test_remove_edge(self):
        # g = self.graph.to_undirected()

        remove_edge(self.graph, '11', '12')
        assert (('11', '12') not in self.graph.nodes())

    def test_update_node_attrs(self):
        new_attr = {"b": {1}}
        add_node_attrs(self.graph, '1', new_attr)
        assert (id(self.graph.get_node('1')) != id(new_attr))

    def test_clone_node(self):
        node_to_clone = '1'

        in_edges = self.graph.in_edges(node_to_clone)
        out_edges = self.graph.out_edges(node_to_clone)

        new_name = clone_node(self.graph, node_to_clone)

        assert (new_name in self.graph.nodes())
        assert (self.graph.get_node(new_name) == self.graph.get_node(
            node_to_clone))
        assert (id(self.graph.get_node(new_name)) != id(
            self.graph.get_node(node_to_clone)))
        for u, _ in in_edges:
            assert ((u, new_name) in self.graph.edges())
            assert (self.graph.get_edge(u,
                                        node_to_clone) == self.graph.get_edge(
                                            u, new_name))
            assert (id(self.graph.get_edge(u, node_to_clone)) != id(
                self.graph.get_edge(u, new_name)))
        for _, v in out_edges:
            assert ((new_name, v) in self.graph.edges())

    def test_clone_node_undirected(self):
        g = self.graph
        node_to_clone = '1'
        new_name = 'a'
        new_node = clone_node(g, node_to_clone, new_name)
        assert (new_name in g.nodes())
        assert (g.get_node(new_name) == self.graph.get_node(node_to_clone))
        assert (id(g.get_node(new_name)) != id(
            self.graph.get_node(node_to_clone)))

    def test_merge_nodes(self):
        g = self.graph

        old_attrs1 = self.graph.get_node('8')
        old_attrs2 = self.graph.get_node('9')
        old_edge_attrs1 = self.graph.get_edge('10', '8')
        old_edge_attrs2 = self.graph.get_edge('10', '9')
        new_name = merge_nodes(self.graph, ["8", "9"])
        assert (new_name in self.graph.nodes())
        assert ("8" not in self.graph.nodes())
        assert ("9" not in self.graph.nodes())
        assert (valid_attributes(old_attrs1, self.graph.get_node(new_name)))
        assert (valid_attributes(old_attrs2, self.graph.get_node(new_name)))
        assert ((new_name, new_name) in self.graph.edges())
        assert (valid_attributes(old_edge_attrs1,
                                 self.graph.get_edge('10', new_name)))
        assert (valid_attributes(old_edge_attrs2,
                                 self.graph.get_edge('10', new_name)))

    def test_relabel_node(self):
        g = self.graph
        relabel_node(g, '1', 'a')
        assert ('1' not in g.nodes())
        assert ('a' in g.nodes())

    def test_subtract(self):
        g = copy.deepcopy(self.graph)
        remove_node(g, '1')
        remove_node(g, '4')
        remove_node(g, '2')
        sub_graph = subtract(self.graph, g, identity(g, self.graph))
        assert ('1' in sub_graph.nodes())
        assert (('4', '2') in sub_graph.edges())

    def test_append_to_node_names(self):
        g = copy.deepcopy(self.graph)
        mapping = dict((str(n) + '_lala', n) for n in g.nodes())
        append_to_node_names(g, 'lala')
        relabel_nodes(g, mapping)
        assert (set(g.nodes()) == set(self.graph.nodes()))

    # def test_from_json_like(self):
    #     pass

    # def test_to_json_like(self):
    #     pass

    def test_load_export(self):
        g1 = load_networkx_graph("tests/graph_example.json")
        export_graph(g1, "tests/graph_output.json")
        g2 = load_networkx_graph("tests/graph_output.json")
        assert (set(g1.nodes()) == set(g2.nodes()))
        assert (set(g1.edges()) == set(g2.edges()))

    def test_find_matching(self):
        pattern = NXGraph()
        add_nodes_from(pattern, [(1, {
            'state': 'p'
        }), (2, {
            'name': 'BND'
        }), (3), (4)])
        add_edges_from(pattern, [(1, 2, {
            's': 'p'
        }), (3, 2, {
            's': 'u'
        }), (3, 4)])
        find_matching(self.graph, pattern)
        # assert smth here

    def test_rewrite(self):
        pattern = NXGraph()
        add_nodes_from(pattern, [(1, {
            'state': 'p'
        }), (2, {
            'name': 'BND'
        }), 3, 4])
        add_edges_from(pattern, [(1, 2, {
            's': 'p'
        }), (3, 2, {
            's': 'u'
        }), (3, 4)])

        p = NXGraph()
        add_nodes_from(p, [(1, {'state': 'p'}), (2, {'name': 'BND'}), 3, 4])
        p.add_edges_from([(1, 2), (3, 4)])

        rhs = NXGraph()
        add_nodes_from(rhs, [(1, {
            'state': 'p'
        }), (2, {
            'name': 'BND'
        }), (3, {
            'merged': 'yes'
        }), (4, {
            'new': 'yes'
        })])

        add_edges_from(rhs, [(1, 2, {
            's': 'u'
        }), (2, 4), (3, 3), (3, 4, {
            'from': 'merged'
        })])

        p_lhs = {1: 1, 2: 2, 3: 3, 4: 4}
        p_rhs = {1: 1, 2: 2, 3: 3, 4: 3}

        rule = Rule(p, pattern, rhs, p_lhs, p_rhs)
        # instances = find_matching_with_types(self.graph, rule.lhs, {}, {}, {})
        instances = self.graph.find_matching(rule.lhs)
        self.graph.rewrite(rule, instances[0])
Exemplo n.º 2
0
class TestGraphClasses:
    """Main test class."""
    def __init__(self):
        """Initialize test object."""
        self.nx_graph = NXGraph()
        try:
            self.neo4j_graph = Neo4jGraph(uri="bolt://localhost:7687",
                                          user="******",
                                          password="******")
            self.neo4j_graph._clear()
        except:
            warnings.warn("Neo4j is down, skipping Neo4j-related tests")
            self.neo4j_graph = None

        node_list = [("b", {
            "name": "Bob",
            "age": 20
        }), ("a", {
            "name": "Alice",
            "age": 35
        }), ("d", {
            "name": "dummy"
        })]

        edge_list = [("a", "b", {
            "type": "friends",
            "since": 1999
        }), ("d", "a"), ("b", "d")]

        self.nx_graph.add_nodes_from(node_list)
        self.nx_graph.add_edges_from(edge_list)

        if self.neo4j_graph:
            self.neo4j_graph.add_nodes_from(node_list)
            self.neo4j_graph.add_edges_from(edge_list)

        node = "c"
        attrs = {"name": "Claire", "age": 66}
        self.nx_graph.add_node(node, attrs)
        if self.neo4j_graph:
            self.neo4j_graph.add_node(node, attrs)
        edge_attrs = {"type": "parent"}
        self.nx_graph.add_edge("c", "b", edge_attrs)
        if self.neo4j_graph:
            self.neo4j_graph.add_edge("c", "b", edge_attrs)

        self.nx_graph.remove_edge("d", "a")
        if self.neo4j_graph:
            self.neo4j_graph.remove_edge("d", "a")
        self.nx_graph.remove_node("d")
        if self.neo4j_graph:
            self.neo4j_graph.remove_node("d")

        self.nx_graph.update_node_attrs("a", {"name": "Alison"})
        if self.neo4j_graph:
            self.neo4j_graph.update_node_attrs("a", {"name": "Alison"})
        self.nx_graph.update_edge_attrs("a", "b", {"type": "enemies"})
        if self.neo4j_graph:
            self.neo4j_graph.update_edge_attrs("a", "b", {"type": "enemies"})

        self.nx_graph.set_node_attrs("a", {"age": 19}, update=False)
        if self.neo4j_graph:
            self.neo4j_graph.set_node_attrs("a", {"age": 19}, update=False)
        self.nx_graph.set_edge_attrs("a", "b", {"since": 1945}, update=False)
        if self.neo4j_graph:
            self.neo4j_graph.set_edge_attrs("a",
                                            "b", {"since": 1945},
                                            update=False)

        self.nx_graph.add_node_attrs("a", {"gender": {"M", "F"}})
        if self.neo4j_graph:
            self.neo4j_graph.add_node_attrs("a", {"gender": {"M", "F"}})
        self.nx_graph.add_edge_attrs("a", "b", {"probability": 0.5})
        if self.neo4j_graph:
            self.neo4j_graph.add_edge_attrs("a", "b", {"probability": 0.5})

        self.nx_graph.remove_node_attrs("a", {"gender": "F"})
        if self.neo4j_graph:
            self.neo4j_graph.remove_node_attrs("a", {"gender": "F"})
        self.nx_graph.remove_edge_attrs("a", "b", {"probability": 0.5})
        if self.neo4j_graph:
            self.neo4j_graph.remove_edge_attrs("a", "b", {"probability": 0.5})

        clone_id = self.nx_graph.clone_node("b", "b_clone")
        if self.neo4j_graph:
            self.neo4j_graph.clone_node("b", "b_clone")

        # Test relabeling
        self.nx_graph.relabel_node("b", "baba")
        if self.neo4j_graph:
            self.neo4j_graph.relabel_node("b", "baba")
        self.nx_graph.relabel_node("baba", "b")
        if self.neo4j_graph:
            self.neo4j_graph.relabel_node("baba", "b")
        self.nx_graph.relabel_nodes({
            clone_id: "lala",
            "b": "b1",
            "a": "a1",
            "c": "c1"
        })
        if self.neo4j_graph:
            self.neo4j_graph.relabel_nodes({
                clone_id: "lala",
                "b": "b1",
                "a": "a1",
                "c": "c1"
            })
        self.nx_graph.relabel_nodes({
            "b1": "b",
            "a1": "a",
            "c1": "c",
            "lala": clone_id
        })
        if self.neo4j_graph:
            self.neo4j_graph.relabel_nodes({
                "b1": "b",
                "a1": "a",
                "c1": "c",
                "lala": clone_id
            })

        self.nx_graph.merge_nodes(["b", "c"])
        if self.neo4j_graph:
            self.neo4j_graph.merge_nodes(["b", "c"])

        self.nx_graph.copy_node("a", "a_copy")
        if self.neo4j_graph:
            self.neo4j_graph.copy_node("a", "a_copy")

        # Test find matching
        pattern = NXGraph()
        pattern.add_nodes_from(["x", ("y", {"name": "Claire"}), "z"])
        pattern.add_edges_from([("x", "y"), ("y", "y"), ("y", "z")])
        instances1 = self.nx_graph.find_matching(pattern)
        if self.neo4j_graph:
            instances2 = self.neo4j_graph.find_matching(pattern)
            assert (instances1 == instances2)

        rule = Rule.from_transform(pattern)
        p_n, r_n = rule.inject_clone_node("y")
        rule.inject_remove_edge(p_n, "y")
        rule.inject_remove_edge("y", "y")
        rule.inject_add_node("w", {"name": "Frank"})
        rule.inject_add_edge("w", r_n, {"type": "parent"})
        rhs_g1 = self.nx_graph.rewrite(rule, instances1[0])
        if self.neo4j_graph:
            rhs_g2 = self.neo4j_graph.rewrite(rule, instances1[0])

        self.nx_graph.relabel_node(rhs_g1[r_n], "b")
        if self.neo4j_graph:
            self.neo4j_graph.relabel_node(rhs_g2[r_n], "b")
        self.nx_graph.relabel_node(rhs_g1["y"], "c")
        if self.neo4j_graph:
            self.neo4j_graph.relabel_node(rhs_g2["y"], "c")
            # Test the two obtained graphs are the same
            assert (self.nx_graph == self.neo4j_graph)
            assert (set(self.nx_graph.predecessors("b")) == set(
                self.neo4j_graph.predecessors("b")))
            assert (set(self.nx_graph.successors("a")) == set(
                self.neo4j_graph.successors("a")))
            assert (
                self.nx_graph.get_node("c") == self.neo4j_graph.get_node("c"))
            assert (self.nx_graph.get_edge("c",
                                           "b") == self.neo4j_graph.get_edge(
                                               "c", "b"))

    def test_getters(self):
        """Test various getters."""
        if self.neo4j_graph:
            assert (set(self.nx_graph.nodes()) == set(
                self.neo4j_graph.nodes()))
            assert (set(self.nx_graph.edges()) == set(
                self.neo4j_graph.edges()))
            self.neo4j_graph.nodes(data=True)
            self.neo4j_graph.edges(data=True)
            assert (
                self.nx_graph.get_node("a") == self.neo4j_graph.get_node("a"))
            assert (self.nx_graph.get_edge("a",
                                           "b") == self.neo4j_graph.get_edge(
                                               "a", "b"))
            assert (set(self.nx_graph.in_edges("b")) == set(
                self.neo4j_graph.in_edges("b")))
            assert (set(self.nx_graph.out_edges("a")) == set(
                self.neo4j_graph.out_edges("a")))

    def test_load_export(self):
        self.nx_graph.export("nxgraph.json")
        if self.neo4j_graph:
            self.neo4j_graph.export("neo4jgraph.json")

        g1 = NXGraph.load("nxgraph.json")
        if self.neo4j_graph:
            p = Neo4jGraph(driver=self.neo4j_graph._driver,
                           node_label="new_node",
                           edge_label="new_edge")
            p._clear()
            g2 = Neo4jGraph.load(driver=self.neo4j_graph._driver,
                                 filename="neo4jgraph.json",
                                 node_label="new_node",
                                 edge_label="new_edge")
            assert (g1 == g2)