Пример #1
0
    def test_mcis(self):
        # Example graphs from DOI: 10.1002/spe.588
        graph1 = nx.Graph()
        graph1.add_edges_from([(1, 2), (2, 3), (2, 4), (3, 4), (4, 5)])
        graph1.nodes[1]['color'] = 0

        graph2 = nx.Graph()
        graph2.add_edges_from([(1, 2), (2, 3), (2, 4), (3, 4), (3, 5),
                               (5, 6), (5, 7), (6, 7)])
        graph2.nodes[1]['color'] = 1
        graph2.nodes[6]['color'] = 2
        graph2.nodes[7]['color'] = 2

        ismags = iso.ISMAGS(graph1, graph2, node_match=iso.categorical_node_match('color', None))
        assert list(ismags.subgraph_isomorphisms_iter(True)) == []
        assert list(ismags.subgraph_isomorphisms_iter(False)) == []
        found_mcis = _matches_to_sets(ismags.largest_common_subgraph())
        expected = _matches_to_sets([{2: 2, 3: 4, 4: 3, 5: 5},
                                     {2: 4, 3: 2, 4: 3, 5: 5}])
        assert expected == found_mcis

        ismags = iso.ISMAGS(graph2, graph1, node_match=iso.categorical_node_match('color', None))
        assert list(ismags.subgraph_isomorphisms_iter(True)) == []
        assert list(ismags.subgraph_isomorphisms_iter(False)) == []
        found_mcis = _matches_to_sets(ismags.largest_common_subgraph())
        # Same answer, but reversed.
        expected = _matches_to_sets([{2: 2, 3: 4, 4: 3, 5: 5},
                                     {4: 2, 2: 3, 3: 4, 5: 5}])
        assert expected == found_mcis
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)
def equal_graphs(g1, g2,
                 node_attrs=('resid', 'resname', 'atomname', 'chain', 'charge_group', 'atype'),
                 edge_attrs=()):
    """
    Parameters
    ----------
    g1: networkx.Graph
    g2: networkx.Graph
    node_attrs: collections.abc.Iterable or None
        Node attributes to consider. If `None`, the node attribute dicts must
        be equal.
    edge_attrs: collections.abc.Iterable or None
        Edge attributes to consider. If `None`, the edge attribute dicts must
        be equal.

    Returns
    -------
    bool
        True if `g1` and `g2` are isomorphic, False otherwise.
    """
    if node_attrs is None:
        node_equal = operator.eq
    else:
        node_equal = iso.categorical_node_match(node_attrs, [''] * len(node_attrs))
    if edge_attrs is None:
        edge_equal = operator.eq
    else:
        edge_equal = iso.categorical_node_match(edge_attrs, [''] * len(edge_attrs))
    matcher = iso.GraphMatcher(g1, g2, node_match=node_equal, edge_match=edge_equal)
    return matcher.is_isomorphic()
Пример #4
0
    def test_symmetry_mcis(self):
        graph1 = nx.Graph()
        nx.add_path(graph1, range(4))

        graph2 = nx.Graph()
        nx.add_path(graph2, range(3))
        graph2.add_edge(1, 3)

        # Only the symmetry of graph2 is taken into account here.
        ismags1 = iso.ISMAGS(graph1, graph2, node_match=iso.categorical_node_match('color', None))
        assert list(ismags1.subgraph_isomorphisms_iter(True)) == []
        found_mcis = _matches_to_sets(ismags1.largest_common_subgraph())
        expected = _matches_to_sets([{0: 0, 1: 1, 2: 2},
                                     {1: 0, 3: 2, 2: 1}])
        assert expected == found_mcis

        # Only the symmetry of graph1 is taken into account here.
        ismags2 = iso.ISMAGS(graph2, graph1, node_match=iso.categorical_node_match('color', None))
        assert list(ismags2.subgraph_isomorphisms_iter(True)) == []
        found_mcis = _matches_to_sets(ismags2.largest_common_subgraph())
        expected = _matches_to_sets([{3: 2, 0: 0, 1: 1},
                                     {2: 0, 0: 2, 1: 1},
                                     {3: 0, 0: 2, 1: 1},
                                     {3: 0, 1: 1, 2: 2},
                                     {0: 0, 1: 1, 2: 2},
                                     {2: 0, 3: 2, 1: 1}])

        assert expected == found_mcis

        found_mcis1 = _matches_to_sets(ismags1.largest_common_subgraph(False))
        found_mcis2 = ismags2.largest_common_subgraph(False)
        found_mcis2 = [{v: k for k, v in d.items()} for d in found_mcis2]
        found_mcis2 = _matches_to_sets(found_mcis2)

        expected = _matches_to_sets([{3: 2, 1: 3, 2: 1},
                                     {2: 0, 0: 2, 1: 1},
                                     {1: 2, 3: 3, 2: 1},
                                     {3: 0, 1: 3, 2: 1},
                                     {0: 2, 2: 3, 1: 1},
                                     {3: 0, 1: 2, 2: 1},
                                     {2: 0, 0: 3, 1: 1},
                                     {0: 0, 2: 3, 1: 1},
                                     {1: 0, 3: 3, 2: 1},
                                     {1: 0, 3: 2, 2: 1},
                                     {0: 3, 1: 1, 2: 2},
                                     {0: 0, 1: 1, 2: 2}])
        assert expected == found_mcis1
        assert expected == found_mcis2
Пример #5
0
    def test_graph(self):

        db = self.inst

        strict, loose = db.build_matrices()
        graph = db.build_graph()

        self.assertRaises(IOError, nx.nx_agraph.write_dot, graph, '/check.dot')

        mol2_graph = nx.read_gpickle("test/basic/molecules.gpickle")

        dic1_nodes = graph.nodes(data=True)
        dic1_edges = graph.edges(data=True)

        dic2_nodes = mol2_graph.nodes(data=True)
        dic2_edges = mol2_graph.edges(data=True)

        self.assertEqual(True, dic1_nodes == dic2_nodes)
        self.assertEqual(True, dic2_edges == dic2_edges)

        nm = iso.categorical_node_match(['fname_comp', 'ID'], ['noname', -1])
        em = iso.categorical_edge_match(['strict_flag', 'similarity'],
                                        [False, -1.0])

        self.assertEqual(
            True,
            nx.is_isomorphic(graph, mol2_graph, node_match=nm, edge_match=em))
Пример #6
0
def _mapped_graph_list(G1, liblist):
    """
    find all matches of library element in the graph
    """

    logging.info("Matching circuit Graph from library elements")
    mapped_graph_list = {}

    for lib_ele in liblist:
        G2 = lib_ele['lib_graph']
        sub_block_name = lib_ele['name']
        #print("Matching:",sub_block_name)
        logging.info("G: %s : %s", sub_block_name, str(' '.join(G2.nodes())))
        GM = isomorphism.GraphMatcher(
            G1,
            G2,
            node_match=isomorphism.categorical_node_match(['inst_type'],
                                                          ['nmos']),
            edge_match=isomorphism.categorical_edge_match(['weight'], [1]))
        if GM.subgraph_is_isomorphic():
            logging.info("ISOMORPHIC : %s", sub_block_name)
            map_list = []
            for Gsub in GM.subgraph_isomorphisms_iter():
                map_list.append(Gsub)
                logging.info("Matched Lib: %s", str(' '.join(Gsub.values())))
                logging.info("Matched Circuit: %s", str(' '.join(Gsub)))
            mapped_graph_list[sub_block_name] = map_list

    return mapped_graph_list
Пример #7
0
    def test_graph_radial_hub_fingerprint(self):

        db = DBMolecules('test/radial/',
                         radial=True,
                         fingerprint=True,
                         fast=True,
                         hub="ejm_46.mol2")

        strict, loose = db.build_matrices()
        graph = db.build_graph()

        mol2_graph = nx.read_gpickle(
            "test/radial/radial_hub_fingerprint_fast.gpickle")

        dic1_nodes = graph.nodes(data=True)
        dic1_edges = graph.edges(data=True)

        dic2_nodes = mol2_graph.nodes(data=True)
        dic2_edges = mol2_graph.edges(data=True)

        self.assertEqual(True, dic1_nodes == dic2_nodes)
        self.assertEqual(True, dic2_edges == dic2_edges)

        nm = iso.categorical_node_match(['fname_comp', 'ID'], ['noname', -1])
        em = iso.categorical_edge_match(['strict_flag', 'similarity'],
                                        [False, -1.0])

        self.assertEqual(
            True,
            nx.is_isomorphic(graph, mol2_graph, node_match=nm, edge_match=em))
Пример #8
0
    def _calculate_reward(self):
        """
        Calculates the shaped reward for current timestep using state and task

        state is EnvState from Agent.py. The comparison needs to be done
        between the current graph and intended graph

        FIXME: task right now is hand-coded, need to include in meta-reasoner
        """
        # nx does not support different tolerances for different edges
        # therefore the comparison is a two-step process for xy and theta
        node_condition = iso.categorical_node_match(['length', 'width'],
                                                    [1, 1])
        edge_condition1 = iso.numerical_edge_match(['delx', 'dely'], [0, 0],
                                                   rtol=self._errortolerancexy)
        edge_condition2 = iso.numerical_edge_match(
            ['deltheta'], [0], rtol=self._errortolerancetheta)
        result1 = nx.is_isomorphic(self._expectation.ws_state,
                                   self._blocks.ws_state,
                                   edge_match=edge_condition1,
                                   node_match=node_condition)
        result2 = nx.is_isomorphic(self._expectation.ws_state,
                                   self._blocks.ws_state,
                                   edge_match=edge_condition2,
                                   node_match=node_condition)
        result = result1 and result2
        if result:
            shaped_reward = self._gamma * len(
                self._missions[self._mission_ptr]) - (self._mission_ptr + 1)
            return (-1 + shaped_reward)
        else:
            return -1
Пример #9
0
 def _is_isomorphic_graphs(self):
     nm = iso.categorical_node_match('label', '')
     em = iso.numerical_edge_match('weight', 1)
     return nx.is_isomorphic(self.graph1,
                             self.graph2,
                             node_match=nm,
                             edge_match=em)
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
Пример #11
0
def main(n_minus_1_pattern_path,n_pattern_level_path):
    selected_patterns_parent=[]
    selected_patterns_child=[]
    all_parent_permuted_graphs=[]
    with open(n_minus_1_pattern_path,'r') as f:
        for line in f.readlines():
            selected_patterns_parent.append(Pattern(None,os.path.join(line.replace("RESULTS","PATTERNS").rstrip()+"/"+line.split("/")[-1].rstrip().replace("/","")+".gml")))
    with open(n_pattern_level_path,'r') as f:
        for line in f.readlines():
            selected_patterns_child.append(Pattern(None,os.path.join(line.replace("RESULTS","PATTERNS").rstrip()+"/"+line.split("/")[-1].rstrip().replace("/","")+".gml")))
        
    nm = iso.categorical_node_match('label', 'label')
    print "Loaded all selected graphs ..."
    subgraphs=get_all_subgraphs_child(selected_patterns_child)
    print "Found all subgraphs ..."
    found_matches={}
    counter=1
    for pattern_path in subgraphs.keys():
         print "Processing ",counter,"child pattern"
         counter+=1
         match_found=False
         for parent in selected_patterns_parent:
             if match_found:
                 break
             for subgr in subgraphs[pattern_path]:                  
                if nx.is_isomorphic(subgr.pattern_graph,parent.pattern_graph,nm):
                    match_found=True
                    found_matches[pattern_path]=parent.pattern_path
                    break
                
             
    print "Nr matches: ",len(found_matches)
    for m in found_matches.keys():
        with open(os.path.join(m).replace("gml","parent"),"w") as f:
            f.write(found_matches[m].split("/")[-1].replace(".gml",""))
Пример #12
0
    def test_build_unique_fragments(self):
        edges = {(e[0], e[1]): None for e in self.pc_edges}
        mol_graph = MoleculeGraph.with_edges(self.pc, edges)
        unique_fragments = mol_graph.build_unique_fragments()
        self.assertEqual(len(unique_fragments), 295)
        nm = iso.categorical_node_match("specie", "ERROR")
        for ii in range(295):
            # Test that each fragment is unique
            for jj in range(ii + 1, 295):
                self.assertFalse(
                    nx.is_isomorphic(unique_fragments[ii].graph,
                                     unique_fragments[jj].graph,
                                     node_match=nm))

            # Test that each fragment correctly maps between Molecule and graph
            self.assertEqual(len(unique_fragments[ii].molecule),
                             len(unique_fragments[ii].graph.nodes))
            species = nx.get_node_attributes(unique_fragments[ii].graph, "specie")
            coords = nx.get_node_attributes(unique_fragments[ii].graph, "coords")

            mol = unique_fragments[ii].molecule
            for ss, site in enumerate(mol):
                self.assertEqual(str(species[ss]), str(site.specie))
                self.assertEqual(coords[ss][0], site.coords[0])
                self.assertEqual(coords[ss][1], site.coords[1])
                self.assertEqual(coords[ss][2], site.coords[2])

            # Test that each fragment is connected
            self.assertTrue(nx.is_connected(unique_fragments[ii].graph.to_undirected()))
Пример #13
0
def subgraph_is_isomorphic(graph, subgraph):
    """
    determines whether main graph contains a subgraph which is isomorphic to input subgraph
    :param graph: main graph
    :param subgraph: a subgraph to be searched in main graph
    :return: boolean
    """
    graph_gspan = networkx_to_gspan(graph, 0)
    subgraph_gspan = networkx_to_gspan(subgraph, 1)

    # create temporary files during gspan processing
    input_fd, input_filename = tempfile.mkstemp()
    output_fd, output_filename = tempfile.mkstemp()

    with os.fdopen(input_fd, 'w', encoding='utf-8') as input_handler:
        input_handler.write(graph_gspan + subgraph_gspan)
    orig_stdout = sys.stdout
    sys.stdout = os.fdopen(output_fd, 'w', encoding='utf-8')
    subgraph_miner = gSpan(input_filename, 2, where=True)
    subgraph_miner.run()
    sys.stdout = orig_stdout
    mined_subgraphs = parse_mined_gspan_file(output_filename)

    # remove temporary files
    os.remove(input_filename)
    os.remove(output_filename)

    em = iso.numerical_edge_match('weight', 0)
    nm = iso.categorical_node_match('name', None)
    for mined_subgraph in mined_subgraphs:
        graph_matcher = iso.GraphMatcher(mined_subgraph, subgraph, node_match=nm, edge_match=em)
        if graph_matcher.is_isomorphic():
            return True
    return False
Пример #14
0
def isomorphism(pattern, target, nx_structures):
    """
    Uses the NetworkX isomorphism algorithm to check if the pattern graph and the target graph are isomorphic.

    The faster_could_be_isomorphic method is used to discount two structures if they could not be isomorphic.
    :param pattern: a molecule object which is to be tested for isomorphism
    :param target: a molecule object which pattern graph is to be compared against
    :return: None if the graphs are not isomorphic
    :return: a dictionary which maps the indices of the two NetworkX graphs together if they are isomorphic
    """
    if pattern not in nx_structures:
        nx_structures[pattern] = create_nx_graph(pattern, nx_structures)
    if target not in nx_structures:
        nx_structures[target] = create_nx_graph(target, nx_structures)
    if not nx.faster_could_be_isomorphic(nx_structures[pattern],
                                         nx_structures[target]):
        # Graphs are definitely not isomorphic
        return None

    #print pattern, target
    # Ensures the isomorphism considers the vertex label and edge type
    matcher = iso.GraphMatcher(
        nx_structures[pattern],
        nx_structures[target],
        node_match=iso.categorical_node_match('label', 'C'),
        edge_match=iso.categorical_edge_match('type', 'single'))
    if matcher.is_isomorphic():
        return matcher.mapping
Пример #15
0
def uniquelist(l1, l2, fva):
    l = []
    temp = []
    # li=[]
    nm = iso.categorical_node_match('elem', 'C')
    em = iso.numerical_edge_match('weight', 1)

    for i, k in zip(l1, fva):
        flag = 1
        # c=0
        for j in l2:
            # c+=1
            #             GM = nx.algorithms.isomorphism.GraphMatcher(i,j)
            if iso.is_isomorphic(i, j, edge_match=em, node_match=nm):
                #                 print "1"
                flag = 0
                # li.append(c)
                break
        if flag == 1:
            l.append(i)
            temp.append(k)
    # print len(l)
    # print len(li)
    # print li
    # c=0
    # for i in range(0,len(l2)):


#         c=0
# if i+1 not in li:
# l.append(l2[c])
# print "hola"
# else:
# c+=1
    return l, temp
Пример #16
0
def compare(cc1, cc2):
    s1 = {a.id for a in cc1.atoms}
    s2 = {a.id for a in cc2.atoms}
    b1 = {b.lexicographic_str() for b in cc1.rt.bonds}
    b2 = {b.lexicographic_str() for b in cc2.rt.bonds}
    if s1 == s2 and b1 == b2:
        #print(cc1.name, "the same")
        return
    G1 = graph_from_chemcomp(cc1)
    G2 = graph_from_chemcomp(cc2)
    node_match = isomorphism.categorical_node_match('Z', 0)
    GM = isomorphism.GraphMatcher(G1, G2, node_match=node_match)
    if GM.is_isomorphic():
        print(cc1.name, 'is isomorphic')
        # we could use GM.match(), but here we try to find the shortest diff
        short_diff = None
        for n, mapping in enumerate(GM.isomorphisms_iter()):
            diff = {k: v for k, v in mapping.items() if k != v}
            if short_diff is None or len(diff) < len(short_diff):
                short_diff = diff
            if n == 10000:  # don't spend too much here
                print(' (it may not be the simplest isomorphism)')
                break
        for id1, id2 in short_diff.items():
            print('\t', id1, '->', id2)
    else:
        print(cc1.name, 'differs')
        if s2 - s1:
            print('\tmissing:', ' '.join(s2 - s1))
        if s1 - s2:
            print('\textra:  ', ' '.join(s1 - s2))
Пример #17
0
    def _get_subgraph_N_X_N(self, graph1, graph2, name1, name2):
        ret = {'subgraph_N_0_N': 0}
        # TODO: not worth counting all of them
        # ret = {
        #     'subgraph_N_0_N' : 0,
        #     'subgraph_N_1_N' : 0,
        #     'subgraph_N_2_N' : 0
        # }
        subgraphs1 = self._get_subgraphs(graph1, name1, 2)
        subgraphs2 = self._get_subgraphs(graph2, name2, 2)

        for r in itertools.product(subgraphs1, subgraphs2):
            GM = nx.algorithms.isomorphism.GraphMatcher(
                r[0],
                r[1],
                node_match=iso.categorical_node_match(['str_name'], ['name']),
                edge_match=iso.numerical_edge_match(['color'], [-1]))
            if GM.is_isomorphic():
                for u, v, d in r[0].edges(data=True):
                    if d['color'] == 0:
                        ret['subgraph_N_0_N'] += 1
                        # print u + " " + v + " 0"
                    # TODO: appears to be unuseful
                    # elif d['color'] == 1:
                    #     ret['subgraph_N_1_N'] += 1
                    #     # print u + " " + v + " 1"
                    # elif d['color'] == 2:
                    #     ret['subgraph_N_2_N'] += 1
                    #     # print u + " " + v + " 2"
        return ret
Пример #18
0
    def _get_subgraph_N_X_N(self, graph1, graph2, name1, name2):
        ret = {
            'subgraph_N_0_N' : 0
        }
        # TODO: not worth counting all of them
        # ret = {
        #     'subgraph_N_0_N' : 0,
        #     'subgraph_N_1_N' : 0,
        #     'subgraph_N_2_N' : 0
        # }
        subgraphs1 = self._get_subgraphs(graph1, name1, 2)
        subgraphs2 = self._get_subgraphs(graph2, name2, 2)

        for r in itertools.product(subgraphs1, subgraphs2):
            GM =  nx.algorithms.isomorphism.GraphMatcher(r[0], r[1],
                                                         node_match=iso.categorical_node_match(['str_name'], ['name']),
                                                         edge_match=iso.numerical_edge_match(['color'], [-1]))
            if GM.is_isomorphic():
                for u, v, d in r[0].edges(data=True):
                    if d['color'] == 0:
                        ret['subgraph_N_0_N'] += 1
                        # print u + " " + v + " 0"
                    # TODO: appears to be unuseful
                    # elif d['color'] == 1:
                    #     ret['subgraph_N_1_N'] += 1
                    #     # print u + " " + v + " 1"
                    # elif d['color'] == 2:
                    #     ret['subgraph_N_2_N'] += 1
                    #     # print u + " " + v + " 2"
        return ret
Пример #19
0
 def __eq__(self, other):  # two rules are equal if the LHSs match and RHSs are isomorphic
     g1 = nx.convert_node_labels_to_integers(self.graph)
     g2 = nx.convert_node_labels_to_integers(other.graph)
     # and nx.fast_could_be_isomorphic(g1, g2) \
     return self.lhs == other.lhs \
            and nx.is_isomorphic(g1, g2, edge_match=iso.numerical_edge_match('weight', 1.0),
                                 node_match=iso.categorical_node_match('label', ''))
Пример #20
0
def isIsomorphism(n, G1, G2):
    drawIsomorphic(n, G1)

    # g1 = nx.DiGraph()
    # g2 = nx.DiGraph()
    # nx.add_path(G1, G1, weight=1)
    # nx.add_path(G2, G2, weight=2)
    # em = iso.numerical_edge_match("weight", 1)
    # nx.is_isomorphic(G1, G2)  # no weights considered
    # g = nx.is_isomorphic(G1, G2)
    # print("is isomorphic? ", g)

    g1 = nx.MultiDiGraph()
    g2 = nx.MultiDiGraph()
    g1.add_nodes_from(G1, fill="red")
    g2.add_nodes_from(G2, fill="red")
    nx.add_path(g1, G1, weight=3, linewidth=2.5)
    nx.add_path(g2, G2, weight=3)
    nm = iso.categorical_node_match("fill", "red")
    nx.is_isomorphic(g1, g2, node_match=nm)
    g = nx.is_isomorphic(g1, g2, node_match=nm)
    print("is isomorphic? ", g)

    g3 = nx.Graph()
    # g1.add_node("a")
    g3.add_edges_from(G2)
    nx.draw(g3)
    plt.savefig("G2.png")  # save as png
    plt.show()

    return g
Пример #21
0
def has_isomorphism_with(g, graphs):
    for oldgraph in graphs:
        if nx.is_isomorphic(g,
                            oldgraph,
                            node_match=iso.categorical_node_match(
                                'nodetype', 'dumb')):
            return True
    return False
Пример #22
0
    def build(self):
        self.nm = iso.categorical_node_match("color", "")
        self.em = iso.numerical_edge_match("weight", 1)

        self.g1.add_node("A", color="red")
        self.g2.add_node("C", color="blue")

        self.g1.add_edge("A", "B", weight=1)
        self.g2.add_edge("C", "D", weight=1)
    def build(self):
        self.nm = iso.categorical_node_match('color', '')
        self.em = iso.numerical_edge_match('weight', 1)

        self.g1.add_node('A', color='red')
        self.g2.add_node('C', color='blue')

        self.g1.add_edge('A', 'B', weight=1)
        self.g2.add_edge('C', 'D', weight=1)
Пример #24
0
def get_mapping_ts_template(larger_graph, smaller_graph):
    logger.info('Getting mapping of molecule onto the TS template')
    logger.info('Running isomorphism')
    graph_matcher = isomorphism.GraphMatcher(
        larger_graph,
        smaller_graph,
        node_match=isomorphism.categorical_node_match('atom_label', 'C'),
        edge_match=isomorphism.categorical_edge_match('active', False))
    return next(graph_matcher.match())
Пример #25
0
def _mapped_graph_list(G1, liblist, CLOCK=None, DIGITAL=False):
    """
    find all matches of library element in the graph
    """

    logger.debug("Matching circuit Graph from library elements")
    mapped_graph_list = {}

    for lib_ele in liblist:
        G2 = lib_ele['graph']
        # DIgital blocks only transistors:
        nd = [node for node in G2.nodes()
                if 'net' not in G2.nodes[node]["inst_type"]]
        if DIGITAL and len(nd)>1:
            continue

        sub_block_name = lib_ele['name']
        logger.debug(f"Matching: {sub_block_name} : {' '.join(G2.nodes())}")
        GM = isomorphism.GraphMatcher(
            G1, G2,
            node_match=isomorphism.categorical_node_match(['inst_type'],
                                                          ['nmos']),
            edge_match=isomorphism.categorical_edge_match(['weight'], [1]))

        if GM.subgraph_is_isomorphic():
            logger.debug(f"ISOMORPHIC : {sub_block_name}")
            map_list = []
            for Gsub in GM.subgraph_isomorphisms_iter():
                all_nd = [
                key for key in Gsub
                if 'net' not in G1.nodes[key]["inst_type"]]
                logger.debug(f"matched inst: {all_nd}")
                if len(all_nd)>1 and dont_touch_clk(Gsub,CLOCK):
                    logger.debug("Discarding match due to clock")
                    continue
                if sub_block_name.startswith('DP') or sub_block_name.startswith('CMC'):
                    if G1.nodes[all_nd[0]]['values'] == G1.nodes[all_nd[1]]['values'] and \
                        compare_balanced_tree(G1,get_key(Gsub,'DA'),get_key(Gsub,'DB')) :
                        if 'SA' in Gsub.values() and \
                        compare_balanced_tree(G1,get_key(Gsub,'SA'),get_key(Gsub,'SB')) :
                            map_list.append(Gsub)
                            logger.debug(f"Matched Lib: {' '.join(Gsub.values())}")
                            logger.debug(f"Matched Circuit: {' '.join(Gsub)}")
                        else:
                            map_list.append(Gsub)
                            logger.debug(f"Matched Lib: {' '.join(Gsub.values())}")
                            logger.debug(f"Matched Circuit: {' '.join(Gsub)}")
                    else:
                        logger.debug(f"Discarding match {sub_block_name}, {G1.nodes[all_nd[0]]['values']}, {G1.nodes[all_nd[1]]['values']}")
                else:
                    map_list.append(Gsub)
                    logger.debug(f"Matched Lib: {' '.join(Gsub.values())}")
                    logger.debug(f"Matched Circuit: {' '.join(Gsub)}")
            mapped_graph_list[sub_block_name] = map_list

    return mapped_graph_list
Пример #26
0
    def build(self):

        self.nm = iso.categorical_node_match('color', '')
        self.em = iso.numerical_edge_match('weight', 1)

        self.g1.add_node('A', color='red')
        self.g2.add_node('C', color='blue')

        self.g1.add_edge('A','B', weight=1)
        self.g2.add_edge('C','D', weight=1)
Пример #27
0
        def gammaIso(G1, G2):

            nm = isomorphism.categorical_node_match(['fillcolor', 'shape'],
                                                    ['', ''])
            em = isomorphism.categorical_multiedge_match('color', '')

            #G1.remove_nodes_from(nx.isolates(G1)) #Drop Isolates
            #G2.remove_nodes_from(nx.isolates(G2)) #Drop Isolates

            #Create set of induced subgraphs for the Graphs and check for isomorphism.
            len_G1_nodes = len(G1.nodes())
            len_G2_nodes = len(G2.nodes())

            min_len = min(len_G1_nodes, len_G2_nodes)
            max_len = max(len_G1_nodes, len_G2_nodes)

            G1_list = createAllComboList(G1.nodes(), min_len)
            G2_list = createAllComboList(G2.nodes(), min_len)

            induced_subgraph_G1 = [
                G1.subgraph(node_list) for node_list in G1_list
            ]
            induced_subgraph_G2 = [
                G2.subgraph(node_list) for node_list in G2_list
            ]

            new_induced_subgraph_G1 = []
            new_induced_subgraph_G2 = []

            #Remove graphs with empty nodes and empty edges
            for g in induced_subgraph_G1:
                if (len(g.nodes()) == 0 or len(g.edges()) == 0):
                    continue
                new_induced_subgraph_G1.append(g)

            for g in induced_subgraph_G2:
                if (len(g.nodes()) == 0 or len(g.edges()) == 0):
                    continue
                new_induced_subgraph_G2.append(g)

            induced_subgraph_G1_rev = new_induced_subgraph_G1[::-1]
            induced_subgraph_G2_rev = new_induced_subgraph_G2[::-1]

            similarity = 0

            for g1 in induced_subgraph_G1_rev:
                for g2 in induced_subgraph_G2_rev:
                    if (len(g1.nodes()) == len(g2.nodes())
                            and len(g1.edges()) == len(g2.edges())):
                        GM = isomorphism.MultiDiGraphMatcher(g1, g2, nm, em)
                        if (GM.is_isomorphic()):
                            similarity = max(similarity,
                                             len(g1.nodes()) / float(max_len))
                            return similarity, GM.mapping
            return 0, {}
Пример #28
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
Пример #29
0
def is_subgraph_isomorphic(larger_graph, smaller_graph):
    logger.info('Running subgraph isomorphism')
    graph_matcher = isomorphism.GraphMatcher(
        larger_graph,
        smaller_graph,
        node_match=isomorphism.categorical_node_match('atom_label', 'C'),
        edge_match=isomorphism.categorical_edge_match('active', False))
    if graph_matcher.subgraph_is_isomorphic():
        return True

    return False
Пример #30
0
def thread_function(graph, subGraphs):
    vec = np.zeros(len(subGraphs))
    for s_idx, subgraph in enumerate(subGraphs):
        GM = iso.GraphMatcher(
            graph,
            subgraph,
            node_match=iso.categorical_node_match('label', ''),
            edge_match=iso.categorical_edge_match('label', ''))
        if GM.subgraph_is_isomorphic():
            vec[s_idx] = 1
    return vec
Пример #31
0
def _match_graphs(pattern, candidate, exact):
    """ Compare two pattern graphs for isomorphism """
    node_matcher = categorical_node_match('id', default=None)
    if exact:
        return nx.is_isomorphic(pattern._as_graph(),
                                candidate._as_graph(),
                                node_match=node_matcher)
    else:
        return GraphMatcher(candidate._as_graph(),
                            pattern._as_graph(),
                            node_match=node_matcher).subgraph_is_isomorphic()
Пример #32
0
def equals(g1, g2):
    #---
    assert isinstance(g1, nx.Graph) and isinstance(g2, nx.Graph)
    #---
    return nx.isomorphism.GraphMatcher(
        g1,
        g2,
        #node_match=nm,
        node_match=iso.categorical_node_match('type', ''),
        #edge_match=em
        edge_match=iso.categorical_multiedge_match('prop',
                                                   '')).is_isomorphic()
Пример #33
0
    def _get_subgraph_3_nodes(self, graph1, graph2, name1, name2):
        ret = {
            'subgraph_3N' : 0
        }
        subgraphs1 = self._get_subgraphs(graph1, name1, 3)
        subgraphs2 = self._get_subgraphs(graph2, name2, 3)

        for r in itertools.product(subgraphs1, subgraphs2):
            GM =  nx.algorithms.isomorphism.GraphMatcher(r[0], r[1],
                                                         node_match=iso.categorical_node_match(['str_name'], ['name']),
                                                         edge_match=iso.numerical_edge_match(['color'], [-1]))
            if GM.is_isomorphic():
                ret['subgraph_3N'] += 1
        return ret
Пример #34
0
    def __ne__(self, other):

        ''' Function has two molecules as input and decides whether or not 
            they are the same molecule based on the graph. 
            Both the node labels and graph topology must match to be equal '''

        # set up the function that is called to determine the node attribute
        # used to determine equality of the nodes        
        nm = iso.categorical_node_match('atom', Atom(0,'Xx'))
        
        # check that both networks are isomorphic - same number of
        # nodes and same edge connection pattern and that the node atom types 
        # are equivalent 
        return nx.is_isomorphic(self.topology, other.topology, node_match=nm)
Пример #35
0
def get_redox_graph_mapping(G1, G2):
    """Given two graphs, returns subgraph mapping (after removing redox protons)
    ***Now also returns oxygens binded to redox protons in a tuple with the mapping***
    This is a function written for the ease of my research process"""
    if nx.number_of_nodes(G1) > nx.number_of_nodes(G2):
        G1 = G1
        x = remove_redox_protons(G1)
        G1, Hydroxy_oxygen = x[0], x[1]
        Hydroxy_oxygen.append(True)
    else:
        G2 = G2
        x = remove_redox_protons(G2)
        G2, Hydroxy_oxygen = x[0], x[1]
        Hydroxy_oxygen.append(False)
    Gm = iso.GraphMatcher(G1,G2,node_match=iso.categorical_node_match(['Element'],['C']))
    Gm.is_isomorphic()
    return (Gm.mapping,Hydroxy_oxygen)
Пример #36
0
    def _get_subgraph_N(self, graph1, graph2, name1, name2):
        ret = 0
        subgraphs1 = self._get_subgraphs(graph1, name1, 1)
        subgraphs2 = self._get_subgraphs(graph2, name2, 1)

        for r in itertools.product(subgraphs1, subgraphs2):
            GM =  nx.algorithms.isomorphism.GraphMatcher(r[0], r[1],
                                                         node_match=iso.categorical_node_match(['str_name'], ['name']),
                                                         edge_match=iso.numerical_edge_match(['color'], [-1]))
            if GM.is_isomorphic():
                is_upper = False
                for n, d in r[0].nodes_iter(data=True):
                    if d['str_name'].isupper():
                        is_upper = True
                if not is_upper:
                    ret = 1
        return {'subgraph_N' : ret}
Пример #37
0
def supportValue(gList, sg):
    '''
    求支持数量,即gList中包含sg的图的数量

    gList [Graph, ]
    sg Graph
    '''
    print '*** start ***'
    v = 0
    sptList = []
    for i in range(len(gList)):
        g = gList[i]
        GM = nx.isomorphism.DiGraphMatcher(g, sg, node_match=iso.categorical_node_match('name', None))
        if GM.subgraph_is_isomorphic():
            v += 1
            sptList.append(i)
    print '*** end.. ***'
    return v, sptList
Пример #38
0
def listener():
    global G,spatial_nodes_counter,temporal_nodes_counter,labels,A,G0,Activities

    rospy.init_node('Graphs2')
    rospy.Subscriber("QSRs", QSR, callback_graphs)
    r = rospy.Rate(10) # 10hz

    time.sleep(1)


    nm = iso.categorical_node_match('type1', '')
    em = iso.categorical_edge_match('dirx', '')

    while not rospy.is_shutdown():

	plotting = False
	G1 = graph_maker(A.o1,A.o2,A.spatial,A.temporal,A.objects,plotting)

	results = []
	for i in range(len(Activities)):
		flag = 1
		G_copy = G1
		counter = 0
		while flag==1:
			GM = iso.GraphMatcher(G_copy,Activities[int(i)],node_match=nm,edge_match=em)
			if GM.subgraph_is_isomorphic():
				counter +=1
			used_nodes1 = GM.mapping
			if used_nodes1 != {}:
				#print list(used_nodes1)
				#print [n for n in list(used_nodes1) if G_copy.node[n]['type2']=='temporal']
				used_nodes2 = []
				used_nodes2 = np.append(used_nodes2, [n for n in list(used_nodes1) if G_copy.node[n]['type2']=='temporal'])
				G_copy.remove_nodes_from(used_nodes2)	# remove temporal nodes from the graph
			else:
	 			flag = 0
		 		results = np.append(results,counter)

	msg = []
	for i in range(len(activities_names)):
		msg = np.append(msg,activities_names[i]+'='+str(results[i]))
	print msg
        r.sleep()
Пример #39
0
def _match_graphs(pattern, candidate, exact, count):
    """ Compare two pattern graphs for isomorphism """
    node_matcher = categorical_node_match('id', default=None)
    if exact:
        match = nx.is_isomorphic(pattern._as_graph(),
                                 candidate._as_graph(),
                                 node_match=node_matcher)
        return 1 if count else match
    else:
        gm = GraphMatcher(
            candidate._as_graph(), pattern._as_graph(),
            node_match=node_matcher
        )
        if count:
            if pattern.match_once:
                return 1 if gm.subgraph_is_isomorphic() else 0
            return sum(1 for _ in gm.subgraph_isomorphisms_iter())
        else:
            return gm.subgraph_is_isomorphic()
Пример #40
0
    def categorize_functional_groups(self, groups):
        """
        Determine classes of functional groups present in a set.

        :param groups: Set of functional groups.
        :return: dict containing representations of the groups, the indices of
            where the group occurs in the MoleculeGraph, and how many of each
            type of group there is.
        """

        categories = {}

        em = iso.numerical_edge_match("weight", 1)
        nm = iso.categorical_node_match("specie", "C")

        for group in groups:
            atoms = [self.molecule[a] for a in group]
            species = [a.specie for a in atoms]
            coords = [a.coords for a in atoms]

            adaptor = BabelMolAdaptor(Molecule(species, coords))
            # Use Canonical SMILES to ensure uniqueness
            smiles = adaptor.pybel_mol.write("can").strip()

            if smiles in categories:
                this_subgraph = self.molgraph.graph.subgraph(list(group)).to_undirected()
                for other in categories[smiles]["groups"]:
                    other_subgraph = self.molgraph.graph.subgraph(list(other)).to_undirected()

                    if not nx.is_isomorphic(this_subgraph, other_subgraph,
                                            edge_match=em, node_match=nm):
                        break

                    if group not in categories[smiles]["groups"]:
                        categories[smiles]["groups"].append(group)
                        categories[smiles]["count"] += 1

            else:
                categories[smiles] = {"groups": [group],
                                      "count": 1}

        return categories
Пример #41
0
def generate_all_unique_dependency_subgraphs(graphs, node_attrib='label',
                                             edge_attrib='label'):
    same_node_label = iso.categorical_node_match(node_attrib, '')
    same_edge_label = iso.categorical_edge_match(edge_attrib, '')
    if len(graphs) == 0:
        return []
    elif len(graphs) == 1:
        return list(get_dependency_subgraphs(graphs[0], node_attrib=node_attrib))
    else:
        unique_subgraphs = list(get_dependency_subgraphs(
            graphs[0], node_attrib=node_attrib, edge_attrib=edge_attrib))
        for graph in graphs[1:]:
            for subgraph in get_dependency_subgraphs(graph):
                sg_combs = itertools.product([subgraph], unique_subgraphs)
                if not any(nx.is_isomorphic(new_sg, old_sg,
                                            node_match=same_node_label,
                                            edge_match=same_edge_label)
                           for new_sg, old_sg in sg_combs):
                    unique_subgraphs.append(subgraph)
        return unique_subgraphs
    def _nx_isomorphism(self, pattern, target):
        """
        Uses the NetworkX isomorphism algorithm to check if the pattern graph and the target graph are isomorphic.

        The faster_could_be_isomorphic method is used to discount two structures if they could not be isomorphic.
        :param pattern: a molecule object which is to be tested for isomorphism
        :param target: a molecule object which pattern graph is to be compared against
        :return: None if the graphs are not isomorphic
        :return: a dictionary which maps the indices of the two NetworkX graphs together if they are isomorphic
        """
        if pattern not in self.structure_nx:
            self._create_nx_graph(pattern)
        if target not in self.structure_nx:
            self._create_nx_graph(target)
        if not nx.faster_could_be_isomorphic(self.structure_nx[pattern], self.structure_nx[target]):
            # Graphs are definitely not isomorphic
            return None
        # Ensures the isomorphism considers the vertex label and edge type
        matcher = iso.GraphMatcher(self.structure_nx[pattern], self.structure_nx[target],
                                   node_match=iso.categorical_node_match('label', 'C'),
                                   edge_match=iso.categorical_edge_match('type', 'single'))
        if matcher.is_isomorphic():
            return matcher.mapping
def listener():
    global G,spatial_nodes_counter,temporal_nodes_counter,labels,A1,G0,Activities,activity,ID
    
    # initialize ROS node
    rospy.init_node('sub_activity')
    rospy.Subscriber('QSRs', QSR, callback_graphs)
    rospy.Subscriber('CAD120_act', ActivityName, callback_activity)
    r = rospy.Rate(10) # 20hz

    # important delay - keep it
    time.sleep(3)

    # matching proporties
    nm = iso.categorical_node_match('type1', '')
    em = iso.categorical_edge_match('dirx', '')

    # preparing the sub_activity matrix
    window = 250
    number = len(activities_names)
    th = 15			# thickness of qsr lines
    name_window = 200		# left margin to write activity names

    subA_vector = np.zeros(shape=(number, window), dtype=int)  		# initilize the sub_activity matrix actual one
    subA = np.zeros(shape=(th*number, window, 3), dtype=int)+255  	# initilize the sub_activity matrix for image
    subA_interval = np.zeros(shape=(number, window, 1), dtype=int)  	# initilize the sub_activity matrix for intervals

    # preparing the image
    img = np.zeros((th*number,window+name_window,3), np.uint8)+255		# initializing the image	
    img[:,name_window-5:name_window,:] = np.zeros((th*number,5,3), np.uint8)

    # writing on the image
    counter = 0
    for i in range(len(activities_names)):
	cv2.putText(img,activities_names[i],(10,(th*(counter+1))-5), cv2.FONT_HERSHEY_SIMPLEX, .5,(0,0,0),1)
	counter = counter+1

    # writing on file the histogram
    f = open('/home/omari/catkin_ws/src/cad120/src/histogram'+'.txt', 'w')
    ID=0
    ID_old = 0
    activity_old = 'nothing'

    while not rospy.is_shutdown():

	G1 = graph_maker(A1.o1,A1.o2,A1.spatial,A1.temporal,A1.objects,False)

	results = []
	for i in range(len(Activities)):
		flag = 1
		G_copy = G1
		counter = 0
		while flag==1:
			GM = iso.GraphMatcher(G_copy,Activities[int(i)],node_match=nm,edge_match=em)
			if GM.subgraph_is_isomorphic():
				counter +=1
			used_nodes1 = GM.mapping
			if used_nodes1 != {}:
				#print list(used_nodes1)
				#print [n for n in list(used_nodes1) if G_copy.node[n]['type2']=='temporal']
				used_nodes2 = []
				used_nodes2 = np.append(used_nodes2, [n for n in list(used_nodes1) if G_copy.node[n]['type2']=='temporal'])
				G_copy.remove_nodes_from(used_nodes2)	# remove temporal nodes from the graph
			else:
	 			flag = 0
		 		results = np.append(results,counter)

    	subA[:,0:window-1,:] = subA[:,1:window,:]
	subA_vector[:,0:window-1] = subA_vector[:,1:window]

	counter = 0
	for i1 in results:
	    if i1>0:
		subA[th*counter:th*(counter+1),window-1,:] = [255,0,0]
		subA_vector[counter,window-1] = 1
	    else:
		subA[th*counter:th*(counter+1),window-1,:] = [255,255,255]
		subA_vector[counter,window-1] = 0
	    counter += 1


	# If you ever needed to do the interval,
	# 1 find sub_interval
	# 2 find the first positive number because thats where the first pick is
	"""
	subA_interval = subA[th,:,2]-subA[0,:,2]
	index_pk = list(np.where(subA_interval==255))
	index_pc = np.where(subA_interval==-255)
	if list(index_pk[0]) !=[]:
		I_pk = list(index_pk[0])[0]
		for j1 in range(len(list(index_pk[0]))-1):
		    if list(index_pk[0])[j1+1]-list(index_pk[0])[j1] > 1:
			I_pk = np.append(I_pk,list(index_pk[0])[j1+1])

	if list(index_pc[0]) !=[]:
		I_pc = list(index_pc[0])[0]
		for j1 in range(len(list(index_pc[0]))-1):
		    if list(index_pc[0])[j1+1]-list(index_pc[0])[j1] > 1:
			I_pc = np.append(I_pc,list(index_pc[0])[j1+1])
	"""
	counter_sub_acivities = np.zeros((number), np.uint8)
	for i1 in range(number):
	    index_pk = list(np.where(subA_vector[i1,:]==1))
	    if list(index_pk[0]) !=[]:
		counter_sub_acivities[i1] = 1
		for j1 in range(len(list(index_pk[0]))-1):
		    if list(index_pk[0])[j1+1]-list(index_pk[0])[j1] > 1:
			counter_sub_acivities[i1] += 1

	if ID_old != ID:
		#-------------------#
		f.write(activity_old+',')
		f.write(str(counter_sub_acivities))
		f.write('\n')
		#-------------------#
		print activity_old,ID_old,counter_sub_acivities

		ID_old = ID
		activity_old = activity[0].split('/')[0]
		if ID[0] == '1204145902':
			f.close()
			print 'Done'

    		subA_vector = np.zeros(shape=(number, window), dtype=int)  		# initilize the sub_activity matrix actual one

    	img[:,name_window:window+name_window,:] = subA

        r.sleep()
    	cv2.imshow('sub activities',img)
    	k = cv2.waitKey(1) & 0xFF
Пример #44
0
 def __eq__(self, other):
     """Return True if the two structures are isomorphic."""
     func_vals = iso.categorical_node_match(self.funcs.polarizing + self.funcs.labeling, repeat(None))
     func_name = iso.categorical_edge_match("func", None)
     return nx.is_isomorphic(self, other, func_vals, func_name)
Пример #45
0
def listener():
    global G,spatial_nodes_counter,temporal_nodes_counter,labels,A1,G0,Activities,activity,ID
    
    # initialize ROS node
    rospy.init_node('sub_activity')
    rospy.Subscriber('QSRs', QSR, callback_graphs)
    rospy.Subscriber('CAD120_act', ActivityName, callback_activity)
    r = rospy.Rate(10) # 20hz

    # important delay - keep it
    time.sleep(3)

    # matching proporties
    nm = iso.categorical_node_match('type1', '')
    em = iso.categorical_edge_match('dirx', '')

    # preparing the sub_activity matrix
    window = 150
    number = len(activities_names)
    th = 15			# thickness of qsr lines
    name_window = 200		# left margin to write activity names

    subA_vector = np.zeros(shape=(number, window), dtype=int)  		# initilize the sub_activity matrix actual one
    subA = np.zeros(shape=(th*number, window, 3), dtype=int)+255  	# initilize the sub_activity matrix for image
    subA_interval = np.zeros(shape=(number, window, 1), dtype=int)  	# initilize the sub_activity matrix for intervals

    # preparing the image
    img = np.zeros((th*number,window+name_window,3), np.uint8)+255		# initializing the image	
    img[:,name_window-5:name_window,:] = np.zeros((th*number,5,3), np.uint8)

    # writing on the image
    counter = 0
    for i in range(len(activities_names)):
	cv2.putText(img,activities_names[i],(10,(th*(counter+1))-5), cv2.FONT_HERSHEY_SIMPLEX, .5,(0,0,0),1)
	counter = counter+1

    # KNN
    knn = Training()
    KNN_Timer = 0
    Main_Counter = 0

    while not rospy.is_shutdown():

	G1 = graph_maker(A1.o1,A1.o2,A1.spatial,A1.temporal,A1.objects,False)

	results = []
	for i in range(len(Activities)):
		flag = 1
		G_copy = G1
		counter = 0
		while flag==1:
			GM = iso.GraphMatcher(G_copy,Activities[int(i)],node_match=nm,edge_match=em)
			if GM.subgraph_is_isomorphic():
				counter +=1
			used_nodes1 = GM.mapping
			if used_nodes1 != {}:
				#print list(used_nodes1)
				#print [n for n in list(used_nodes1) if G_copy.node[n]['type2']=='temporal']
				used_nodes2 = []
				used_nodes2 = np.append(used_nodes2, [n for n in list(used_nodes1) if G_copy.node[n]['type2']=='temporal'])
				G_copy.remove_nodes_from(used_nodes2)	# remove temporal nodes from the graph
			else:
	 			flag = 0
		 		results = np.append(results,counter)

    	subA[:,0:window-1,:] = subA[:,1:window,:]
	subA_vector[:,0:window-1] = subA_vector[:,1:window]

	counter = 0
	for i1 in results:
	    if i1>0:
		subA[th*counter:th*(counter+1),window-1,:] = [255,0,0]
		subA_vector[counter,window-1] = 1
	    else:
		subA[th*counter:th*(counter+1),window-1,:] = [255,255,255]
		subA_vector[counter,window-1] = 0
	    counter += 1


	# If you ever needed to do the interval,
	# 1 find sub_interval
	# 2 find the first positive number because thats where the first pick is
	"""
	subA_interval = subA[th,:,2]-subA[0,:,2]
	index_pk = list(np.where(subA_interval==255))
	index_pc = np.where(subA_interval==-255)
	if list(index_pk[0]) !=[]:
		I_pk = list(index_pk[0])[0]
		for j1 in range(len(list(index_pk[0]))-1):
		    if list(index_pk[0])[j1+1]-list(index_pk[0])[j1] > 1:
			I_pk = np.append(I_pk,list(index_pk[0])[j1+1])

	if list(index_pc[0]) !=[]:
		I_pc = list(index_pc[0])[0]
		for j1 in range(len(list(index_pc[0]))-1):
		    if list(index_pc[0])[j1+1]-list(index_pc[0])[j1] > 1:
			I_pc = np.append(I_pc,list(index_pc[0])[j1+1])
	"""

	# testing the hitogram
	if KNN_Timer == 5:
	    counter_sub_acivities = np.array(np.zeros((1,40)), dtype = np.float32)
	    for i1 in range(number):
	    	index_pk = list(np.where(subA_vector[i1,:]==1))
	    	if list(index_pk[0]) !=[]:
		    counter_sub_acivities[0,i1] = 1
		    for j1 in range(len(list(index_pk[0]))-1):
		    	    if list(index_pk[0])[j1+1]-list(index_pk[0])[j1] > 1:
				counter_sub_acivities[0,i1] += 1

	    #ret,result,neighbours,dist = knn.find_nearest(counter_sub_acivities[0:1,:],k=1)
	    print counter_sub_acivities
	    KNN_Timer = 0
	    Main_Counter +=1
	else:
	    KNN_Timer += 1

    	img[:,name_window:window+name_window,:] = subA

    	cv2.imshow('sub activities',img)
    	k = cv2.waitKey(1) & 0xFF
        r.sleep()
Пример #46
0
def listener():
    global QSR_msg,Activities
    
    # initialize ROS node
    rospy.init_node('sub_activity')
    rospy.Subscriber('QSRs', QSR, callback_graphs)
    pub = rospy.Publisher('SubActivities', SubAct)
    r = rospy.Rate(5) # 5hz

    # important delay - keep it
    time.sleep(1)

    # matching proporties
    nm = iso.categorical_node_match('type1', '')
    em = iso.categorical_edge_match('dirx', '')

    # preparing the sub_activity matrix
    window = 150
    number = len(activities_names)
    th = 15			# thickness of qsr lines
    name_window = 200		# left margin to write activity names

    subA_vector = np.zeros(shape=(number, window), dtype=int)  		# initilize the sub_activity matrix actual one
    subA = np.zeros(shape=(th*number, window, 3), dtype=int)+255  	# initilize the sub_activity matrix for image
    #subA_interval = np.zeros(shape=(number, window, 1), dtype=int)  	# initilize the sub_activity matrix for intervals

    # preparing the image
    img = np.zeros((th*number,window+name_window,3), np.uint8)+255		# initializing the image	
    img[:,name_window-5:name_window,:] = np.zeros((th*number,5,3), np.uint8)

    # writing on the image
    counter = 0
    for i in range(len(activities_names)):
	cv2.putText(img,activities_names[i],(10,(th*(counter+1))-5), cv2.FONT_HERSHEY_SIMPLEX, .5,(0,0,0),1)
	counter = counter+1

    A1 = 0
    while not rospy.is_shutdown():

	# if A1 dont change then no need to do all the calculation !
	if A1 != QSR_msg:
		A1 = QSR_msg
		G1 = graph_maker(A1.o1,A1.o2,A1.spatial,A1.temporal,A1.objects,False)

		results = []
		for i in range(len(Activities)):
			flag = 1
			G_copy = G1
			counter = 0
			nodes1 = Activities[int(i)].nodes()
			nodes2 = G_copy.nodes()
			obj_nodes1 = []
			obj_nodes2 = []
			obj_nodes1 = np.append(obj_nodes1,[n for n in list(nodes1) if Activities[int(i)].node[n]['type2']=='object'])
			obj_nodes2 = np.append(obj_nodes2,[n for n in list(nodes2) if G_copy.node[n]['type2']=='object'])
			obj_exist = []
			for n in obj_nodes1:
				obj_exist = np.append(obj_exist, np.where(obj_nodes2==n))
			#print len(obj_exist),len(obj_nodes1)
			print i
			#print Activities[int(i)].node[n]['type2']=='temporal'
			if len(obj_exist)==len(obj_nodes1):
			    while flag==1:
				GM = iso.GraphMatcher(G_copy,Activities[int(i)],node_match=nm,edge_match=em)
				if GM.subgraph_is_isomorphic():
					counter +=1
				used_nodes1 = GM.mapping
				if used_nodes1 != {}:
					#print list(used_nodes1)
					#print [n for n in list(used_nodes1) if G_copy.node[n]['type2']=='temporal']
					used_nodes2 = []
					used_nodes2 = np.append(used_nodes2, [n for n in list(used_nodes1) if G_copy.node[n]['type2']=='temporal'])
					G_copy.remove_nodes_from(used_nodes2)	# remove temporal nodes from the graph
				else:
		 			flag = 0
			 		results = np.append(results,counter)

			else:
		 		flag = 0
				results = np.append(results,counter)
			#print i

    	subA[:,0:window-1,:] = subA[:,1:window,:]
	subA_vector[:,0:window-1] = subA_vector[:,1:window]

	counter = 0
	for i1 in results:
	    if i1>0:
		subA[th*counter:th*(counter+1),window-1,:] = [255,0,0]
		subA_vector[counter,window-1] = 1
	    else:
		subA[th*counter:th*(counter+1),window-1,:] = [255,255,255]
		subA_vector[counter,window-1] = 0
	    counter += 1


	# If you ever needed to do the interval,
	# 1 find sub_interval
	# 2 find the first positive number because thats where the first pick is
	"""
	subA_interval = subA[th,:,2]-subA[0,:,2]
	index_pk = list(np.where(subA_interval==255))
	index_pc = np.where(subA_interval==-255)
	if list(index_pk[0]) !=[]:
		I_pk = list(index_pk[0])[0]
		for j1 in range(len(list(index_pk[0]))-1):
		    if list(index_pk[0])[j1+1]-list(index_pk[0])[j1] > 1:
			I_pk = np.append(I_pk,list(index_pk[0])[j1+1])

	if list(index_pc[0]) !=[]:
		I_pc = list(index_pc[0])[0]
		for j1 in range(len(list(index_pc[0]))-1):
		    if list(index_pc[0])[j1+1]-list(index_pc[0])[j1] > 1:
			I_pc = np.append(I_pc,list(index_pc[0])[j1+1])
	"""
	counter_sub_acivities = np.zeros((number), np.uint8)
	for i1 in range(number):
	    index_pk = list(np.where(subA_vector[i1,:]==1))
	    if list(index_pk[0]) !=[]:
		counter_sub_acivities[i1] = 1
		for j1 in range(len(list(index_pk[0]))-1):
		    if list(index_pk[0])[j1+1]-list(index_pk[0])[j1] > 1:
			counter_sub_acivities[i1] += 1

	pub.publish(tuple(counter_sub_acivities))
    	img[:,name_window:window+name_window,:] = subA

        r.sleep()
    	cv2.imshow('sub activities',img)		
	if cv2.waitKey(1) & 0xFF == 27:
            	break 
    def get_value(self):
        # comment tekens moeten weg wnn het op pi gaat runnen
        stream = io.BytesIO()
        self.camera.capture(stream, format='jpeg')
        image = np.fromstring(stream.getvalue(), dtype=np.uint8)
        center, figures = image_processing.get_figures_data(image)
        self.message('Figures: %s' % figures)
#        _, figures = image_processing.get_figures_image(image)

        if (len(figures) < 3):
            print "found less than three figures"
            return None                                                                                                                                                                                  
        img_graph = self.build_graph_image(figures)
        if img_graph is None:
            print "IMG GRAPH IS NONE"
            return None
        nm = iso.categorical_node_match('fig', None)
        GM = iso.GraphMatcher(self.grid_graph,img_graph, node_match = nm)
        best_match = 0
        list_of_best_matches = []
        number_of_isomorphisms = 0
        for mapping_i in GM.subgraph_isomorphisms_iter():
            number_of_isomorphisms += 1
            if number_of_isomorphisms == 10:
                print "more than 10 color isomorphisms"
                return None
            score_mapping_i = 0
#             print mapping_i
            for j in mapping_i.keys():
#                 print self.grid_graph.node[j]['fig']
#                 print img_graph.node[mapping_i[j]]['fig']
                if self.grid_graph.node[j]['fig'].shape == img_graph.node[mapping_i[j]]['fig'].shape:
                    score_mapping_i += 1
#                     print "+1"
            if score_mapping_i == best_match:
#                 print 
                list_of_best_matches.append(mapping_i)
            elif score_mapping_i > best_match:
                list_of_best_matches = []
                list_of_best_matches.append(mapping_i)
                best_match = score_mapping_i 
        print list_of_best_matches
        if len(list_of_best_matches)  == 0:
            print "FOUT BIJ KLEURHERKENNING !!! (NAKIJKEN)"
            return None
        if len(list_of_best_matches) > 1:
            print "meerdere mogelijke matches gevonden, we returnen None"
            return None
        


        inv_map = {v:k for k, v in list_of_best_matches[0].items()}
#         print "INVMAP"
#         print inv_map
            
        # ORIENTATION GEBEURD NU VIA MATRIX !!
#         coordinates_img_fig1 = img_graph.node[0]['fig'].get_coordinate()
#         coordinates_img_fig2 = img_graph.node[1]['fig'].get_coordinate()
#         vector_in_img = (coordinates_img_fig2[0]-coordinates_img_fig1[0],coordinates_img_fig2[1]-coordinates_img_fig1[1])
#         coordinates_grid_fig1 = self.grid_graph.node[inv_map[0]]['fig'].get_coordinate()
#         coordinates_grid_fig2 = self.grid_graph.node[inv_map[1]]['fig'].get_coordinate()
#         vector_in_grid = (coordinates_grid_fig2[0]-coordinates_grid_fig1[0],coordinates_grid_fig2[1]-coordinates_grid_fig1[1])
#         turn_to_right = get_angle(vector_in_grid,vector_in_img)
          
#         #TODO uitleg
#         orientation = (turn_to_right + math.pi*3/2) % 2*math.pi
                
        # VANAF HIER IS ALLES VOOR LEAST-SQUARES
        w = inv_map.keys()[0]
        x = img_graph.node[w]['fig'].get_coordinate()
        x_reference = np.array((x[0],x[1]))
        x_rel = np.zeros_like((2,1))
    
        x_coordinate = inv_map[w] % 12
        y_coordinate = math.floor(inv_map[w]/12)
        x1 = x_coordinate*length + (y_coordinate % 2)*length/2
        y1 = y_coordinate*height
        b_reference = np.array((x1,y1)) 
        b_rel = np.zeros_like((2,1))
        i = 1
        
        print "b4 while, invmap"
        print inv_map
        print "imggraph" 
        print img_graph.nodes()
        
        for i in inv_map.keys():
#        while i < len(inv_map.keys()):
            
#             print img_graph.node[i]['fig']
            x = img_graph.node[i]['fig'].get_coordinate()
            x = np.array((x[0],x[1]))
            x_rel = np.column_stack((x_rel,x-x_reference))
            x_coordinate = inv_map[i] % 12
            y_coordinate = math.floor(inv_map[i]/12)
            x1 = x_coordinate*length + (y_coordinate % 2)*length/2
            y1 = y_coordinate*height
            b = np.array((x1,y1))
            b_rel = np.column_stack((b_rel,b-b_reference))
#             i+=1
#         print x_rel
#         print b_rel
        at = np.linalg.lstsq(np.transpose(x_rel), np.transpose(b_rel))[0]
        a = np.transpose(at)

    
        # TODO 
        # center = (image.shape[1]/2, image.shape[0]/2)
        location = np.dot(a,center-x_reference)+b_reference
        alpha = math.atan(a[1][0]/a[0][0])
        s = math.sqrt(a[0][0]**2 + a[1][0]**2)
        if not math.copysign(1, math.cos(alpha)*s) == math.copysign(1, a[0][0]):
            alpha = alpha-math.pi
        orientation = (1.5*math.pi-(2*math.pi+alpha)) % (2*math.pi)
        print orientation*180/math.pi
        loc_and_or = {'location': location, 'orientation': orientation}
        print loc_and_or
        return loc_and_or
Пример #48
0
def get_isomorphic_subgraph_mapping(G1, G2):
    """Returns a dictionary mapping one graph onto another if one graph is a 
    subgraph of the other"""
    Gm = iso.GraphMatcher(G1,G2,node_match=iso.categorical_node_match(['Element'],['C']))
    Gm.is_isomorphic()
    return Gm.mapping
Пример #49
0
def test_categorical_node_match():
    nm = iso.categorical_node_match(['x', 'y', 'z'], [None]*3)
    assert_true(nm(dict(x=1, y=2, z=3), dict(x=1, y=2, z=3)))
    assert_true(not nm(dict(x=1, y=2, z=2), dict(x=1, y=2, z=1)))