def max_comp_element_alg(nodes, graph, comp_graph, max_arr):
    em = isomorphism.categorical_edge_match('colour', '')
    nm = isomorphism.categorical_node_match('text', '')
    GM = isomorphism.DiGraphMatcher(comp_graph,
                                    graph,
                                    node_match=nm,
                                    edge_match=em)
    if GM.subgraph_is_isomorphic():
        max_arr.append(graph)
    else:
        for obj in nodes['children']:
            new_graph = copy.deepcopy(graph)
            curr_graph = del_nodes(new_graph, obj['_id'], nodes)
            em = isomorphism.categorical_edge_match('colour', '')
            nm = isomorphism.categorical_node_match('text', '')
            GM = isomorphism.DiGraphMatcher(comp_graph,
                                            curr_graph,
                                            node_match=nm,
                                            edge_match=em)
            if GM.subgraph_is_isomorphic():
                max_arr.append(curr_graph)
            else:
                curr_graph.remove_edge(nodes['_id'], obj['_id'])
                curr_graph.remove_node(nodes['_id'])
                max_comp_element_alg(obj, curr_graph, comp_graph, max_arr)
示例#2
0
def isoscore(subg1, subg2):
    dot = Digraph(comment=subg1.key_node)
    dot.attr("node", fontname="monospace")
    dot.attr("edge", fontname="monospace")
    dot.graph_attr["rankdir"] = "BT"
    for event_node_id in subg1.event_nodes_map:
        node = subg1.event_nodes_map[event_node_id]
        name = "%d %d %s" % (node.call_nonce, node.event_id, node.name)
        dot.node(node._display_id(), name, shape="box")
    for normal_node_id in subg1.normal_nodes_map:
        node = subg1.normal_nodes_map[normal_node_id]
        name = "%d %d %s" % (node.call_nonce, node.node_id,
                             node._display_name())
        dot.node(node._display_id(), name, shape="oval")
    for edge_id in subg1.edges_map:
        edge = subg1.edges_map[edge_id]
        dot.edge(edge.src_node._display_id(),
                 edge.dst_node._display_id(),
                 label=edge.name)
    dotplus = pydotplus.graph_from_dot_data(dot.source)
    nx_graph = nx.nx_pydot.from_pydot(dotplus)
    # print(type(nx_graph))
    # print(len(subg1.edges_map))
    # print(len(nx_graph.edges))
    # print(nx_graph.nodes)

    dot = Digraph(comment=subg2.key_node)
    dot.attr("node", fontname="monospace")
    dot.attr("edge", fontname="monospace")
    dot.graph_attr["rankdir"] = "BT"
    for event_node_id in subg2.event_nodes_map:
        node = subg2.event_nodes_map[event_node_id]
        name = "%d %d %s" % (node.call_nonce, node.event_id, node.name)
        dot.node(node._display_id(), name, shape="box")
    for normal_node_id in subg2.normal_nodes_map:
        node = subg2.normal_nodes_map[normal_node_id]
        name = "%d %d %s" % (node.call_nonce, node.node_id,
                             node._display_name())
        dot.node(node._display_id(), name, shape="oval")
    for edge_id in subg2.edges_map:
        edge = subg2.edges_map[edge_id]
        dot.edge(edge.src_node._display_id(),
                 edge.dst_node._display_id(),
                 label=edge.name)
    dotplus = pydotplus.graph_from_dot_data(dot.source)
    nx_graph1 = nx.nx_pydot.from_pydot(dotplus)
    # print(type(nx_graph1))
    # print(len(subg1.edges_map))
    # print(len(nx_graph1.edges))
    # print(nx_graph1.nodes)
    if nx_graph.order() > nx_graph1.order():
        DiGM = isomorphism.DiGraphMatcher(nx_graph, nx_graph1)
    else:
        DiGM = isomorphism.DiGraphMatcher(nx_graph1, nx_graph)
    print(DiGM.is_isomorphic())
    print(DiGM.subgraph_is_isomorphic())
    print(DiGM.mapping)
    return DiGM.subgraph_is_isomorphic()
示例#3
0
def max_isom_substree(G, H):
    #gm_one = isomorphism.DiGraphMatcher(G, H)
    #gm_two = isomorphism.DiGraphMatcher(H, G)
    nm = isomorphism.categorical_node_match('text', '')
    gm_one = isomorphism.DiGraphMatcher(G, H, node_match=nm)
    gm_two = isomorphism.DiGraphMatcher(H, G, node_match=nm)
    if gm_one.subgraph_is_isomorphic():
        return af.count_nodes(H)
    if gm_two.subgraph_is_isomorphic():
        return af.count_nodes(G)
    return 0
示例#4
0
def graph_match(sig,proj,cfg,sym_tab=None):
    #The sig DiGraph already has all the necessary node attributes for matching, but target cfg doesn't.
    #So the first step is to generate these necessary node attributes for target cfg.
    prep_node_attributes_for_match(proj,cfg,sym_tab=sym_tab)
    #Do the subgraph match, node_matcher() is a simple node-level semantic matcher.
    digm = isomorphism.DiGraphMatcher(cfg,sig,node_match=node_matcher)
    candidates = []
    for it in digm.subgraph_isomorphisms_iter():
        #Each iter here is a possible match (i.e. a candidate)
        #At first wrap it into a sig structure.
        addrs = [x.addr for x in it.keys()]
        print '[TOPO MATCH] ' + hex_array_sorted(addrs)
        #We guarantee in extraction phase that every signature is connected, so here the candidate signature must also be connected, thus we
        #can directly use init_signature(...)[0].
        c_sig = init_signature(proj,cfg,addrs,sym_tab=sym_tab)[0]
        #The 'it' is the mapping from the whole func_cfg to original sig, now we just want the mapping from
        #candidate sig to original sig.
        mapping = {}
        for k in it:
            #L: Candidates R: Original Signature
            mapping[get_node_by_addr(c_sig,k.addr)] = it[k]
        #show_signature(c_sig)
        #Do some preliminary filtering before the real symbolic execution.
        if pre_filter(c_sig,sig,mapping):
            candidates.append((c_sig,mapping))
    print '%d candidates after graph_match()' % len(candidates)
    return candidates
示例#5
0
def test_multiedge():
    # Simple test for multigraphs
    # Need something much more rigorous
    edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5),
             (5, 6), (6, 7), (7, 8), (8, 9), (9, 10),
             (10, 11), (10, 11), (11, 12), (11, 12),
             (12, 13), (12, 13), (13, 14), (13, 14),
             (14, 15), (14, 15), (15, 16), (15, 16),
             (16, 17), (16, 17), (17, 18), (17, 18),
             (18, 19), (18, 19), (19, 0), (19, 0)]
    nodes = list(range(20))

    for g1 in [nx.MultiGraph(), nx.MultiDiGraph()]:
        g1.add_edges_from(edges)
        for _ in range(10):
            new_nodes = list(nodes)
            random.shuffle(new_nodes)
            d = dict(zip(nodes, new_nodes))
            g2 = nx.relabel_nodes(g1, d)
            if not g1.is_directed():
                gm = iso.GraphMatcher(g1, g2)
            else:
                gm = iso.DiGraphMatcher(g1, g2)
            assert gm.is_isomorphic()
            # Testing if monomorphism works in multigraphs
            assert gm.subgraph_is_monomorphic()
示例#6
0
def find_sub_iso(G_subgraphs, G_pat, node_match=None, edge_match=None):
    """
    Returns the list of all the graph isomorphisms between one of the subgraphs of G in G_subgraphs and the graph pattern G_pat. 
    Each isomorphim is defined as a dictionary with keys "nodes" itself a dictionary mapping G_pat nodes to G nodes, and "edges" a dictionary mapping G_pat edges to G edges.
    
    Args:
        - G_subgraphs([NetworkX.DiGraph]): List of subgraphs
        - G_pat(NetworkX.DiGraph)
        - node_match (callable): node_match should be either "None" or networkx isomorphisms matching functions generated by node_iso_match().
        - edge_match (callable): edge_match should be either "None" or networkx isomorphisms matching functions generated by edge_iso_match().
        - subgraph_filter (callable): subgraph_filter should be a callable that takes on a subgraph and returns True or False. Only the subgraphs that return True
                                        are considered for subgraph isomorphism matching. By default returns always True.
    """
    sub_iso = []
    mappings = []
    for subgraph in G_subgraphs:
        DiGM = isomorphism.DiGraphMatcher(subgraph,
                                          G_pat,
                                          node_match=node_match,
                                          edge_match=edge_match)
        if DiGM.is_isomorphic():
            mappings.append(DiGM.mapping)

    for mapping in mappings:
        iso = {"nodes": {}, "edges": {}}
        for key in mapping:
            iso["nodes"][mapping[
                key]] = key  # reverse mapping for convenience (SemFrame -> SemRep)
        for edge in G_pat.edges():  # Add mapping between edges
            iso["edges"][edge] = (iso["nodes"][edge[0]], iso["nodes"][edge[1]])
        sub_iso.append(iso)

    return sub_iso
示例#7
0
 def add_rule(self, graph):
     size = len(graph.nodes())
     if size not in self._rules:
         self._rules[size] = [[graph, self._next_id, 1]]
         self._next_id += 1
         return self._next_id - 1
     else:
         rules = self._rules[size]
         for i in range(0, len(rules)):
             gm = isomorphism.DiGraphMatcher(rules[i][0], graph)
             if gm.is_isomorphic():
                 # Note that this rule appeared once more.
                 rules[i][2] += 1
                 # Move the rule closer to the front of the list if it's more popular.
                 j = i - 1
                 while j >= 0 and rules[j][2] < rules[i][2]:
                     j -= 1
                 j += 1
                 if i != j and rules[j][2] < rules[i][2]:
                     temp = rules[j]
                     rules[j] = rules[i]
                     rules[i] = temp
                     return rules[j][1]
                 return rules[i][1]
         # If not already in the library.
         rules.append([graph, self._next_id, 1])
         self._next_id += 1
         return self._next_id - 1
def isomorphism_check(G1, G2):
    plagiarised = -1
    #TODO: change gamma
    gamma = 0.9
    nm = iso.categorical_node_match(
        'node_type', 'motion'
    )  #just putting motion as the default value anyway all nodes will have node_type
    GM = iso.DiGraphMatcher(G1, G2, node_match=nm)
    num_nodes = min(nx.number_of_nodes(G1), nx.number_of_nodes(G2))  #----
    max_num_node = max(nx.number_of_nodes(G1), nx.number_of_nodes(G2))
    #settings.OutputLogFile.write("Isomorphism_check: min number of nodes = "+str(num_nodes)+"\n")
    #DiGraphMatcher.subgraph_isomorphisms_iter()
    #settings.OutputLogFile.write("Subgraphs:\n")
    for subgraph in GM.subgraph_isomorphisms_iter():
        #print("type of subgraph: ",type(subgraph)) #WAS COMMENTED OUT BEFORE
        #print(subgraph)	#WAS COMMENTED OUT BEFORE
        settings.OutputLogFile.write("subgraph:\n" + str(subgraph) + '\n')
        settings.OutputLogFile.write(str(subgraph) + '\n')
        if (len(subgraph) >=
                gamma * num_nodes):  #passing it through the filter
            #settings.OutputLogFile.write("Plagiarised subgraph:\n" + str(subgraph)+'\n')
            #plagiarised = True
            plagiarised = (len(subgraph) /
                           max_num_node if max_num_node != 0 else 0)
            break
    return plagiarised
示例#9
0
 def match(self, terms):
     # 
     g = nx.DiGraph()
     for t in terms: g.add_node(t[0], pos=t[3],  rel=t[5], val=t[1])
     for t in terms:
         if t[4]: g.add_edge(t[0], t[4])
     rg = g.reverse(copy=True)
     
     # Try match
     digm = isomorphism.DiGraphMatcher(g,self.pattern, node_match=Rule.is_match)
     
     pair = []
     for m in digm.subgraph_isomorphisms_iter():
         m = dict((v,k) for k, v in m.items())
         
         for e in self.extraction:
             li = [m[int(t)] for t in e[0]]
             ri = [m[int(t)] for t in e[1]]
             
             n = self.negation(g, rg, set(li+ri))
             n = sum(n.values())
             
             l = "".join(terms[t-1][1] for t in li)
             r = "".join(terms[t-1][1] for t in ri)
             
             pair.append((l,r,n))
     return pair
def main():

    if len(sys.argv) < 2:
        sys.exit('Usage: %s $json_file' % sys.argv[0])

    if not os.path.exists(sys.argv[1]):
        sys.exit('ERROR: %s was not found!' % sys.argv[1])

    if len(sys.argv) == 2:
        G = merge_same_node(parse_saaf_json(sys.argv[1]))
        nx.draw_graphviz(G, prog='dot')
        plt.axis('off')
        plt.savefig("merged_by_networkx.png")
        json.dump(json_graph.node_link_data(G),
                  open('ford3js.json', 'w'),
                  sort_keys=True,
                  indent=4)
    if len(sys.argv) == 3:
        G1 = merge_same_node(parse_saaf_json(sys.argv[1]))
        G2 = merge_same_node(parse_saaf_json(sys.argv[2]))
        GM = isomorphism.DiGraphMatcher(G2, G1, node_match=op_match)
        #GM = isomorphism.DiGraphMatcher(G2, G1)
        print GM.is_isomorphic()
        print GM.subgraph_is_isomorphic()
        print GM.mapping
示例#11
0
def test_selfloop_mono():
    # Simple test for graphs with selfloops
    edges0 = [
        (0, 1),
        (0, 2),
        (1, 2),
        (1, 3),
        (2, 4),
        (3, 1),
        (3, 2),
        (4, 2),
        (4, 5),
        (5, 4),
    ]
    edges = edges0 + [(2, 2)]
    nodes = list(range(6))

    for g1 in [nx.Graph(), nx.DiGraph()]:
        g1.add_edges_from(edges)
        for _ in range(100):
            new_nodes = list(nodes)
            random.shuffle(new_nodes)
            d = dict(zip(nodes, new_nodes))
            g2 = nx.relabel_nodes(g1, d)
            g2.remove_edges_from(nx.selfloop_edges(g2))
            if not g1.is_directed():
                gm = iso.GraphMatcher(g2, g1)
            else:
                gm = iso.DiGraphMatcher(g2, g1)
            assert not gm.subgraph_is_monomorphic()
示例#12
0
    def get_subgraph_cn(self, netlist_subgraph) -> ConstructionNode:
        """Returns the Construction node matching the subgraph

        Args:
            subgraph (subgraph_view): Subgraph to match against

        Returns:
            ConstructionNode: Construction node that contains the
            same subgraph
        """
        subgraph_node_list = list(netlist_subgraph.nodes)
        for cn in list(self._construction_nodes.values()):
            for mapping_option in cn.mapping_options:
                cn_subgraph = mapping_option.fig_subgraph
                cn_subgraph_nodelist = list(cn_subgraph.nodes)
                if (str_lists_equal(subgraph_node_list, cn_subgraph_nodelist)
                        is not True):
                    continue
                graph_matcher = isomorphism.DiGraphMatcher(
                    cn_subgraph, netlist_subgraph)
                is_it_isomorphic = graph_matcher.is_isomorphic()
                if is_it_isomorphic:
                    return cn

        raise Exception(
            "Could not find construction node with the same netlist subgraph")
示例#13
0
def isomorph(g, l):
  res = False
  if l != []:
    for i in l:
      gm = isomorphism.DiGraphMatcher(g, i)
      res = res or gm.is_isomorphic()
  return res
示例#14
0
 def _process(X_s, match_set, is_good):
     special_edges = []
     special_nodes = []
     for i in match_set:
         f = self.feat_graphlets[int(i)]
         if len(f) == 1:  ### h = 0 features
             for i in range(len(X_s)):
                 if X_s.nodes[i]['op_name'] == f.nodes[0]['op_name']:
                     special_nodes.append(i)
         else:
             gm = isomorphism.DiGraphMatcher(
                 X_s,
                 f,
                 node_match=lambda x, y: x['op_name'] == y['op_name'])
             print(gm.subgraph_is_isomorphic())
             mapping = gm.mapping
             if not len(mapping):
                 from misc.draw_nx import draw_graph
                 draw_graph(X_s)
                 draw_graph(f)
             rev_mapping = {v: k for k, v in mapping.items()}
             if len(mapping):
                 root_node = rev_mapping[0]
                 special_edges += [(root_node, m)
                                   for m in list(mapping.keys())[1:]]
                 for i in list(mapping.keys()):
                     # color the nodes
                     special_nodes.append(i)
                 # special edges
     return X_s, special_nodes, special_edges
示例#15
0
 def is_same_derg(derg1, derg2):
     GM = isomorphism.DiGraphMatcher(
         derg1.g,
         derg2.g,
         node_match=ThirdPartyLibRepo.node_match,
         edge_match=ThirdPartyLibRepo.edge_match)
     return GM.is_isomorphic()
示例#16
0
    def getBodyIsomorphism(self, rule):
        """
        Applies the isomorphism algorithm on the graphs
        of this and another rules' bodies.

        Parameters
        ----------
        rule : AMIERule
            The other rule to compare.

        Returns
        -------
        nxiso.DiGraphMatcher
            The DiGraphMatcher instance of the applied isomorphism algorithm.
        """

        # build graphs for the body of each rule and test for isomorphism
        self_graph = nx.DiGraph()
        for body_triple in self._body:
            self_graph.add_node(body_triple.s)
            self_graph.add_node(body_triple.o)
            self_graph.add_edge(body_triple.s,
                                body_triple.o,
                                label=body_triple.p)
        other_graph = nx.DiGraph()
        for body_triple in rule.body:
            other_graph.add_node(body_triple.s)
            other_graph.add_node(body_triple.o)
            other_graph.add_edge(body_triple.s,
                                 body_triple.o,
                                 label=body_triple.p)
        nm = nxiso.categorical_edge_match("label", "empty")
        dgm = nxiso.DiGraphMatcher(self_graph, other_graph, edge_match=nm)
        return dgm
示例#17
0
def _subgraph_isomorphism_matcher(digraph, nxpattern, node_pred, edge_pred):
    """ Match based on the VF2 algorithm for general SI. """
    graph_matcher = iso.DiGraphMatcher(digraph,
                                       nxpattern,
                                       node_match=node_pred,
                                       edge_match=edge_pred)
    yield from graph_matcher.subgraph_isomorphisms_iter()
示例#18
0
def compare_topology(graph1, graph2, match1=_node_match, match2=_edge_match):
    """
    Compares the topology of two graphs.

    :param graph1: The first graph.
    :param graph2: The second graph.
    :param match1: Matcher for attributes of the nodes.
    :param match2: Matcher for attributes of the edges.
    :return: Triple of: True if graphs are identical - otherwise False,
                         True if g2 is subgraph of g1 - otherwise False,
                         dict with the mappings and differences.
    """
    graph_equal = False
    is_subgraph = False
    result = {'mapping': {}, 'diff': []}

    comp = isomorphism.DiGraphMatcher(graph1,
                                      graph2,
                                      node_match=match1,
                                      edge_match=match2)

    if comp.is_isomorphic():
        graph_equal = True
    elif comp.subgraph_is_isomorphic():
        is_subgraph = True
        result['diff'] = list(set(graph1.nodes()) - set(comp.mapping.keys()) -
                              set(comp.mapping.values()))

    result['mapping'] = comp.mapping

    return graph_equal, is_subgraph, result
示例#19
0
def match_pattern(state: SDFGState,
                  pattern: Type[Transformation],
                  sdfg: SDFG,
                  node_match=type_match,
                  edge_match=None,
                  strict=False):
    """ Returns a list of single-state Transformations of a certain class that
        match the input SDFG.
        :param state: An SDFGState object to match.
        :param pattern: Transformation type to match.
        :param sdfg: The SDFG to match in.
        :param node_match: Function for checking whether two nodes match.
        :param edge_match: Function for checking whether two edges match.
        :param strict: Only match transformation if strict (i.e., can only
                       improve the performance/reduce complexity of the SDFG).
        :return: A list of Transformation objects that match.
    """

    # Collapse multigraph into directed graph
    # Handling VF2 in networkx for now
    digraph = collapse_multigraph_to_nx(state)

    for idx, expression in enumerate(pattern.expressions()):
        cexpr = collapse_multigraph_to_nx(expression)
        graph_matcher = iso.DiGraphMatcher(digraph,
                                           cexpr,
                                           node_match=node_match,
                                           edge_match=edge_match)
        for subgraph in graph_matcher.subgraph_isomorphisms_iter():
            subgraph = {
                cexpr.nodes[j]['node']: state.node_id(digraph.nodes[i]['node'])
                for (i, j) in subgraph.items()
            }
            try:
                match_found = pattern.can_be_applied(state,
                                                     subgraph,
                                                     idx,
                                                     sdfg,
                                                     strict=strict)
            except Exception as e:
                if Config.get_bool('optimizer', 'match_exception'):
                    raise
                print('WARNING: {p}::can_be_applied triggered a {c} exception:'
                      ' {e}'.format(p=pattern.__name__,
                                    c=e.__class__.__name__,
                                    e=e))
                match_found = False
            if match_found:
                yield pattern(sdfg.sdfg_id, sdfg.node_id(state), subgraph, idx)

    # Recursive call for nested SDFGs
    for node in state.nodes():
        if isinstance(node, nd.NestedSDFG):
            sub_sdfg = node.sdfg
            for sub_state in sub_sdfg.nodes():
                yield from match_pattern(sub_state,
                                         pattern,
                                         sub_sdfg,
                                         strict=strict)
示例#20
0
def test_multiple():
    # Verify that we can use the graph matcher multiple times
    edges = [('A','B'),('B','A'),('B','C')]
    for g1,g2 in [(nx.Graph(),nx.Graph()), (nx.DiGraph(),nx.DiGraph())]:
        g1.add_edges_from(edges)
        g2.add_edges_from(edges)
        g3 = nx.subgraph(g2, ['A','B'])
        if not g1.is_directed():
            gmA = iso.GraphMatcher(g1,g2)
            gmB = iso.GraphMatcher(g1,g3)
        else:
            gmA = iso.DiGraphMatcher(g1,g2)
            gmB = iso.DiGraphMatcher(g1,g3)
        assert_true(gmA.is_isomorphic())
        g2.remove_node('C')
        assert_true(gmA.subgraph_is_isomorphic())
        assert_true(gmB.subgraph_is_isomorphic())
示例#21
0
def test_monomorphism_iter1():
    g1 = nx.DiGraph()
    g2 = nx.DiGraph()
    g1.add_edge('A', 'B')
    g1.add_edge('B', 'C')
    g1.add_edge('C', 'A')
    g2.add_edge('X', 'Y')
    g2.add_edge('Y', 'Z')
    gm12 = iso.DiGraphMatcher(g1, g2)
    x = list(gm12.subgraph_monomorphisms_iter())
    assert {'A': 'X', 'B': 'Y', 'C': 'Z'} in x
    assert {'A': 'Y', 'B': 'Z', 'C': 'X'} in x
    assert {'A': 'Z', 'B': 'X', 'C': 'Y'} in x
    assert len(x) == 3
    gm21 = iso.DiGraphMatcher(g2, g1)
    # Check if StopIteration exception returns False
    assert not gm21.subgraph_is_monomorphic()
示例#22
0
def test_monomorphism_iter1():
    g1 = nx.DiGraph()
    g2 = nx.DiGraph()
    g1.add_edge("A", "B")
    g1.add_edge("B", "C")
    g1.add_edge("C", "A")
    g2.add_edge("X", "Y")
    g2.add_edge("Y", "Z")
    gm12 = iso.DiGraphMatcher(g1, g2)
    x = list(gm12.subgraph_monomorphisms_iter())
    assert {"A": "X", "B": "Y", "C": "Z"} in x
    assert {"A": "Y", "B": "Z", "C": "X"} in x
    assert {"A": "Z", "B": "X", "C": "Y"} in x
    assert len(x) == 3
    gm21 = iso.DiGraphMatcher(g2, g1)
    # Check if StopIteration exception returns False
    assert not gm21.subgraph_is_monomorphic()
示例#23
0
 def isProportional(self, other):
     selfGraph = self.getGraph()
     otherGraph = other.getGraph()
     DiGM = isomorphism.DiGraphMatcher(selfGraph, otherGraph)
     return (self.tensorList
             == other.tensorList) and DiGM.is_isomorphic() and all([
                 DiGM.semantic_feasibility(DiGM.mapping[n], n)
                 for n in DiGM.mapping.keys()
             ])
示例#24
0
def subgraph_isomorphism(G1, G2):
    digraph_matcher = isomorphism.DiGraphMatcher(G2,
                                                 G1,
                                                 node_match=node_matching)
    for subgraph in digraph_matcher.subgraph_isomorphisms_iter():
        print subgraph
    print "G2 is subgraph isomorphic G1:", str(
        digraph_matcher.subgraph_is_isomorphic())
    print "G2 - G1 mapping:", str(digraph_matcher.mapping)
示例#25
0
def graph_matcher(map: nx.DiGraph, history: nx.DiGraph):
    """
    Check whether the history can be created on the given map
    :param map: map graph
    :param history: history graph
    :return: match
    """
    dg_matcher = iso.DiGraphMatcher(map, history)
    return dg_matcher.subgraph_is_isomorphic()
示例#26
0
def match_expression(graph,
                     expressions,
                     node_match=type_match,
                     edge_match=None,
                     pattern_match=None,
                     strict=False):
    """ Returns a generator which yields a subgraph mapping from 
        `expression_node` to `graph_node`.
        :param graph: Directed multigraph object to be searched for subgraphs.
        :param expressions: List of directed graphs, isomorphic to any
                            (sub)graph that potentially matches a 
                            transformation.
        :param node_match: Function for checking whether two nodes match.
        :param edge_match: Function for checking whether two edges match.
        :param pattern_match: Function for checking whether a subgraph matches
                              a transformation.
        :return: Generator of 2-tuples: (subgraph, expression index in
                 `expressions`).
    """

    # Collapse multigraph into directed graph
    digraph = collapse_multigraph_to_nx(graph)

    # If expression is a list, try to match each one of them
    if not isinstance(expressions, list) and not isinstance(
            expressions, GeneratorType):
        expressions = [expressions]

    for expr_index, expr in enumerate(expressions):
        # Also collapse expression multigraph
        cexpr = collapse_multigraph_to_nx(expr)

        # Find candidate subgraphs (per-node / per-edge matching)
        graph_matcher = iso.DiGraphMatcher(digraph,
                                           cexpr,
                                           node_match=node_match,
                                           edge_match=edge_match)
        for subgraph in graph_matcher.subgraph_isomorphisms_iter():
            # Convert candidate to original graph node representation
            # The type of subgraph is {graph_node_id: subgraph_node_id}
            # We return the inverse mapping: {subgraph_node: graph_node} for
            # ease of access
            subgraph = {
                cexpr.nodes[j]['node']: digraph.nodes[i]['node']
                for (i, j) in subgraph.items()
            }

            # Match original (regular) expression on found candidate
            if pattern_match is None:
                # Yield mapping and index of expression found
                yield subgraph, expr_index
            else:
                match_found = pattern_match(graph, subgraph)
                if match_found:
                    # Yield mapping and index of expression found
                    # expr_index_list = list(range(match_num))
                    yield subgraph, expr_index  # expr_index_list
示例#27
0
def enumerate_matches(sdfg: SDFG,
                      pattern: gr.Graph,
                      node_match=type_or_class_match,
                      edge_match=None) -> Iterator[gr.SubgraphView]:
    """
    Returns a generator of subgraphs that match the given subgraph pattern.
    :param sdfg: The SDFG to search in.
    :param pattern: A subgraph to look for.
    :param node_match: An optional function to use for matching nodes.
    :param node_match: An optional function to use for matching edges.
    :return: Yields SDFG subgraph view objects.
    """
    if len(pattern.nodes()) == 0:
        raise ValueError('Subgraph pattern cannot be empty')

    # Find if the subgraph is within states or SDFGs
    is_interstate = (isinstance(pattern.node(0), SDFGState)
                     or (isinstance(pattern.node(0), type)
                         and pattern.node(0) is SDFGState))

    # Collapse multigraphs into directed graphs
    pattern_digraph = collapse_multigraph_to_nx(pattern)

    # Find matches in all SDFGs and nested SDFGs
    for graph in sdfg.all_sdfgs_recursive():
        if is_interstate:
            graph_matcher = iso.DiGraphMatcher(
                collapse_multigraph_to_nx(graph),
                pattern_digraph,
                node_match=node_match,
                edge_match=edge_match)
            for subgraph in graph_matcher.subgraph_isomorphisms_iter():
                yield gr.SubgraphView(graph,
                                      [graph.node(i) for i in subgraph.keys()])
        else:
            for state in graph.nodes():
                graph_matcher = iso.DiGraphMatcher(
                    collapse_multigraph_to_nx(state),
                    pattern_digraph,
                    node_match=node_match,
                    edge_match=edge_match)
                for subgraph in graph_matcher.subgraph_isomorphisms_iter():
                    yield gr.SubgraphView(
                        state, [state.node(i) for i in subgraph.keys()])
示例#28
0
def add_graph_single(graph, graph_dict):
    if len(graph_dict) == 0:
        graph_dict[graph] = 1
        return
    for graph_in_dict in list(graph_dict.keys()):
        matcher = isomorphism.DiGraphMatcher(graph, graph_in_dict)
        if matcher.is_isomorphic():
            graph_dict[graph_in_dict] = graph_dict[graph_in_dict] + 1
            return
    graph_dict[graph] = 1
示例#29
0
def get_feature(sfcg, feature_subgraph_list):
    result_str = ""
    for feature_subgraph in feature_subgraph_list:
        matcher = isomorphism.DiGraphMatcher(sfcg, feature_subgraph)
        if matcher.subgraph_is_isomorphic():
            result_str += "1,"
        else:
            result_str += "0,"
    print(result_str)
    return result_str
示例#30
0
 def match(self, q, t, q_prepared, t_prepared):
     GM = isomorphism.DiGraphMatcher(t,
                                     q,
                                     node_match=self.custom_node_match,
                                     edge_match=self.custom_edge_match)
     res = GM.subgraph_is_isomorphic()
     if res:
         return {}, 100
     else:
         return {}, 0