Пример #1
0
    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)
Пример #2
0
    def test_add_relation(self):
        self.hierarchy.add_relation(
            "a2", "a1", {
                "right_circle": {"white_circle", "black_circle"},
                "middle_square": "white_square",
                "left_circle": "black_circle"
            }, {"name": "Some relation"})

        g, l, r = self.hierarchy.relation_to_span("a1",
                                                  "a2",
                                                  edges=True,
                                                  attrs=True)
        # print_graph(g)
        # print(l)
        # print(r)
        # print(self.hierarchy)
        # self.hierarchy.remove_graph("a1")
        # print(self.hierarchy.relation)

        lhs = NXGraph()
        lhs.add_nodes_from(["s", "c"])

        rule = Rule.from_transform(lhs)
        rule.inject_clone_node("s")

        # instances = self.hierarchy.find_matching(
        #     "base",
        #     rule.lhs
        # )

        self.hierarchy.rewrite("base", rule, {"s": "square", "c": "circle"})
Пример #3
0
    def test_triangle_1(self):
        h = self._generate_triangle_hierarchy()

        pattern = NXGraph()
        pattern.add_nodes_from([1, 2])
        rule = Rule.from_transform(pattern)
        rule.inject_remove_node(1)
        rule.inject_clone_node(2)

        instances = h.find_matching("g1", pattern)
        h.rewrite("g1", rule, instances[0])
Пример #4
0
    def __init__(self, graph=None, meta_typing=None,
                 reference_typing=None):
        """Initialize graph container."""
        if graph:
            self.graph = NXGraph.copy(graph)
        else:
            self.graph = NXGraph()

        if meta_typing:
            self.meta_typing = copy.deepcopy(meta_typing)
        else:
            self.meta_typing = dict()
        if reference_typing:
            self.reference_typing = copy.deepcopy(reference_typing)
        else:
            self.reference_typing = dict()
        return
Пример #5
0
    def test_porpagation_node_attrs_adds(self):
        p = NXGraph()
        primitives.add_nodes_from(p, [1, 2])

        lhs = NXGraph()
        primitives.add_nodes_from(lhs, [1, 2])

        rhs = NXGraph()
        primitives.add_nodes_from(rhs, [(1, {
            "a1": True
        }), (2, {
            "a2": 1
        }), (3, {
            "a3": "x"
        })])

        rule = Rule(p, lhs, rhs)
        instance = {1: "A", 2: "A_res_1"}

        rhs_typing = {"mm": {3: "state"}}

        try:
            self.hierarchy.rewrite("n1",
                                   rule,
                                   instance,
                                   rhs_typing=rhs_typing,
                                   strict=True)
            raise ValueError("Error was not caught!")
        except RewritingError:
            pass

        new_hierarchy = NXHierarchy.copy(self.hierarchy)

        new_hierarchy.rewrite("n1", rule, instance, rhs_typing=rhs_typing)

        # test propagation of the node attribute adds
        assert ("a1" in new_hierarchy.get_graph("n1").get_node("A"))
        assert ("a2" in new_hierarchy.get_graph("n1").get_node("A_res_1"))
        assert ("a3" in new_hierarchy.get_graph("n1").get_node(3))

        assert ("a1" in new_hierarchy.get_graph("ag").get_node("A"))
        assert ("a2" in new_hierarchy.get_graph("ag").get_node("A_res_1"))
        assert ("a3" in new_hierarchy.get_graph("ag").get_node(3))
Пример #6
0
    def test_controlled_backward(self):
        h = self._generate_triangle_hierarchy()
        pattern = NXGraph()
        pattern.add_nodes_from(["1"])
        rule = Rule.from_transform(pattern)
        rule.inject_clone_node("1", "11")

        p_typing = {
            "g2": {
                "1a": {"1"},
                "1b": {"11"}
            },
        }

        old_g3_nodes = h.get_graph("g3").nodes(True)
        old_g2_nodes = h.get_graph("g2").nodes(True)

        h.rewrite("g1", rule, {"1": "1"}, p_typing=p_typing)

        # assert(old_g3_nodes == h.get_graph("g3").nodes(True))
        assert (old_g2_nodes == h.get_graph("g2").nodes(True))
Пример #7
0
    def test_find_matching(self):
        pattern = NXGraph()
        pattern.add_nodes_from([1, (2, {"a": 1}), 3])
        pattern.add_edges_from([(1, 2), (2, 3)])
        pattern_typing = {1: "circle", 2: "square", 3: "triangle"}

        nxinstances = self.nx_hierarchy.find_matching(graph_id="g1",
                                                      pattern=pattern,
                                                      pattern_typing={
                                                          "g0": pattern_typing,
                                                          "g00": {
                                                              1: "white",
                                                              2: "white",
                                                              3: "black"
                                                          }
                                                      })
        if self.neo4j_hierarchy:
            n4instances = self.neo4j_hierarchy.find_matching(
                graph_id="g1",
                pattern=pattern,
                pattern_typing={
                    "g0": pattern_typing,
                    "g00": {
                        1: "white",
                        2: "white",
                        3: "black"
                    }
                })

        assert (len(nxinstances) == 1)
        if self.neo4j_hierarchy:
            assert (n4instances == nxinstances)
Пример #8
0
    def test_controlled_forward(self):
        h = self._generate_triangle_hierarchy()
        pattern = NXGraph()
        pattern.add_nodes_from(["1a"])
        rule = Rule.from_transform(pattern)
        rule.inject_add_node("1c")

        rhs_typing = {"g3": {"1c": "1x"}}

        old_g3_nodes = h.get_graph("g3").nodes(True)
        old_g1_nodes = h.get_graph("g1").nodes(True)

        h.rewrite("g2", rule, {"1a": "1a"}, rhs_typing=rhs_typing)

        assert (old_g3_nodes == h.get_graph("g3").nodes(True))
        assert (old_g1_nodes == h.get_graph("g1").nodes(True))

        rhs_typing = {"g1": {"1c": "1"}}

        h.rewrite("g2", rule, {"1a": "1a"}, rhs_typing=rhs_typing)
        assert (old_g1_nodes == h.get_graph("g1").nodes(True))
        assert (len(old_g3_nodes) + 1 == len(h.get_graph("g3").nodes()))
Пример #9
0
    def test_controlled_up_propagation(self):
        pattern = NXGraph()
        pattern.add_nodes_from(["A"])
        rule = Rule.from_transform(pattern)
        p_clone, _ = rule.inject_clone_node("A")
        rule.inject_add_node("D")

        p_typing = {
            "nn1": {
                "A_bye": set(),
                "A_hello": {p_clone}
            },
            "n1": {
                "A": p_clone
            }
        }

        instance = {"A": "A"}

        nugget_1 = NXGraph()
        primitives.add_nodes_from(
            nugget_1, ["A_bye", "A_hello", "A_res_1", "p", "B", "mod"])
        primitives.add_edges_from(nugget_1, [("A_res_1", "A_hello"),
                                             ("A_res_1", "A_bye"),
                                             ("p", "A_res_1"), ("mod", "p"),
                                             ("B", "mod")])
        self.hierarchy.add_graph("nn1", nugget_1)
        self.hierarchy.add_typing(
            "nn1", "n1", {
                "A_bye": "A",
                "A_hello": "A",
                "A_res_1": "A_res_1",
                "p": "p",
                "B": "B",
                "mod": "mod"
            })

        new_hierarchy = NXHierarchy.copy(self.hierarchy)
        new_hierarchy.rewrite("ag", rule, instance, p_typing=p_typing)
Пример #10
0
 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)
Пример #11
0
    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)
Пример #12
0
    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])
Пример #13
0
    def test_pushout_symmetry_directed(self):

        A = NXGraph()
        A.add_nodes_from(["a", "b"])
        A.add_edges_from([("a", "b")])

        B = NXGraph()
        B.add_nodes_from([1, 2, 3])
        B.add_edges_from([(2, 3), (3, 2), (1, 3)])

        C = NXGraph()
        C.add_nodes_from(["x", "y"])
        C.add_edges_from([("x", "x"), ("x", "y")])

        homAB = {"a": 2, "b": 3}
        homAC = {"a": "x", "b": "x"}

        D, homBD, homCD = pushout(
            A, B, C, homAB, homAC
        )
        D_inv, homCD_inv, homBD_inv = pushout(
            A, C, B, homAC, homAB
        )
        assert_equals(len(D.nodes()), len(D_inv.nodes()))
        assert_equals(len(D.edges()), len(D_inv.edges()))
Пример #14
0
    def test_add_typing_advanced(self):
        hierarchy = NXHierarchy()

        g9 = NXGraph()
        g9.add_nodes_from(["a", "b"])
        hierarchy.add_graph(9, g9)

        g8 = NXGraph()
        g8.add_nodes_from(["1_a", "1_b", "2_a", "2_b"])
        hierarchy.add_graph(8, g8)

        hierarchy.add_typing(
            8,
            9,
            {
                "1_a": "a",
                "1_b": "b",
                "2_a": "a",
                "2_b": "b"
            },
        )

        g7 = NXGraph()
        g7.add_nodes_from(["x_a", "x_b", "y_a", "y_b"])
        hierarchy.add_graph(7, g7)

        hierarchy.add_typing(
            7,
            9,
            {
                "x_a": "a",
                "x_b": "b",
                "y_a": "a",
                "y_b": "b"
            },
        )

        g2 = NXGraph()
        g2.add_nodes_from(["s_1_a", "t_1_a", "s_1_b", "t_2_a"])
        hierarchy.add_graph(2, g2)

        hierarchy.add_typing(2, 8, {
            "s_1_a": "1_a",
            "t_1_a": "1_a",
            "s_1_b": "1_b",
            "t_2_a": "2_a"
        })

        g3 = NXGraph()
        g3.add_nodes_from(["s_x_a", "t_x_a", "g_y_b"])
        hierarchy.add_graph(3, g3)

        hierarchy.add_typing(3, 7, {
            "s_x_a": "x_a",
            "t_x_a": "x_a",
            "g_y_b": "y_b"
        })

        g4 = NXGraph()
        g4.add_nodes_from(["a_x_a", "t_y_b"])
        hierarchy.add_graph(4, g4)

        hierarchy.add_typing(4, 3, {"a_x_a": "s_x_a", "t_y_b": "g_y_b"})

        hierarchy.add_typing(4, 7, {"a_x_a": "x_a", "t_y_b": "y_b"})

        g6 = NXGraph()
        g6.add_nodes_from(["a_x_a", "b_x_a", "a_y_b", "b_y_a", "c_x_b"])
        hierarchy.add_graph(6, g6)

        hierarchy.add_typing(
            6, 7, {
                "a_x_a": "x_a",
                "b_x_a": "x_a",
                "a_y_b": "y_b",
                "b_y_a": "y_a",
                "c_x_b": "x_b"
            })

        g5 = NXGraph()
        g5.add_nodes_from(["1_a_x_a", "2_a_x_a", "1_a_y_b"])
        hierarchy.add_graph(5, g5)

        hierarchy.add_typing(5, 6, {
            "1_a_x_a": "a_x_a",
            "2_a_x_a": "a_x_a",
            "1_a_y_b": "a_y_b"
        })

        hierarchy.add_typing(5, 4, {
            "1_a_x_a": "a_x_a",
            "2_a_x_a": "a_x_a",
            "1_a_y_b": "t_y_b"
        })

        g1 = NXGraph()
        g1.add_nodes_from(["1_s_1_a", "2_s_1_a", "1_s_1_b"])
        hierarchy.add_graph(1, g1)

        hierarchy.add_typing(1, 2, {
            "1_s_1_a": "s_1_a",
            "2_s_1_a": "s_1_a",
            "1_s_1_b": "s_1_b"
        })

        hierarchy.add_typing(1, 3, {
            "1_s_1_a": "s_x_a",
            "2_s_1_a": "t_x_a",
            "1_s_1_b": "g_y_b"
        })
        # start testing
        hierarchy.add_typing(3, 8, {
            "s_x_a": "1_a",
            "t_x_a": "1_a",
            "g_y_b": "1_b"
        })
        hierarchy.add_typing(6, 9, {
            "a_x_a": "a",
            "b_x_a": "b",
            "a_y_b": "b",
            "b_y_a": "a",
            "c_x_b": "b"
        })
Пример #15
0
    def _generate_triangle_hierarchy():
        h = NXHierarchy()

        g1 = NXGraph()
        g1.add_nodes_from(["1", "2"])

        g2 = NXGraph()
        g2.add_nodes_from(["1a", "1b", "2a", "2b"])

        g3 = NXGraph()
        g3.add_nodes_from(["1x", "1y", "2x", "2y"])

        h.add_graph("g1", g1)
        h.add_graph("g2", g2)
        h.add_graph("g3", g3)
        h.add_typing("g2", "g1", {"1a": "1", "1b": "1", "2a": "2", "2b": "2"})
        h.add_typing("g3", "g1", {"1x": "1", "1y": "1", "2x": "2", "2y": "2"})
        h.add_typing("g2", "g3", {
            "1a": "1x",
            "1b": "1y",
            "2a": "2y",
            "2b": "2x"
        })
        return h
Пример #16
0
    def test_neo4j_hierarchy_versioning(self):
        """Test hierarchy versioning functionality."""
        try:
            hierarchy = Neo4jHierarchy(uri="bolt://localhost:7687",
                                       user="******",
                                       password="******")
            hierarchy._clear()
            hierarchy.add_graph(
                "shapes", node_list=[
                    ("c", {"a": 1}),
                    ("s", {"b": 2})])
            hierarchy.add_graph("colors", node_list=[
                ("w", {"a": 1, "b": 2}),
                ("b", {"a": 1, "b": 2})])
            hierarchy.add_graph("ag", node_list=[
                ("wc", {"a": 1}),
                "bc", 
                "ws",
                ("bs", {"b": 2})])
            hierarchy.add_graph(
                "nugget", node_list=[
                    ("wc1", {"a": 1}),
                    "wc2", "bc1", "ws1",
                    ("bs2", {"b": 2})])

            hierarchy.add_typing(
                "ag", "shapes", {
                    "wc": "c",
                    "bc": "c",
                    "ws": "s",
                    "bs": "s"
                })
            hierarchy.add_typing(
                "ag", "colors", {
                    "wc": "w",
                    "bc": "b",
                    "ws": "w",
                    "bs": "b"
                })
            hierarchy.add_typing(
                "nugget", "ag", {
                    "wc1": "wc",
                    "wc2": "wc",
                    "bc1": "bc",
                    "ws1": "ws",
                    "bs2": "bs"
                })
            hierarchy.add_typing(
                "nugget", "colors", {
                    "wc1": "w",
                    "wc2": "w",
                    "bc1": "b",
                    "ws1": "w",
                    "bs2": "b"
                })

            hierarchy.add_graph("base", node_list=[
                ("node", {"a": 1, "b": 2})])
            hierarchy.add_typing(
                "colors",
                "base", {
                    "w": "node",
                    "b": "node"
                })

            pattern = NXGraph()
            pattern.add_nodes_from(["s", "c"])
            rule = Rule.from_transform(pattern)
            rule.inject_add_edge("s", "c", {"c": 3})

            hierarchy.rewrite(
                "nugget",
                rule,
                {"s": "bs2", "c": "wc1"})

            h = VersionedHierarchy(hierarchy)
            rollback_commit = h._heads["master"]

            pattern = NXGraph()
            primitives.add_nodes_from(
                pattern,
                [("s", {"b": 2}),
                 ("c", {"a": 1})])
            primitives.add_edges_from(
                pattern,
                [("s", "c", {"c": 3})])
            rule2 = Rule.from_transform(pattern)
            clone, _ = rule2.inject_clone_node("s")
            rule2.inject_add_node("new_node")
            rule2.inject_add_edge("new_node", "s", {"d": 4})
            merged_rule_node = rule2.inject_merge_nodes([clone, "c"])
            rule2.inject_remove_edge("s", "c")

            rhs_instances, first_commit = h.rewrite(
                "ag", rule2, {"s": "bs", "c": "wc"},
                message="Rewriting neo4j graph")

            merged_ag_node = rhs_instances["ag"][merged_rule_node]

            h.branch('test')

            pattern = NXGraph()
            pattern.add_nodes_from(["ws"])
            rule3 = Rule.from_transform(pattern)
            rule3.inject_remove_node("ws")

            h.rewrite(
                "ag", rule3, {"ws": "ws"},
                message="Removed ws from ag")

            h.switch_branch("master")

            pattern = NXGraph()
            pattern.add_nodes_from([merged_ag_node])
            rule4 = Rule.from_transform(pattern)
            rule4.inject_clone_node(merged_ag_node)

            h.rewrite(
                "ag", rule4, {merged_ag_node: merged_ag_node},
                message="Cloned merged from ag")
            h.merge_with("test")

            data = h.to_json()
            h1 = VersionedHierarchy.from_json(hierarchy, data)
            h1.print_history()
            h1.rollback(rollback_commit)
        # except ServiceUnavailable as e:
        #     print(e)
        except:
            print()
Пример #17
0
    def test_rewrite(self):
        pattern = NXGraph()
        pattern.add_nodes_from([1, (2, {"a": {1, 2}}), 3])
        pattern.add_edges_from([(1, 2), (2, 3)])
        lhs_typing = {
            "g0": {
                1: "circle",
                2: "square",
                3: "triangle"
            },
            "g00": {
                1: "white",
                2: "white",
                3: "black"
            }
        }

        p = NXGraph()
        p.add_nodes_from([1, 2, 3])
        p.add_edges_from([(2, 3)])

        rhs = NXGraph()
        rhs.add_nodes_from([1, (2, {"a": {3, 5}}), (3, {"new_attrs": {1}}), 4])
        rhs.add_edges_from([(2, 1, {
            "new_attrs": {2}
        }), (2, 4, {
            "new_attrs": {3}
        }), (2, 3, {
            "new_attrs": {4}
        })])
        p_lhs = {1: 1, 2: 2, 3: 3}
        p_rhs = {1: 1, 2: 2, 3: 3}

        rule = Rule(p, pattern, rhs, p_lhs, p_rhs)
        rhs_typing = {
            "g0": {
                1: "circle",
                2: "square",
                3: "triangle",
                4: "triangle"
            },
            "g00": {
                1: "white",
                2: "white",
                3: "black",
                4: "black"
            }
        }

        instances = self.nx_hierarchy.find_matching("g1",
                                                    pattern,
                                                    pattern_typing=lhs_typing)

        old_g0_nodes = self.nx_hierarchy.get_graph("g0").nodes(data=True)
        old_g0_edges = self.nx_hierarchy.get_graph("g0").edges(data=True)
        old_g00_nodes = self.nx_hierarchy.get_graph("g00").nodes(data=True)
        old_g00_edges = self.nx_hierarchy.get_graph("g00").edges(data=True)

        self.nx_hierarchy.rewrite("g1",
                                  rule,
                                  instances[0],
                                  rhs_typing=rhs_typing)

        assert (set([n[0] for n in old_g0_nodes
                     ]) == set(self.nx_hierarchy.get_graph("g0").nodes()))
        assert (set([(n[0], n[1]) for n in old_g0_edges
                     ]) == set(self.nx_hierarchy.get_graph("g0").edges()))
        assert (set([n[0] for n in old_g00_nodes
                     ]) == set(self.nx_hierarchy.get_graph("g00").nodes()))
        assert (set([(n[0], n[1]) for n in old_g00_edges
                     ]) == set(self.nx_hierarchy.get_graph("g00").edges()))

        for n, attrs in old_g0_nodes:
            assert (self.nx_hierarchy.get_graph("g0").get_node(n) == attrs)

        for s, t, attrs in old_g0_edges:
            assert (self.nx_hierarchy.get_graph("g0").get_edge(s, t) == attrs)

        for n, attrs in old_g00_nodes:
            assert (self.nx_hierarchy.get_graph("g00").get_node(n) == attrs)

        for s, t, attrs in old_g00_edges:
            assert (self.nx_hierarchy.get_graph("g00").get_edge(s, t) == attrs)

        if self.neo4j_hierarchy:
            instances = self.neo4j_hierarchy.find_matching(
                "g1", pattern, pattern_typing=lhs_typing)

        if self.neo4j_hierarchy:
            old_g0_nodes = self.neo4j_hierarchy.get_graph("g0").nodes(
                data=True)
            old_g0_edges = self.neo4j_hierarchy.get_graph("g0").edges(
                data=True)
            old_g00_nodes = self.neo4j_hierarchy.get_graph("g00").nodes(
                data=True)
            old_g00_edges = self.neo4j_hierarchy.get_graph("g00").edges(
                data=True)
            self.neo4j_hierarchy.rewrite("g1",
                                         rule,
                                         instances[0],
                                         rhs_typing=rhs_typing)

            assert (set([n[0] for n in old_g0_nodes]) == set(
                self.neo4j_hierarchy.get_graph("g0").nodes()))
            assert (set([
                (n[0], n[1]) for n in old_g0_edges
            ]) == set(self.neo4j_hierarchy.get_graph("g0").edges()))
            assert (set([n[0] for n in old_g00_nodes]) == set(
                self.neo4j_hierarchy.get_graph("g00").nodes()))
            assert (set([
                (n[0], n[1]) for n in old_g00_edges
            ]) == set(self.neo4j_hierarchy.get_graph("g00").edges()))

            for n, attrs in old_g0_nodes:
                assert (
                    self.neo4j_hierarchy.get_graph("g0").get_node(n) == attrs)

            for s, t, attrs in old_g0_edges:
                assert (self.neo4j_hierarchy.get_graph("g0").get_edge(
                    s, t) == attrs)

            for n, attrs in old_g00_nodes:
                assert (
                    self.neo4j_hierarchy.get_graph("g00").get_node(n) == attrs)

            for s, t, attrs in old_g00_edges:
                assert (self.neo4j_hierarchy.get_graph("g00").get_edge(
                    s, t) == attrs)
Пример #18
0
    def __init__(self):
        D = NXGraph()

        D.add_node('square')
        D.add_node('circle')
        D.add_node('dark_square')
        D.add_node('dark_circle')
        D.add_edge('square', 'circle')
        D.add_edge('circle', 'dark_circle')
        D.add_edge('circle', 'dark_square')
        D.add_edge('circle', 'circle')

        self.D = D

        A = NXGraph()

        A.add_node(2)
        A.add_node(3)
        A.add_edge(2, 3)

        self.A = A

        B = NXGraph()

        B.add_node(1)
        B.add_node(2)
        B.add_node(3)
        B.add_edge(1, 2)
        B.add_edge(2, 3)

        self.B = B

        C = NXGraph()

        C.add_node(2)
        C.add_node(3)
        C.add_node('dark_square')

        C.add_edge(2, 3)
        C.add_edge(2, 'dark_square')
        C.add_edge(2, 2)

        self.C = C

        self.homAB = {
            2: 2,
            3: 3
        }
        self.homAC = {
            2: 2,
            3: 3
        }
        self.homBD = {
            1: 'square',
            2: 'circle',
            3: 'dark_circle'
        }

        self.homCD = {
            2: 'circle',
            3: 'dark_circle',
            'dark_square': 'dark_square'
        }
Пример #19
0
    def __init__(self):
        """Initialize hierarchies."""
        self.nx_hierarchy = NXHierarchy()
        try:
            self.neo4j_hierarchy = Neo4jHierarchy(uri="bolt://localhost:7687",
                                                  user="******",
                                                  password="******")
            self.neo4j_hierarchy._clear()
        except:
            warnings.warn("Neo4j is down, skipping Neo4j-related tests")
            self.neo4j_hierarchy = None

        g0 = NXGraph()
        g0.add_node("circle", {"a": {1, 2, 3}})
        g0.add_node("square", {"a": {1, 2, 3, 5}})
        g0.add_node("triangle", {"new_attrs": {1}})
        g0.add_edges_from([
            ("circle", "circle"),  # , {"b": {1, 2, 3, 4}}),
            ("circle", "square"),
            ("square", "circle", {
                "new_attrs": {2}
            }),
            ("square", "triangle", {
                "new_attrs": {3, 4}
            })
        ])
        self.nx_hierarchy.add_graph("g0", g0, {"name": "Shapes"})
        if self.neo4j_hierarchy:
            self.neo4j_hierarchy.add_graph("g0", g0, {"name": "Shapes"})

        g00 = NXGraph()
        g00.add_node('black', {"a": {1, 2, 3}, "new_attrs": {1}})
        g00.add_node('white', {"a": {1, 2, 3, 5}})
        g00.add_edges_from([('white', 'white', {
            "new_attrs": 2
        }), ('white', 'black', {
            "new_attrs": {4, 3}
        }), ('black', 'black'), ('black', 'white')])
        self.nx_hierarchy.add_graph("g00", g00, {"name": "Colors"})
        if self.neo4j_hierarchy:
            self.neo4j_hierarchy.add_graph("g00", g00, {"name": "Colors"})

        g1 = NXGraph()
        g1.add_nodes_from([("black_circle", {
            "a": {1, 2, 3}
        }), "white_circle", "black_square", ("white_square", {
            "a": {1, 2}
        }), "black_triangle", "white_triangle"])

        g1.add_edges_from([
            ("black_circle", "black_circle"),  # {"b": {1, 2, 3, 4}}),
            ("black_circle", "white_circle"),
            ("black_circle", "black_square"),
            ("white_circle", "black_circle"),
            ("white_circle", "white_square"),
            ("black_square", "black_circle"),
            ("black_square", "black_triangle"),
            ("black_square", "white_triangle"),
            ("white_square", "white_circle"),
            ("white_square", "black_triangle"),
            ("white_square", "white_triangle")
        ])

        self.nx_hierarchy.add_graph("g1", g1)
        if self.neo4j_hierarchy:
            self.neo4j_hierarchy.add_graph("g1", g1)
        self.nx_hierarchy.add_typing(
            "g1", "g0", {
                "black_circle": "circle",
                "white_circle": "circle",
                "black_square": "square",
                "white_square": "square",
                "black_triangle": "triangle",
                "white_triangle": "triangle"
            })
        if self.neo4j_hierarchy:
            self.neo4j_hierarchy.add_typing(
                "g1", "g0", {
                    "black_circle": "circle",
                    "white_circle": "circle",
                    "black_square": "square",
                    "white_square": "square",
                    "black_triangle": "triangle",
                    "white_triangle": "triangle"
                })

        self.nx_hierarchy.add_typing(
            "g1", "g00", {
                "black_square": "black",
                "black_circle": "black",
                "black_triangle": "black",
                "white_square": "white",
                "white_circle": "white",
                "white_triangle": "white"
            })
        if self.neo4j_hierarchy:
            self.neo4j_hierarchy.add_typing(
                "g1", "g00", {
                    "black_square": "black",
                    "black_circle": "black",
                    "black_triangle": "black",
                    "white_square": "white",
                    "white_circle": "white",
                    "white_triangle": "white"
                })

        g2 = NXGraph()
        g2.add_nodes_from([
            (1, {
                "a": {1, 2}
            }),
            2,
            3,
            4,
            (5, {
                "a": {1}
            }),
            6,
            7,
        ])

        g2.add_edges_from([
            (1, 2),  # {"b": {1, 2, 3}}),
            (2, 3),
            (3, 6),
            (3, 7),
            (4, 2),
            (4, 5),
            (5, 7)
        ])
        self.nx_hierarchy.add_graph("g2", g2)
        if self.neo4j_hierarchy:
            self.neo4j_hierarchy.add_graph("g2", g2)
        self.nx_hierarchy.add_typing(
            "g2", "g1", {
                1: "black_circle",
                2: "black_circle",
                3: "black_square",
                4: "white_circle",
                5: "white_square",
                6: "white_triangle",
                7: "black_triangle"
            })
        if self.neo4j_hierarchy:
            self.neo4j_hierarchy.add_typing(
                "g2", "g1", {
                    1: "black_circle",
                    2: "black_circle",
                    3: "black_square",
                    4: "white_circle",
                    5: "white_square",
                    6: "white_triangle",
                    7: "black_triangle"
                })

        g3 = NXGraph()
        g3.add_nodes_from([
            (1),  # {"a": {1, 2}}),
            2,
            3,
            5,
            (4),  # {"a": {1}}),
            6,
            7,
        ])

        g3.add_edges_from([
            (1, 1),  # , {"b": {1, 2, 3}}),
            (1, 2),
            (1, 3),
            (1, 5),
            (2, 1),
            (3, 4),
            (4, 7),
            (4, 6),
            (5, 6),
            (5, 7)
        ])
        self.nx_hierarchy.add_graph("g3", g3)
        if self.neo4j_hierarchy:
            self.neo4j_hierarchy.add_graph("g3", g3)
        self.nx_hierarchy.add_typing(
            "g3", "g1", {
                1: "black_circle",
                2: "white_circle",
                3: "white_circle",
                5: "black_square",
                4: "white_square",
                6: "white_triangle",
                7: "black_triangle"
            })
        if self.neo4j_hierarchy:
            self.neo4j_hierarchy.add_typing(
                "g3", "g1", {
                    1: "black_circle",
                    2: "white_circle",
                    3: "white_circle",
                    5: "black_square",
                    4: "white_square",
                    6: "white_triangle",
                    7: "black_triangle"
                })

        g4 = NXGraph()
        g4.add_nodes_from([1, 2, 3])
        g4.add_edges_from([(1, 2), (2, 3)])

        self.nx_hierarchy.add_graph("g4", g4)
        self.nx_hierarchy.add_typing("g4", "g2", {1: 2, 2: 3, 3: 6})
        self.nx_hierarchy.add_typing("g4", "g3", {1: 1, 2: 5, 3: 6})
        if self.neo4j_hierarchy:
            self.neo4j_hierarchy.add_graph("g4", g4)
            self.neo4j_hierarchy.add_typing("g4", "g2", {1: 2, 2: 3, 3: 6})
            self.neo4j_hierarchy.add_typing("g4", "g3", {1: 1, 2: 5, 3: 6})

        g5 = NXGraph()
        g5.add_nodes_from([
            ("black_circle"),  # {"a": {255}}),
            ("black_square"),  # {"a": {256}}),
            ("white_triangle"),  # {"a": {257}}),
            ("star")  # , {"a": {258}})
        ])
        g5.add_edges_from([
            ("black_circle", "black_square"),
            ("black_square", "white_triangle"),  # , {"b": {11}}),
            ("star", "black_square"),
            ("star", "white_triangle")
        ])

        self.nx_hierarchy.add_graph("g5", g5)
        if self.neo4j_hierarchy:
            self.neo4j_hierarchy.add_graph("g5", g5)
Пример #20
0
 def __init__(self):
     graph = NXGraph()
     graph.add_nodes_from(["circle", "square"])
     graph.add_edge("circle", "square")
     self.initial_graph = graph
Пример #21
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])
Пример #22
0
    def test_graph_rollback(self):
        g = VersionedGraph(self.initial_graph)

        # Branch 'test'
        g.branch("test")

        pattern = NXGraph()
        pattern.add_node("square")
        rule = Rule.from_transform(pattern)
        # _, rhs_clone =
        rule.inject_clone_node("square")
        g.rewrite(
            rule, {"square": "square"},
            "Clone square")

        # Switch to master
        g.switch_branch("master")

        print("\n\n\nasserting...............")
        for s, t in g._revision_graph.edges():
            print(g._revision_graph.nodes[s]["message"])
            print(g._revision_graph.nodes[t]["message"])
            d = g._revision_graph.adj[s][t]["delta"]
            assert(
                set(d["rule"].rhs.nodes()) ==
                set(d["rhs_instance"].keys())
            )

        # Add edge and triangle
        pattern = NXGraph()
        pattern.add_nodes_from(["circle"])
        rule = Rule.from_transform(pattern)
        # _, rhs_clone =
        rule.inject_add_edge("circle", "circle")
        rule.inject_add_node("triangle")
        rule.inject_add_edge("triangle", "circle")
        rhs_instance, _ = g.rewrite(
            rule, {"circle": "circle"},
            "Add edge to circle and triangle")
        triangle = rhs_instance["triangle"]

        # Clone circle
        pattern = NXGraph()
        pattern.add_node("circle")
        rule = Rule.from_transform(pattern)
        _, rhs_clone = rule.inject_clone_node("circle")

        rhs_instance, rollback_commit = g.rewrite(
            rule, {"circle": "circle"},
            "Clone circle")

        rhs_circle_clones = list({
            rule.p_rhs[p] for p in rule.cloned_nodes()["circle"]
        })

        # Remove original circle
        pattern = NXGraph()
        pattern.add_node("circle")
        rule = Rule.from_transform(pattern)
        rule.inject_remove_node("circle")

        rhs_instance, _ = g.rewrite(
            rule,
            {"circle": rhs_instance[rhs_circle_clones[0]]},
            message="Remove circle")

        # Merge circle clone and triangle
        pattern = NXGraph()
        pattern.add_nodes_from(["circle", "triangle"])
        rule = Rule.from_transform(pattern)
        rule.inject_merge_nodes(["circle", "triangle"])

        rhs_instance, _ = g.rewrite(
            rule,
            {
                "circle": rhs_instance[rhs_clone],
                "triangle": triangle
            },
            message="Merge circle and triangle")
        g.print_history()
        g.rollback(rollback_commit)

        g.merge_with("test")
Пример #23
0
    def test_irreversible_hierarchy(self):
        hierarchy = NXHierarchy()
        d = NXGraph()
        d.add_nodes_from(["c1", "c2", "s1", "s2"])
        hierarchy.add_graph("d", d)

        s = NXGraph()
        s.add_nodes_from(["c", "s"])
        hierarchy.add_graph("s", s)

        hierarchy.add_typing(
            "d", "s", {
                "c1": "c",
                "c2": "c",
                "s1": "s",
                "s2": "s"
            })
        h = VersionedHierarchy(hierarchy)

        pattern = NXGraph()
        pattern.add_nodes_from(["c1", "s1"])
        rule = Rule.from_transform(pattern)
        rule.inject_merge_nodes(["c1", "s1"])

        instance = {
            "c1": "c1",
            "s1": "s1"
        }

        h.rewrite("d", rule, instance)

        h.rollback(h.initial_commit())
        print(h.hierarchy.get_typing("d", "s"))
Пример #24
0
class KamiGraph:
    """Graph container data structure.

    Attributes
    ----------
    graph : nx.(Di)Graph
        Graph
    meta_typing : dict
        Typing of the graph by the meta-model
    reference_typing : dict
        Typing of the graph by the reference graph
    """

    def __init__(self, graph=None, meta_typing=None,
                 reference_typing=None):
        """Initialize graph container."""
        if graph:
            self.graph = NXGraph.copy(graph)
        else:
            self.graph = NXGraph()

        if meta_typing:
            self.meta_typing = copy.deepcopy(meta_typing)
        else:
            self.meta_typing = dict()
        if reference_typing:
            self.reference_typing = copy.deepcopy(reference_typing)
        else:
            self.reference_typing = dict()
        return

    def add_node(self, node_id, attrs=None, meta_typing=None,
                 reference_typing=None):
        """Add node + typings to a nugget."""
        self.graph.add_node(node_id, attrs)
        if meta_typing:
            self.meta_typing[node_id] = meta_typing
        if reference_typing:
            self.reference_typing[node_id] = reference_typing
        return

    def add_node_attrs(self, node_id, attrs):
        self.graph.add_node_attrs(node_id, attrs)

    def add_edge(self, s, t, attrs=None):
        """Add edge between the nodes of a nugget."""
        self.graph.add_edge(s, t, attrs)
        return

    def remove_node(self, node_id):
        self.graph.remove_node(node_id)
        del self.meta_typing[node_id]
        if node_id in self.reference_typing:
            del self.reference_typing[node_id]

    def remove_node_attrs(self, node_id, attrs):
        self.graph.remove_node_attrs(node_id, attrs)

    def remove_edge(self, s, t):
        self.graph.remove_edge(s, t)

    def nodes(self):
        """Return a list of nodes of the nugget graph."""
        return self.graph.nodes()

    def edges(self):
        """Return a list of edges of the nugget graph."""
        return self.graph.edges()
Пример #25
0
    def test_propagation_node_adds(self):
        """Test propagation down of additions."""
        p = NXGraph()
        primitives.add_nodes_from(p, ["B"])

        l = NXGraph()
        primitives.add_nodes_from(l, ["B"])

        r = NXGraph()
        primitives.add_nodes_from(r, ["B", "B_res_1", "X", "Y"])
        primitives.add_edge(r, "B_res_1", "B")

        rule = Rule(p, l, r)

        instance = {"B": "B"}

        rhs_typing = {
            "mm": {
                "B_res_1": "residue"
            },
            "mmm": {
                "X": "component"
            },
            "colors": {
                "Y": "red"
            }
        }
        try:
            self.hierarchy.rewrite("n1",
                                   rule,
                                   instance,
                                   rhs_typing=rhs_typing,
                                   strict=True)
            raise ValueError("Error was not caught!")
        except RewritingError:
            pass

        new_hierarchy = NXHierarchy.copy(self.hierarchy)

        new_hierarchy.rewrite("n1", rule, instance, rhs_typing=rhs_typing)

        # test propagation of node adds
        assert ("B_res_1" in new_hierarchy.get_graph("n1").nodes())
        assert ("B_res_1" in new_hierarchy.get_graph("ag").nodes())
        assert (new_hierarchy.get_typing("n1", "ag")["B_res_1"] == "B_res_1")
        assert (new_hierarchy.get_typing("ag", "mm")["B_res_1"] == "residue")
        assert (("B_res_1", "B") in new_hierarchy.get_graph("n1").edges())
        assert (("B_res_1", "B") in new_hierarchy.get_graph("ag").edges())

        assert ("X" in new_hierarchy.get_graph("n1").nodes())
        assert ("X" in new_hierarchy.get_graph("ag").nodes())
        assert ("X" in new_hierarchy.get_graph("mm").nodes())
        assert ("X" in new_hierarchy.get_graph("colors").nodes())
        assert (new_hierarchy.get_typing("n1", "ag")["X"] == "X")
        assert (new_hierarchy.get_typing("ag", "mm")["X"] == "X")
        assert (new_hierarchy.get_typing("mm", "mmm")["X"] == "component")
        assert (new_hierarchy.get_typing("mm", "colors")["X"] == "X")

        assert ("Y" in new_hierarchy.get_graph("n1").nodes())
        assert ("Y" in new_hierarchy.get_graph("ag").nodes())
        assert ("Y" in new_hierarchy.get_graph("mm").nodes())
        assert ("Y" in new_hierarchy.get_graph("mm").nodes())
        assert (new_hierarchy.get_typing("n1", "ag")["Y"] == "Y")
        assert (new_hierarchy.get_typing("ag", "mm")["Y"] == "Y")
        assert (new_hierarchy.get_typing("mm", "mmm")["Y"] == "Y")
        assert (new_hierarchy.get_typing("mm", "colors")["Y"] == "red")
Пример #26
0
    def __init__(self):
        hierarchy = NXHierarchy()

        base = NXGraph()
        prim.add_nodes_from(base, [("circle", {
            "a": {1, 2, 3}
        }), ("square", {
            "b": {1, 2, 3}
        })])
        prim.add_edges_from(base, [("circle", "circle"), ("square", "square"),
                                   ("circle", "square", {
                                       "c": {5, 6, 7}
                                   }), ("square", "circle")])

        hierarchy.add_graph("base", base)

        a1 = NXGraph()
        prim.add_nodes_from(a1, [("black_circle", {
            "a": {1}
        }), ("white_circle", {
            "a": {2}
        }), ("black_square", {
            "b": {1}
        }), ("white_square", {
            "b": {1}
        })])

        prim.add_edges_from(a1, [("white_circle", "white_circle"),
                                 ("white_circle", "white_square", {
                                     "c": {5}
                                 }), ("black_circle", "black_square"),
                                 ("black_square", "white_square"),
                                 ("black_circle", "white_square", {
                                     "c": {6}
                                 })])

        hierarchy.add_graph("a1", a1)
        hierarchy.add_typing(
            "a1", "base", {
                "black_circle": "circle",
                "white_circle": "circle",
                "white_square": "square",
                "black_square": "square"
            })

        a2 = NXGraph()
        prim.add_nodes_from(a2, [("right_circle", {
            "a": {1, 2}
        }), ("middle_square", {
            "b": {1}
        }), ("left_circle", {
            "a": 1
        })])

        prim.add_edges_from(a2, [("right_circle", "middle_square", {
            "c": {5, 6, 7}
        }), ("left_circle", "middle_square", {
            "c": {6, 7}
        })])

        hierarchy.add_graph("a2", a2)
        hierarchy.add_typing(
            "a2", "base", {
                "right_circle": "circle",
                "middle_square": "square",
                "left_circle": "circle"
            })

        self.hierarchy = hierarchy
Пример #27
0
    def __init__(self):
        hierarchy = NXHierarchy()
        colors = NXGraph()
        primitives.add_nodes_from(colors, [("red", {
            "r": 255,
            "g": 0,
            "b": 0
        }), ("blue", {
            "r": 0,
            "g": 0,
            "b": 255
        })])
        primitives.add_edges_from(colors, [("red", "red"), ("blue", "red"),
                                           ("red", "blue")])
        hierarchy.add_graph("colors", colors)

        mmm = NXGraph()
        primitives.add_nodes_from(mmm, ["component", "state", "action"])

        primitives.add_edges_from(mmm, [("component", "action"),
                                        ("component", "component"),
                                        ("state", "component"),
                                        ("action", "state")])

        hierarchy.add_graph("mmm", mmm)

        mm = NXGraph()
        primitives.add_nodes_from(mm, ["gene", "residue", "state", "mod"])
        primitives.add_edges_from(mm, [("residue", "gene"), ("state", "gene"),
                                       ("state", "residue"), ("mod", "state"),
                                       ("gene", "mod")])
        hierarchy.add_graph("mm", mm)

        action_graph = NXGraph()
        primitives.add_nodes_from(action_graph, [
            "A", "A_res_1", "p_a", "B", "mod1", "mod2", "C", "p_c", "activity"
        ])

        primitives.add_edges_from(action_graph, [("A_res_1", "A"),
                                                 ("p_a", "A_res_1"),
                                                 ("mod1", "p_a"),
                                                 ("B", "mod1"), ("p_c", "C"),
                                                 ("B", "mod2"),
                                                 ("activity", "B"),
                                                 ("mod2", "p_c")])
        hierarchy.add_graph("ag", action_graph)

        nugget_1 = NXGraph()
        primitives.add_nodes_from(nugget_1, ["A", "A_res_1", "p", "B", "mod"])
        primitives.add_edges_from(nugget_1, [("A_res_1", "A"),
                                             ("p", "A_res_1"), ("mod", "p"),
                                             ("B", "mod")])
        hierarchy.add_graph("n1", nugget_1)

        nugget_2 = NXGraph()
        primitives.add_nodes_from(nugget_2, ["B", "activity", "mod", "p", "C"])
        primitives.add_edges_from(nugget_2, [("activity", "B"), ("B", "mod"),
                                             ("mod", "p"), ("p", "C")])
        hierarchy.add_graph("n2", nugget_2)

        # add typings
        hierarchy.add_typing(
            "mm", "mmm", {
                "gene": "component",
                "residue": "component",
                "state": "state",
                "mod": "action"
            })

        hierarchy.add_typing("mm", "colors", {
            "gene": "red",
            "residue": "red",
            "state": "red",
            "mod": "blue"
        })
        hierarchy.add_typing(
            "ag", "mm", {
                "A": "gene",
                "B": "gene",
                "A_res_1": "residue",
                "mod1": "mod",
                "p_a": "state",
                "C": "gene",
                "activity": "state",
                "p_c": "state",
                "mod2": "mod"
            })
        hierarchy.add_typing("n1", "ag", {
            "A": "A",
            "B": "B",
            "A_res_1": "A_res_1",
            "mod": "mod1",
            "p": "p_a",
        })

        hierarchy.add_typing(
            "n2", "ag", {
                "B": "B",
                "C": "C",
                "p": "p_c",
                "activity": "activity",
                "mod": "mod2",
            })

        self.hierarchy = hierarchy
Пример #28
0
    def test_networkx_hierarchy_versioning(self):
        """Test hierarchy versioning functionality."""
        hierarchy = NXHierarchy()
        shapes = NXGraph()
        shapes.add_nodes_from(["c", "s"])
        hierarchy.add_graph("shapes", shapes)

        colors = NXGraph()
        colors.add_nodes_from(["w", "b"])
        hierarchy.add_graph("colors", colors)

        ag = NXGraph()
        ag.add_nodes_from(
            ["wc", "bc", "ws", "bs"])
        hierarchy.add_graph("ag", ag)

        nugget = NXGraph()
        nugget.add_nodes_from(
            ["wc1", "wc2", "bc1", "ws1", "bs2"])
        hierarchy.add_graph("nugget", nugget)

        hierarchy.add_typing(
            "ag", "shapes", {
                "wc": "c",
                "bc": "c",
                "ws": "s",
                "bs": "s"
            })
        hierarchy.add_typing(
            "ag", "colors", {
                "wc": "w",
                "bc": "b",
                "ws": "w",
                "bs": "b"
            })
        hierarchy.add_typing(
            "nugget", "ag", {
                "wc1": "wc",
                "wc2": "wc",
                "bc1": "bc",
                "ws1": "ws",
                "bs2": "bs"
            })
        hierarchy.add_typing(
            "nugget", "colors", {
                "wc1": "w",
                "wc2": "w",
                "bc1": "b",
                "ws1": "w",
                "bs2": "b"
            })

        base = NXGraph()
        base.add_nodes_from(["node"])
        hierarchy.add_graph("base", base)
        hierarchy.add_typing(
            "colors",
            "base", {
                "w": "node",
                "b": "node"
            })

        h = VersionedHierarchy(hierarchy)

        h.branch("test1")

        pattern = NXGraph()
        pattern.add_nodes_from(["s"])
        rule2 = Rule.from_transform(pattern)
        rule2.inject_remove_node("s")

        h.rewrite(
            "shapes",
            rule2, {"s": "s"},
            message="Remove square in shapes")

        h.switch_branch("master")

        pattern = NXGraph()
        pattern.add_nodes_from(["wc"])

        rule1 = Rule.from_transform(pattern)
        rule1.inject_clone_node("wc")

        _, clone_commit = h.rewrite(
            "ag",
            rule1, {"wc": "wc"},
            message="Clone 'wc' in ag")

        pattern = NXGraph()
        pattern.add_nodes_from(["wc1"])

        rule3 = Rule.from_transform(pattern)
        rule3.inject_add_node("new_node")
        rule3.inject_add_edge("new_node", "wc1")

        h.rewrite("nugget", rule3, {"wc1": "wc1"})
        # print(h.print_history())
        h.switch_branch("test1")
        h.switch_branch("master")
        h.merge_with("test1")

        h.rollback(clone_commit)
        h.switch_branch("test1")
Пример #29
0
"""Collection of data structures for querying KAMI corpora and models."""
import itertools
import copy
import warnings

from regraph import NXGraph

from kamiql.parser import parse_query

from kami.resources.metamodels import meta_model_base_typing, meta_model
from kami.exceptions import KamiQLError, KamiQLWarning


# Global variables used to query nuggets and the action graph
META_MODEL = NXGraph()
META_MODEL.add_nodes_from(meta_model["nodes"])
META_MODEL.add_edges_from(meta_model["edges"])
META_TYPES = list(meta_model_base_typing.keys())
GENERIC_TYPES = list(set(meta_model_base_typing.values()))
GENERIC_TYPE_EXTENSION = {
    "component": ["protoform", "region", "site", "residue"],
    "interaction": ["bnd", "mod"],
    "state": ["state"]
}


def isinteraction(types):
    for t in types:
        if t in ["mod", "bnd"]:
            return True
    return False
Пример #30
0
    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"))