def test_weightkey():
    g1 = nx.DiGraph()
    g2 = nx.DiGraph()

    g1.add_edge('A','B', weight=1)
    g2.add_edge('C','D', weight=0)

    assert_true(  nx.is_isomorphic(g1, g2) )
    em = iso.numerical_edge_match('nonexistent attribute', 1)
    assert_true(  nx.is_isomorphic(g1, g2, edge_match=em) )
    em = iso.numerical_edge_match('weight', 1)
    assert_false( nx.is_isomorphic(g1, g2, edge_match=em) )

    g2 = nx.DiGraph()
    g2.add_edge('C','D')
    assert_true( nx.is_isomorphic(g1, g2, edge_match=em) )
    def build(self):
        g1 = self.g1
        g2 = self.g2

        # We will assume integer weights only.
        g1.add_edge('A', 'B', color='green', weight=0, size=.5)
        g1.add_edge('A', 'B', color='red', weight=1, size=.35)
        g1.add_edge('A', 'B', color='red', weight=2, size=.65)

        g2.add_edge('C', 'D', color='green', weight=1, size=.5)
        g2.add_edge('C', 'D', color='red', weight=0, size=.45)
        g2.add_edge('C', 'D', color='red', weight=2, size=.65)

        if g1.is_multigraph():
            self.em = iso.numerical_multiedge_match('weight', 1)
            self.emc = iso.categorical_multiedge_match('color', '')
            self.emcm = iso.categorical_multiedge_match(['color', 'weight'], ['', 1])
            self.emg1 = iso.generic_multiedge_match('color', 'red', eq)
            self.emg2 = iso.generic_multiedge_match(['color', 'weight', 'size'], ['red', 1, .5], [eq, eq, iso.matchhelpers.close])
        else:
            self.em = iso.numerical_edge_match('weight', 1)
            self.emc = iso.categorical_edge_match('color', '')
            self.emcm = iso.categorical_edge_match(['color', 'weight'], ['', 1])
            self.emg1 = iso.generic_multiedge_match('color', 'red', eq)
            self.emg2 = iso.generic_edge_match(['color', 'weight', 'size'], ['red', 1, .5], [eq, eq, iso.matchhelpers.close])
Exemple #3
0
    def test_graphml(self):
        output = convert(
            'graph', self.test_input['distances'], {'format': 'graphml'})
        expected_edges = set(self.test_input['distances']['data'].edges(
            data='distance'))
        actual_edges = set()

        self.assertIsInstance(output['data'], (str, unicode))
        tree = etree.fromstring(output['data'])
        self.assertEqual(len(tree), 2)
        self.assertEqual(tree[0].tag, self.GRAPHML_NS + 'key')
        self.assertEqual(tree[1].tag, self.GRAPHML_NS + 'graph')

        for edge in tree[1].findall(self.GRAPHML_NS + 'edge'):
            edge = (edge.attrib['source'],
                    edge.attrib['target'],
                    int(edge.find(self.GRAPHML_NS + 'data').text))

            self.assertNotIn(edge, actual_edges)
            actual_edges.add(edge)

        self.assertEqual(expected_edges, actual_edges)

        output = convert(
            'graph', output, {'format': 'networkx'})

        self.assertTrue(
            is_isomorphic(output['data'],
                          self.test_input['distances']['data'],
                          edge_match=numerical_edge_match('distance', 1)))
Exemple #4
0
def get_frequency(G_q, train_g_path):
    """
    # Projecting a Query Graph to BoFG histogram
    """
    train_lst = fn.get_file_list(train_g_path, ".g")
    freq_lst = []
    for g_tr in train_lst:
        G_tr = nx.read_gpickle(train_g_path + g_tr)
        # Count the frequency of each G_tr in G_q
        # Check that Node labels of G_tr belongs to that of G_q
        with open(train_g_path + g_tr[:-2] + ".nodelabel", "r") as nl:
            G_tr_nlabels = json.load(nl)
        G_q_nlabels = [int(n_tup[1]["label"]) for n_tup in G_q.nodes(data=True)]
        if fn.is_subset(G_tr_nlabels, G_q_nlabels):
            # print G_tr_nlabels, G_tr.edges(data=True)
            nm = iso.numerical_node_match("label", 1)
            em = iso.numerical_edge_match("weight", 0)
            GM = iso.GraphMatcher(G_q, G_tr, node_match=nm, edge_match=em)

            frequency = len(list(GM.subgraph_isomorphisms_iter()))
            if frequency > 0:
                BoFG_ID = int(g_tr[-5:-2])
                freq_lst.append((BoFG_ID, frequency))

    return freq_lst
Exemple #5
0
def check_isomorphism(json_1, json_2):
    g1 = json.loads(json_1)
    g2 = json.loads(json_2)

    try:
        nodes_1 = [(i['id'], {'type': i['type']}) for i in g1['nodes']]
        edges_1 = [(i['from'],i['to'], {'type': i['type']}) for i in g1['edges']]

        nodes_2 = [(i['id'], {'type': i['type']}) for i in g2['nodes']]
        edges_2 = [(i['from'],i['to'], {'type': i['type']}) for i in g2['edges']]
    except KeyError:
        return g1 == g2  # if graph isomorphism check is not possible, fall back to simple json-level equality check

    graph_1 = nx.Graph()
    graph_1.add_nodes_from(nodes_1)
    graph_1.add_edges_from(edges_1)

    graph_2 = nx.Graph()
    graph_2.add_nodes_from(nodes_2)
    graph_2.add_edges_from(edges_2)

    nm = iso.numerical_node_match('type',-1)
    em = iso.numerical_edge_match('type',-1)

    return nx.is_isomorphic(graph_1, graph_2, node_match=nm, edge_match=em)
Exemple #6
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
Exemple #7
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)
Exemple #8
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', ''))
    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)
Exemple #10
0
 def __fit_graph(self, model):
     if self.get_bin_step() != 0:
         gm = iso.GraphMatcher(self._PharmacophoreBase__g,
                               model,
                               node_match=self.__nm,
                               edge_match=self.__em)
     else:
         gm = iso.GraphMatcher(self._PharmacophoreBase__g,
                               model,
                               node_match=self.__nm,
                               edge_match=iso.numerical_edge_match(
                                   'dist', 0, atol=0.75))
     return gm
 def test_find_edges_in_file_different_weight(self):
     with mock.patch('graph.open') as m:
         with mock.patch("sample.count_import") as s:
             s.return_value = 2
             m.return_value = io.StringIO("import sample \n from agh")
             gg = networkx.DiGraph()
             g.find_edges_in_file("node.py", gg, "/")
             em = iso.numerical_edge_match('weight', 1)
             # equality of graph
             self.assertFalse(
                 networkx.is_isomorphic(gg,
                                        self.get_expected_graph(),
                                        edge_match=em))
    def test_back_and_forth(self):
        ncsv, ecsv = self.tmp_root + "test_node_csv", self.tmp_root + "test_edges_csv"

        parser.networkx_to_csv(self.G, ncsv, ecsv)
        H = parser.csv_to_networkx(ncsv, ecsv)

        print(self.G.nodes())
        print(H.nodes())
        print(self.G.edges(), H.edges())

        #Test isomorphism
        em = iso.numerical_edge_match('weight', 1)
        self.assertTrue(nx.is_isomorphic(self.G, H, edge_match=em))
Exemple #13
0
    def test_cmdline_back_and_forth(self):
        pickle.dump(self.G, open("test_out.nx", 'wb'))

        su.check_call([
            "lntk-nx_to_csv", "test_out.nx", "test_nodes_csv", "test_edges_csv"
        ])

        su.check_call([
            "lntk-csv_to_nx", "test_nodes_csv", "test_edges_csv", "test_out.nx"
        ])
        H = pickle.load(open("test_out.nx", 'rb'))

        em = iso.numerical_edge_match('weight', 1)
        self.assertTrue(nx.is_isomorphic(self.G, H, edge_match=em))
Exemple #14
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
Exemple #15
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
def test_simple():
    # 16 simple tests
    w = 'weight'
    edges = [(0, 0, 1), (0, 0, 1.5), (0, 1, 2), (1, 0, 3)]
    for g1 in [
            nx.Graph(),
            nx.DiGraph(),
            nx.MultiGraph(),
            nx.MultiDiGraph(),
    ]:

        g1.add_weighted_edges_from(edges)
        g2 = g1.subgraph(g1.nodes())
        if g1.is_multigraph():
            em = iso.numerical_multiedge_match('weight', 1)
        else:
            em = iso.numerical_edge_match('weight', 1)
        assert_true(nx.is_isomorphic(g1, g2, edge_match=em))

        for mod1, mod2 in [(False, True), (True, False), (True, True)]:
            # mod1 tests a regular edge
            # mod2 tests a selfloop
            if g2.is_multigraph():
                if mod1:
                    data1 = {0: {'weight': 10}}
                if mod2:
                    data2 = {0: {'weight': 1}, 1: {'weight': 2.5}}
            else:
                if mod1:
                    data1 = {'weight': 10}
                if mod2:
                    data2 = {'weight': 2.5}

            g2 = g1.subgraph(g1.nodes()).copy()
            if mod1:
                if not g1.is_directed():
                    g2._adj[1][0] = data1
                    g2._adj[0][1] = data1
                else:
                    g2._succ[1][0] = data1
                    g2._pred[0][1] = data1
            if mod2:
                if not g1.is_directed():
                    g2._adj[0][0] = data2
                else:
                    g2._succ[0][0] = data2
                    g2._pred[0][0] = data2

            assert_false(nx.is_isomorphic(g1, g2, edge_match=em))
Exemple #17
0
def test_simple():
    # 16 simple tests
    w = 'weight'
    edges = [(0, 0, 1), (0, 0, 1.5), (0, 1, 2), (1, 0, 3)]
    for g1 in [nx.Graph(),
               nx.DiGraph(),
               nx.MultiGraph(),
               nx.MultiDiGraph(),
               ]:

        g1.add_weighted_edges_from(edges)
        g2 = g1.subgraph(g1.nodes())
        if g1.is_multigraph():
            em = iso.numerical_multiedge_match('weight', 1)
        else:
            em = iso.numerical_edge_match('weight', 1)
        assert_true( nx.is_isomorphic(g1, g2, edge_match=em) )

        for mod1, mod2 in [(False, True), (True, False), (True, True)]:
            # mod1 tests a regular edge
            # mod2 tests a selfloop
            if g2.is_multigraph():
                if mod1:
                    data1 = {0: {'weight': 10}}
                if mod2:
                    data2 = {0: {'weight': 1}, 1: {'weight': 2.5}}
            else:
                if mod1:
                    data1 = {'weight': 10}
                if mod2:
                    data2 = {'weight': 2.5}

            g2 = g1.subgraph(g1.nodes()).copy()
            if mod1:
                if not g1.is_directed():
                    g2._adj[1][0] = data1
                    g2._adj[0][1] = data1
                else:
                    g2._succ[1][0] = data1
                    g2._pred[0][1] = data1
            if mod2:
                if not g1.is_directed():
                    g2._adj[0][0] = data2
                else:
                    g2._succ[0][0] = data2
                    g2._pred[0][0] = data2

            assert_false(nx.is_isomorphic(g1, g2, edge_match=em))
Exemple #18
0
def create_fvl(glist, flist):
    fva = np.zeros((len(glist), len(flist)))
    i = 0
    nm = iso.categorical_node_match('elem', 'C')
    em = iso.numerical_edge_match('weight', 1)

    for mol in glist:
        # print(i)
        j = 0
        for feature in flist:
            GM = iso.GraphMatcher(mol, feature, node_match=nm, edge_match=em)
            if GM.subgraph_is_isomorphic():
                fva[i][j] = 1
            j += 1
        i += 1
    return fva
Exemple #19
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}
Exemple #20
0
    def _matcher_factory(self, graph_component, value_type):
        factory_dict = dict(node=dict(), edge=dict())

        # TODO Is this dangerous?
        numerical_default = 0.
        categorical_default = None

        factory_dict['node']['categorical'] = iso.categorical_node_match(
            self.label, categorical_default)
        factory_dict['node']['numerical'] = iso.numerical_node_match(
            self.label, numerical_default)
        factory_dict['edge']['categorical'] = iso.categorical_edge_match(
            self.label, categorical_default)
        factory_dict['edge']['numerical'] = iso.numerical_edge_match(
            self.label, numerical_default)

        return factory_dict[graph_component][value_type]
Exemple #21
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
Exemple #22
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}
Exemple #23
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
Exemple #24
0
 def _printmoleculename(self):
     mname = []
     d = defaultdict(list)
     em = iso.numerical_edge_match(['atom', 'level'], ["None", 1])
     with WriteBuffer(open(self.moleculefilename, 'w'),
                      sep='\n') as fm, open(self.moleculetemp2filename,
                                            'rb') as ft:
         for line in itertools.zip_longest(*[ft] * 3):
             atoms, bonds = self._getatomsandbonds(line)
             molecule = self._molecule(self, atoms, bonds)
             for isomer in d[str(molecule)]:
                 if isomer.isomorphic(molecule, em):
                     molecule.smiles = isomer.smiles
                     break
             else:
                 d[str(molecule)].append(molecule)
             mname.append(molecule.smiles)
             fm.append(
                 listtostirng((molecule.smiles, atoms, bonds),
                              sep=(' ', ';', ',')))
     self.mname = np.array(mname)
Exemple #25
0
def reactant_indices(R1, R2, P, broken_bond):
    """Match the indices of a pair of reactants from a
     product and broken bond.

    Parameters
    ----------
    R1 : networkx MultiGraph
        Graph representing reactant 1
    R2 : networkx MultiGraph
        Graph representing reactant 2
    P : networkx MultiGraph
        Graph representing the product
    broken_bond : list (2,)
        Indices representing the edge of the product
        to be removed.

    Returns
    -------
    pindex: ndarrays (n,)
        Indices of the product graph sorted by the order of
        the reactants indices.
    """
    GM = nx.algorithms.isomorphism.GraphMatcher
    em = iso.numerical_edge_match('bonds', 1)
    nm = iso.numerical_node_match('number', 1)

    Pgraph = P.copy()
    u, v = broken_bond
    Pgraph.graph.remove_edge(u, v)
    Rgraph = R1 + R2

    gm = GM(Pgraph.graph, Rgraph.graph, edge_match=em, node_match=nm)

    gm.is_isomorphic()

    pindex = np.empty(len(Pgraph), dtype=int)
    for k, v in gm.mapping.items():
        pindex[k] = v

    return pindex
 def _handlespecies(self, name):
     showname = {}
     if self.species == {}:
         species_out = dict([(x, {}) for x in (name if len(
             name) <= self.maxspecies else name[0:self.maxspecies])])
     else:
         species_out = {}
         b = True
         for spec in self.species.items():
             specname, value = spec
             if "structure" in value:
                 atoms, bonds = value["structure"]
                 G1 = self._convertstructure(atoms, bonds)
                 if b:
                     structures = self._readstrcture()
                     em = iso.numerical_edge_match(
                         ['atom', 'level'], ["None", 1])
                     b = False
                 i = 1
                 while (specname+"_"+str(i) if i > 1 else specname) in structures:
                     G2 = self._convertstructure(structures[(
                         specname+"_"+str(i) if i > 1 else specname)][0], structures[(specname+"_"+str(i) if i > 1 else specname)][1])
                     if nx.is_isomorphic(G1, G2, em):
                         if i > 1:
                             specname += "_"+str(i)
                         break
                     i += 1
             species_out[specname] = {}
             if "showname" in value:
                 showname[specname] = value["showname"]
     if self.showid:
         if species_out:
             self._logging()
             self._logging("Species are:")
             for n, (specname, value) in enumerate(species_out.items(), start=1):
                 showname[specname] = str(n)
                 print(n, specname)
     return species_out, showname
Exemple #27
0
    def _get_subgraph_N_X_N(self, graph1, graph2, name1, name2):
        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"
                    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
 def _printmoleculename(self):
     mname = []
     d = {}
     em = iso.numerical_edge_match(['atom', 'level'], ["None", 1])
     with open(self.moleculefilename, 'w') as fm, open(self.moleculetemp2filename, 'rb') as ft, open(self.moleculestructurefilename, 'w') as fs:
         for line in ft:
             s = self._decompress(line).split()
             atoms = np.array([int(x) for x in s[0].split(",")])
             bonds = np.array([tuple(int(y) for y in x.split(","))
                               for x in s[1].split(";")] if len(s) == 3 else [])
             typenumber = np.zeros(len(self.atomname), dtype=np.int)
             atomtypes = []
             for atomnumber in atoms:
                 typenumber[self._atomtype[atomnumber-1]-1] += 1
                 atomtypes.append(
                     (atomnumber, self._atomtype[atomnumber-1]))
             G = self._makemoleculegraph(atomtypes, bonds)
             name = "".join([self.atomname[i]+(str(typenumber[i] if typenumber[i] > 1 else ""))
                             if typenumber[i] > 0 else "" for i in range(0, len(self.atomname))])
             if name in d:
                 for j in range(len(d[name])):
                     if nx.is_isomorphic(G, d[name][j], em):
                         if j > 0:
                             name += "_"+str(j+1)
                         break
                 else:
                     d[name].append(G)
                     name += "_"+str(len(d[name]))
                     print(self._getstructure(name, atoms, bonds), file=fs)
             else:
                 d[name] = [G]
                 print(self._getstructure(name, atoms, bonds), file=fs)
             mname.append(name)
             print(name, ",".join([str(x) for x in atoms]), ";".join(
                 [",".join([str(y) for y in x]) for x in bonds]), file=fm)
     self._mname = mname
 def __setstate__(self, state):
     self.__dict__.update(state)
     self.__nm = iso.categorical_node_match('label', '_')
     self.__em = iso.numerical_edge_match('dist', 0)
 def __init__(self, bin_step=1, cached=False):
     super().__init__(bin_step, cached)
     self.__nm = iso.categorical_node_match('label', '_')
     self.__em = iso.numerical_edge_match('dist', 0)
Exemple #31
0
            G_q.add_edge( v1, v2, weight=order_dist )


    
"""
# Projecting a Query Graph to BoFG histogram
"""
train_path = 'train/model_1/graph/'
train_lst = fn.get_file_list( train_path, '.g' )
for g_tr in train_lst:
    G_tr = nx.read_gpickle( train_path + g_tr )
    # Count the frequency of each G_tr in G_q
    # Check that Node labels of G_tr belongs to that of G_q
    with open( train_path + g_tr[:-2] + '.nodelabel', 'r') as nl:
        G_tr_nlabels = json.load( nl )
    G_q_nlabels = [ int(n_tup[1]['label']) for n_tup in G_q.nodes(data=True)]
    if fn.is_subset( G_tr_nlabels, G_q_nlabels ):
        # print G_tr_nlabels, G_tr.edges(data=True)
        nm = iso.numerical_node_match('label', 1)
        em = iso.numerical_edge_match('weight', 0)
        GM = iso.GraphMatcher( G_q, G_tr, node_match=nm, edge_match=em )
#==============================================================================
#         for subgraph in GM.subgraph_isomorphisms_iter():
#             print subgraph
#==============================================================================
        if len(list(GM.subgraph_isomorphisms_iter())) > 0:
            BoFG_ID = int( g_tr[-5:-2] )
            

    
Exemple #32
0
 def __eq__(self, other):
     return nx.is_isomorphic(self._Graph,
                             other._Graph,
                             edge_match=numerical_edge_match("weight", 1))
def main():
    """ Main func inicial"""
    numberOfCircuits = 100  # numero de arquivos rcirucit0,rcircuit1 ...
    maxElements = 200  # numero maximo de elementos dentro de cada circuito
    maxCM = 0

    criarCircuitos = 0
    if criarCircuitos == 1:
        os.chdir(
            'C:\\Users\\evand\\Documents\\teste pfc\\netlists\\script\\teste_CM0\\experimento'
            + str(numberOfCircuits) + '_' + str(maxElements) + '_' +
            str(maxCM))
        os.system('create_netlists.py --file ' + str(numberOfCircuits) +
                  ' --max_elements ' + str(maxElements) + ' --max_CM ' +
                  str(maxCM))

    #caminho dos circuitos
    os.chdir('C:\\Users\\evand\\Documents\\teste pfc')
    pathC = 'C:/Users/evand/Documents/teste pfc/netlists/script/teste_CM0/experimento' + str(
        numberOfCircuits) + '_' + str(maxElements) + '_' + str(
            maxCM) + '/circuits/'

    #arquivo de simplificações de circuito
    list_simpl = []
    for i in range(1, 5):
        list_simpl.append('netlists/archSimpl/simplifica' + str(i) + '.sp')

    list_arq = []
    for i in range(1, 6):
        list_arq.append('netlists/script/experimento1_evandro/CM_circuits/cm' +
                        str(i) + '.sp')

#        ['netlists/script/CM_circuits/cm0.sp','netlists/script/CM_circuits/cm1.sp','netlists/script/CM_circuits/cm2.sp',
#              'netlists/script/CM_circuits/cm3.sp','netlists/script/CM_circuits/cm4.sp','netlists/script/CM_circuits/cm5.sp',
#              'netlists/script/CM_circuits/cm6.sp','netlists/script/CM_circuits/cm7.sp','netlists/script/CM_circuits/cm8.sp',
#              'netlists/script/CM_circuits/cm9.sp','netlists/script/CM_circuits/cm10.sp','netlists/script/CM_circuits/cm10.sp']
#

#carrega arquiteturas para simplificação de circuitos (associação de resistores e capacitores)
    archSimpl_list = []

    for arq in list_simpl:
        archSimpl_list = read_arch(arq, archSimpl_list)

    #carrega arquiteturas espelhos de corrente
    arch_list = []

    for arq in list_arq:
        arch_list = read_arch(arq, arch_list)

    #carrega circuito
    listaMatchCircs = []
    listaMatchCircsReal = []
    tableOfResults = []
    totalArchitectures = 0
    numberOfCorrectsArch = np.zeros(numberOfCircuits)
    contadorArchCM = 0
    #T_netlist,C_netlist,R_netlist = read_netlist(open('netlists/script/circuits/rcircuit0teste2.sp').readlines())
    #T_netlist,C_netlist,R_netlist = read_netlist(open('netlists/script/teste/simplifica/rcircuit0.sp').readlines())

    for circ in range(0, 130):
        T_netlist, C_netlist, R_netlist = read_netlist(
            open(pathC + 'rcircuit' + str(circ) + '.sp').readlines())
        arch_in_circ = read_log(
            open(pathC + 'rcircuit' + str(circ) + '.log').readlines())

        #cria grafo do circuito sem peso
        #graph = create_graph(T_netlist,R_netlist,C_netlist, False)

        #cria grafo do circuito com pesos
        graph = create_graph(T_netlist, R_netlist, C_netlist, True, False)

        #nx.draw(graph, with_labels=True, node_size=10, font_size = 6,figsize=(400,400))
        #nx.draw_spectral(graph, with_labels=True, node_size=10, font_size = 6)
        #nx.draw_spring(graph, with_labels=True, node_size=10, font_size = 8)
        #nx.draw_circular(graph, with_labels=True)

        #realiza passagens pelo circuitos para identificar e realizar possíveis simplificações
        sair = 0
        nCS = 0  #numero de Capacitores em série
        nCP = 0  #numero de Capacitores em paralelo
        nRS = 0  #numero de Resistores em série
        nRP = 0  #numero de Resistores em paralelo

        while sair == 0:
            sair = 1  # se ele fizer qualquer simplificação ele muda este flag para 0 e verifica novamente
            cont_archSimpl = -1
            for arch in archSimpl_list:
                cont_archSimpl = cont_archSimpl + 1
                graph_arch = create_graph(arch[0], arch[2], arch[1], True,
                                          False)
                em = iso.numerical_edge_match(
                    ['weight', 'weight', 'weight', 'weight', 'weight'],
                    [1, 2, 3, 4, 5])
                nm = iso.categorical_node_match(['type', 'type'], ['C', 'R'])
                GM = iso.GraphMatcher(graph,
                                      graph_arch,
                                      edge_match=em,
                                      node_match=nm)
                II = GM.subgraph_is_isomorphic()

                print('simplificação: ', cont_archSimpl + 1,
                      II)  #+1 porque as arquiteturas começam em 1 e não zero

                # if II: #apenas para visualização
                #     if plotar == 1:
                #         for subgraph in GM.subgraph_isomorphisms_iter():
                #             print(subgraph)
                #             plot_graph(graph.subgraph(subgraph.keys()))

                lista_subgraph = []
                for subgraph in GM.subgraph_isomorphisms_iter():
                    lista_subgraph.append(subgraph)

                #verifica condições extras para simplificação
                #  - capacitores e resistores em série não podem ter mais que duas arestas no nó central entre eles

                if list_espec_simpl[
                        cont_archSimpl] == 'CS':  #para capacitores em série
                    for subgraph in lista_subgraph:

                        #busca estrutura no grafo do circuito
                        NA = list(subgraph.keys())[list(
                            subgraph.values()).index('NA')]
                        NB = list(subgraph.keys())[list(
                            subgraph.values()).index('NB')]
                        NC = list(subgraph.keys())[list(
                            subgraph.values()).index('NC')]
                        NE1 = list(subgraph.keys())[list(
                            subgraph.values()).index(
                                'C1')]  #nó elemento (pode ser C ou R)
                        NE2 = list(subgraph.keys())[list(
                            subgraph.values()).index(
                                'C2')]  #nó elemento (pode ser C ou R)
                        #verifica número de conexões no nó central dos capcitores e se o nó existe (se já não foi simplificado)
                        if (graph.has_node(NE1)) and (
                                graph.has_node(NE2)
                        ):  # existem os nós (não foram simplificados ainda)
                            if (len(graph.edges(NB)) == 2):  #pode simplificar
                                nCS = nCS + 1
                                graph = simplificar(graph, NA, NB, NC, NE1,
                                                    NE2, 'CS')
                                sair = 0
                            #else:
                            #graph.nodes[NB]['valsub']='NNV'  # indica se o nó é valido para comparação de isomorphismo (NNV = nó Não valido para subgrafo - tem mais de duas conexções no nó intermediário)

                if list_espec_simpl[
                        cont_archSimpl] == 'RS':  #para resistores em série
                    for subgraph in lista_subgraph:
                        #busca estrutura no grafo do circuito
                        NA = list(subgraph.keys())[list(
                            subgraph.values()).index('NA')]
                        NB = list(subgraph.keys())[list(
                            subgraph.values()).index('NB')]
                        NC = list(subgraph.keys())[list(
                            subgraph.values()).index('NC')]
                        NE1 = list(subgraph.keys())[list(
                            subgraph.values()).index(
                                'R1')]  #nó elemento (pode ser C ou R)
                        NE2 = list(subgraph.keys())[list(
                            subgraph.values()).index(
                                'R2')]  #nó elemento (pode ser C ou R)
                        #verifica número de conexões no nó central dos resistores e se o nó existe (se já não foi simplificado)
                        if (len(graph.edges(NB))
                                == 2) and (graph.has_node(NE1)) and (
                                    graph.has_node(NE2)):  #pode simplificar
                            nRS = nRS + 1
                            graph = simplificar(graph, NA, NB, NC, NE1, NE2,
                                                'RS')
                            sair = 0

                if list_espec_simpl[
                        cont_archSimpl] == 'CP':  #para capacitores em paralelo
                    #cont = 0
                    for subgraph in lista_subgraph:
                        # AUX DEBUG #######################
                        #if cont == 1:
                        #    print('break ',cont)
                        #    break
                        #print('cont ',cont)
                        #cont = cont + 1
                        #print(list(subgraph.keys())[list(subgraph.values()).index('C1')], list(subgraph.keys())[list(subgraph.values()).index('C2')], '\n')
                        #############################

                        #busca estrutura no grafo do circuito
                        NA = list(subgraph.keys())[list(
                            subgraph.values()).index('NA')]
                        NB = list(subgraph.keys())[list(
                            subgraph.values()).index('NB')]
                        NC = 'none'
                        NE1 = list(subgraph.keys())[list(
                            subgraph.values()).index(
                                'C1')]  #nó elemento (pode ser C ou R)
                        NE2 = list(subgraph.keys())[list(
                            subgraph.values()).index(
                                'C2')]  #nó elemento (pode ser C ou R)
                        #verifica se o nó existe (se já não foi simplificado)
                        if (graph.has_node(NE1)) and (
                                graph.has_node(NE2)):  #pode simplificar
                            nCP = nCP + 1
                            graph = simplificar(graph, NA, NB, NC, NE1, NE2,
                                                'CP')
                            sair = 0

                if list_espec_simpl[
                        cont_archSimpl] == 'RP':  #para resistores em paralelo
                    for subgraph in lista_subgraph:
                        #busca estrutura no grafo do circuito
                        NA = list(subgraph.keys())[list(
                            subgraph.values()).index('NA')]
                        NB = list(subgraph.keys())[list(
                            subgraph.values()).index('NB')]
                        NC = 'none'
                        NE1 = list(subgraph.keys())[list(
                            subgraph.values()).index(
                                'R1')]  #nó elemento (pode ser C ou R)
                        NE2 = list(subgraph.keys())[list(
                            subgraph.values()).index(
                                'R2')]  #nó elemento (pode ser C ou R)
                        #verifica se o nó existe (se já não foi simplificado)
                        if (graph.has_node(NE1)) and (
                                graph.has_node(NE2)):  #pode simplificar
                            nRP = nRP + 1
                            graph = simplificar(graph, NA, NB, NC, NE1, NE2,
                                                'RP')
                            sair = 0

        #cria grafo das arquiteturas
        cont_arch = -1
        listaMatch = []
        for arch in arch_list:
            cont_arch = cont_arch + 1
            #sem peso
            #graph_arch = create_graph(arch[0],arch[2],arch[1], False)
            #COm peso
            graph_arch = create_graph(arch[0], arch[2], arch[1], True, False)

            #para encontrar isomorfismo em grafo sem peso
            #GM = iso.GraphMatcher(graph,graph_arch)

            #em = iso.numerical_multiedge_match(['weight','weight','weight'], [1,2,3])
            em = iso.numerical_edge_match(
                ['weight', 'weight', 'weight', 'weight', 'weight'],
                [1, 2, 3, 4, 5])
            #em = iso.numerical_edge_match('weight', 2)
            GM = iso.GraphMatcher(graph, graph_arch, edge_match=em)
            II = GM.subgraph_is_isomorphic()
            #print(GM.is_isomorphic())
            print('match arquiteturas: ', cont_arch + 1,
                  II)  #+1 porque as arquiteturas começam em 1 e não zero

            #para teste
            if II:
                listaMatch.append(str(cont_arch + 1))
                contadorArchCM += 1
                for subgraph in GM.subgraph_isomorphisms_iter():
                    print(subgraph)
                    plot_graph(graph.subgraph(subgraph.keys()))

        # resultados acurácia
        print('nCS,nCP,nRS,nRP', nCS, nCP, nRS, nRP)
        listaMatchCircs.append(listaMatch)
        listaMatchCircsReal.append(arch_in_circ)
        #print('######### 3/4  3=tipoDaArquiteturaDoEspelhoDeCorrente / 4=asVezesQueEssarArquiteturaSeRepetiu')
        arch_in_circ_ordenadoSemRepeticao = list(
            dict.fromkeys(sorted(arch_in_circ)))
        arch_in_circ_contadorDeRepeticao = dict(
            (i, arch_in_circ.count(i)) for i in sorted(arch_in_circ))
        print(
            f'tipo : numeroDeRepetiçoes = {arch_in_circ_contadorDeRepeticao}')
        # print('listaMatch: ',listaMatch,type(listaMatch))
        # print('arch_in_circ: ',arch_in_circ,type(arch_in_circ))
        # numberOfCorrectsArch[circ] = list((Counter(listaMatch) & Counter(arch_in_circ)).elements())
        # acuraciaDoCircuito = numberOfCorrectsArch[circ]/len(arch_in_circ)

        a = set(listaMatch)
        b = set(arch_in_circ)
        numberOfCorrectsArch[circ] = len(a.intersection(b))
        totalArchitectures = totalArchitectures + len(b)
        if (len(b) == 0):
            b = set([0])
        acuraciaDoCircuito = len(a.intersection(b)) / len(b)
        x = '{} & {} & {} & {} & {} & {} & {} & {}\\'.format(
            circ + 1, maxElements, arch_in_circ_contadorDeRepeticao, nRP, nRS,
            nCP, nCS, contadorArchCM, "{:.2f}".format(acuraciaDoCircuito))
        tableOfResults.append(x)
        print(x)
        print('___________________________________')

    tableOfResults = np.array(tableOfResults)
    tableOfResults = tableOfResults[:, np.newaxis]
    print(tableOfResults)
    print('Acuracia total = ' +
          str(sum(numberOfCorrectsArch) / totalArchitectures))
def main():
    """ Main func """
    #caminho dos circuitos
    pathC = 'netlists/script/experimento1/circuits/' 
    
    
    
    #arquivo de simplificações de circuito
    list_simpl = []
    for i in range(1,5):
        list_simpl.append('netlists/archSimpl/simplifica' + str(i) + '.sp')
    #list_simpl. é uma variavel que recebe o caminho com as simplificações
    
    list_arq = []
    for i in range(1,6):
        list_arq.append('netlists/script/experimento1/CM_circuits/cm' + str(i) + '.sp')
        

        
#        ['netlists/script/CM_circuits/cm0.sp','netlists/script/CM_circuits/cm1.sp','netlists/script/CM_circuits/cm2.sp',
#              'netlists/script/CM_circuits/cm3.sp','netlists/script/CM_circuits/cm4.sp','netlists/script/CM_circuits/cm5.sp',
#              'netlists/script/CM_circuits/cm6.sp','netlists/script/CM_circuits/cm7.sp','netlists/script/CM_circuits/cm8.sp',
#              'netlists/script/CM_circuits/cm9.sp','netlists/script/CM_circuits/cm10.sp','netlists/script/CM_circuits/cm10.sp']
#    

#########################################################################
    #carrega arquiteturas para simplificação de circuitos (associação de resistores e capacitores)
    archSimpl_list = []
    for arq in list_simpl:  
        archSimpl_list = read_arch(arq,archSimpl_list)
# archSimpl_list recebe as arquiteturas dentro do caminho especificado(list_simpl), exemplo
# para a primeira posição deste vetor
# C1 (NA NB) C=1.0E-7
# C2 (NA NB) C=1.0E-7
#########################################################################
# carrega arquiteturas espelhos de corrente # que sao os cm1,cm2,...
    arch_list = []
    for arq in list_arq:
        arch_list = read_arch(arq,arch_list) # read_netlist está dentro da função read_arch
#exemplo da primeira posição do vetor:
# T73 ( net23 net23 0 0)  nfet  L=9.64E-6 W=1.12E-6
# T74 ( net1 net23 0 0)  nfet  L=9.64E-6 W=1.12E-6
# R75 ( net1 net22)  R=4.0E3
#########################################################################
        
    #carrega circuito
    listaMatchCircs = []
    listaMatchCircsReal = []
    contador = 0
    tot = 5# total 
    acc = np.zeros(5)
    #T_netlist,C_netlist,R_netlist = read_netlist(open('netlists/script/circuits/rcircuit0teste2.sp').readlines())
    #T_netlist,C_netlist,R_netlist = read_netlist(open('netlists/script/teste/simplifica/rcircuit0.sp').readlines())
    
    
    
    
    for circ in range(2,3):
        T_netlist,C_netlist,R_netlist = read_netlist(open(pathC + 'rcircuit' + str(circ) + '.sp').readlines())
        arch_in_circ = read_log(open(pathC + 'rcircuit' + str(circ) + '.log').readlines())
        
        
        #cria grafo do circuito sem peso
        #graph = create_graph(T_netlist,R_netlist,C_netlist, False)
    
        #Cria grafo do circuito com pesos
        graph = create_graph(T_netlist,R_netlist,C_netlist,True,False) 
    
        
        nx.draw(graph, with_labels=True, node_size=10, font_size = 6,figsize=(400,400)) 
        nx.draw_spectral(graph, with_labels=True, node_size=10, font_size = 6) 
        nx.draw_spring(graph, with_labels=True, node_size=10, font_size = 8)     
        nx.draw_circular(graph, with_labels=True) 



        # #realiza passagens pelo circuitos para identificar e realizar possíveis simplificações 
        sair = 0
        nCS = 0 #numero de Capacitores em série
        nCP = 0 #numero de Capacitores em paralelo
        nRS = 0 #numero de Resistores em série
        nRP = 0 #numero de Resistores em paralelo
  
######################################## SIMPLIFICAÇÃO ##########################################
#################################################################################################
      
        while sair == 0:
            sair = 1 # se ele fizer qualquer simplificação ele muda este flag para 0 e verifica novamente
            cont_archSimpl = -1
            for arch in archSimpl_list:
                cont_archSimpl=cont_archSimpl +1
                #cria um grafo da arquitetura que se quer simplificar para comparar por ismorfismo
                graph_arch = create_graph(arch[0],arch[2],arch[1],True,False)
                # em <- funcao customizada de edge_match
                em = iso.numerical_edge_match(['weight','weight','weight','weight','weight'], [1,2,3,4,5])
                # nm <- funcao customizada de node match
                nm = iso.categorical_node_match(['type', 'type'], ['C','R'])
                GM = iso.GraphMatcher(graph,graph_arch,edge_match=em,node_match=nm)
                II = GM.subgraph_is_isomorphic() # retorna TRUE or FALSE
                
              
                print('simplificacao: ',cont_archSimpl+1,II) #+1 porque as arquiteturas começam em 1 e não zero
                
                
                if II: #apenas para visualização 
                    #if plotar == 1:
                    for subgraph in GM.subgraph_isomorphisms_iter():
                        print(subgraph)
                        plot_graph(graph.subgraph(subgraph.keys()))
                            
                                        
                    
                lista_subgraph = []
                for subgraph in GM.subgraph_isomorphisms_iter(): 
                    lista_subgraph.append(subgraph)

                #verifica condições extras para simplificação
                #  - capacitores e resistores em série não podem ter mais que duas arestas no nó central entre eles
                
                if list_espec_simpl[cont_archSimpl] == 'CS': #para capacitores em série
                    for subgraph in lista_subgraph:
                     
                        #busca estrutura no grafo do circuito
                        NA = list(subgraph.keys())[list(subgraph.values()).index('NA')]
                        NB = list(subgraph.keys())[list(subgraph.values()).index('NB')]
                        NC = list(subgraph.keys())[list(subgraph.values()).index('NC')]
                        NE1 = list(subgraph.keys())[list(subgraph.values()).index('C1')] #nó elemento (pode ser C ou R)
                        NE2 = list(subgraph.keys())[list(subgraph.values()).index('C2')] #nó elemento (pode ser C ou R)
                        #verifica número de conexões no nó central dos capcitores e se o nó existe (se já não foi simplificado)
                        if (graph.has_node(NE1)) and (graph.has_node(NE2)): # existem os nós (não foram simplificados ainda)
                            if (len(graph.edges(NB))== 2): #pode simplificar
                                nCS = nCS + 1
                                graph = simplificar(graph,NA,NB,NC,NE1,NE2,'CS') # função de simplificação
                                sair = 0
                            #else:
                                #graph.node[NB]['valsub']='NNV'  # indica se o nó é valido para comparação de isomorphismo (NNV = nó Não valido para subgrafo - tem mais de duas conexções no nó intermediário)    

                if list_espec_simpl[cont_archSimpl] == 'RS': #para resistores em série
                    for subgraph in lista_subgraph:
                        #busca estrutura no grafo do circuito
                        NA = list(subgraph.keys())[list(subgraph.values()).index('NA')]
                        NB = list(subgraph.keys())[list(subgraph.values()).index('NB')]
                        NC = list(subgraph.keys())[list(subgraph.values()).index('NC')]
                        NE1 = list(subgraph.keys())[list(subgraph.values()).index('R1')] #nó elemento (pode ser C ou R)
                        NE2 = list(subgraph.keys())[list(subgraph.values()).index('R2')] #nó elemento (pode ser C ou R)
                        #verifica número de conexões no nó central dos resistores e se o nó existe (se já não foi simplificado)
                        if (len(graph.edges(NB))== 2) and (graph.has_node(NE1)) and (graph.has_node(NE2)): #pode simplificar
                            nRS = nRS + 1
                            graph = simplificar(graph,NA,NB,NC,NE1,NE2,'RS')
                            sair = 0
                            
                if list_espec_simpl[cont_archSimpl] == 'CP': #para capacitores em paralelo
                    #cont = 0
                    for subgraph in lista_subgraph:
                        # AUX DEBUG #######################
                        #if cont == 1:
                        #    print('break ',cont)
                        #    break
                        #print('cont ',cont)
                        #cont = cont + 1
                        #print(list(subgraph.keys())[list(subgraph.values()).index('C1')], list(subgraph.keys())[list(subgraph.values()).index('C2')], '\n')
                        #############################
                        
                        #busca estrutura no grafo do circuito
                        NA = list(subgraph.keys())[list(subgraph.values()).index('NA')]
                        NB = list(subgraph.keys())[list(subgraph.values()).index('NB')]
                        NC = 'none'
                        NE1 = list(subgraph.keys())[list(subgraph.values()).index('C1')] #nó elemento (pode ser C ou R)
                        NE2 = list(subgraph.keys())[list(subgraph.values()).index('C2')] #nó elemento (pode ser C ou R)
                        #verifica se o nó existe (se já não foi simplificado)
                        if (graph.has_node(NE1)) and (graph.has_node(NE2)): #pode simplificar
                            nCP = nCP + 1
                            graph = simplificar(graph,NA,NB,NC,NE1,NE2,'CP')
                            sair = 0

                if list_espec_simpl[cont_archSimpl] == 'RP': #para resistores em paralelo
                    for subgraph in lista_subgraph:
                        #busca estrutura no grafo do circuito
                        NA = list(subgraph.keys())[list(subgraph.values()).index('NA')]
                        NB = list(subgraph.keys())[list(subgraph.values()).index('NB')]
                        NC = 'none'
                        NE1 = list(subgraph.keys())[list(subgraph.values()).index('R1')] #nó elemento (pode ser C ou R)
                        NE2 = list(subgraph.keys())[list(subgraph.values()).index('R2')] #nó elemento (pode ser C ou R)
                        #verifica se o nó existe (se já não foi simplificado)
                        if (graph.has_node(NE1)) and (graph.has_node(NE2)): #pode simplificar
                            nRP = nRP + 1
                            graph = simplificar(graph,NA,NB,NC,NE1,NE2,'RP')
                            sair = 0
        
###########################################################################################################
###########################################################################################################


    
        #cria grafo das arquiteturas
        cont_arch = -1
        listaMatch =[]
        for arch in arch_list:
            cont_arch=cont_arch +1
            #sem peso
            #graph_arch = create_graph(arch[0],arch[2],arch[1], False)
            #COm peso
            graph_arch = create_graph(arch[0],arch[2],arch[1],True,False)
    
            #para encontrar isomorfismo em grafo sem peso                
            #GM = iso.GraphMatcher(graph,graph_arch)
    
            #em = iso.numerical_multiedge_match(['weight','weight','weight'], [1,2,3])
            em = iso.numerical_edge_match(['weight','weight','weight','weight','weight'], [1,2,3,4,5])
            #em = iso.numerical_edge_match('weight', 2)
            GM = iso.GraphMatcher(graph,graph_arch,edge_match=em)
            II = GM.subgraph_is_isomorphic()
            #print(GM.is_isomorphic())
            print('espelho de corrente: ',cont_arch+1,II) #+1 porque as arquiteturas começam em 1 e não zero
            
            
            
            #para teste 
            if II:
               listaMatch.append(str(cont_arch+1))
               for subgraph in GM.subgraph_isomorphisms_iter():
                   print(subgraph)
                   
                   plot_graph(graph.subgraph(subgraph.keys()))
        
        
        # resultados acurácia
        print('nCS,nCP,nRS,nRP', nCS,nCP,nRS,nRP)
        
        
        listaMatchCircs.append(listaMatch)
        listaMatchCircsReal.append(arch_in_circ)
        a=set(listaMatch)
        b=set(arch_in_circ)
        contador = contador+1
        print('contador =', contador)
        acc[circ] = len(a.intersection(b))
        tot = tot + len(b)
        print(' ___________________________________________________________' )
        print(' ___________________________________________________________' )
   
    
        print('Acurácia = ' + str(sum(acc)/tot))
  def __init__(self,
               pos: np.ndarray,
               sitetypes: List[str],
               env2config: List[int],
               permutations: List[List[int]],
               cutoff: float = 6.00,
               Grtol: float = 0.0,
               Gatol: float = 0.01,
               rtol: float = 0.01,
               atol: float = 0.0,
               tol: float = 0.01,
               grtol: float = 1e-3):
    """
    Initialize site environment

    This class contains local site environment information. This is used
    to find neighbor list in the datum.

    Parameters
    ----------
    pos : np.ndarray
      n x 3 list or numpy array of (non-scaled) positions. n is the
      number of atom.
    sitetypes : List[str]
      n list of string. String must be S or A followed by a
      number. S indicates a spectator sites and A indicates a active
      sites.
    env2config: List[int]
      A particular permutation of the neighbors around an active
      site. These indexes will be used for lattice transformation.
    permutations : List[List[int]]
      p x n list of list of integer. p is the permutation
      index and n is the number of sites.
    cutoff : float
      cutoff used for pooling neighbors.
    Grtol : float (default 0.0)
      relative tolerance in distance for forming an edge in graph
    Gatol : float (default 0.01)
      absolute tolerance in distance for forming an edge in graph
    rtol : float (default 0.01)
      relative tolerance in rmsd in distance for graph matching
    atol : float (default 0.0)
      absolute tolerance in rmsd in distance for graph matching
    tol : float (default 0.01)
      maximum tolerance of position RMSD to decide whether two
      environment are the same
    grtol : float (default 0.01)
      tolerance for deciding symmetric nodes
    """
    try:
      import networkx.algorithms.isomorphism as iso
    except:
      raise ImportError("This class requires networkx to be installed.")
    self.pos = pos
    self.sitetypes = sitetypes
    self.activesiteidx = [i for i, s in enumerate(self.sitetypes) if 'A' in s]
    self.formula: DefaultDict[str, int] = defaultdict(int)
    for s in sitetypes:
      self.formula[s] += 1
    self.permutations = permutations
    self.env2config = env2config
    self.cutoff = cutoff
    # Set up site environment matcher
    self.tol = tol
    # Graphical option
    self.Grtol = Grtol
    self.Gatol = Gatol
    # tolerance for grouping nodes
    self.grtol = grtol
    # determine minimum distance between sitetypes.
    # This is used to determine the existence of an edge
    dists = squareform(pdist(pos))
    mindists = defaultdict(list)
    for i, row in enumerate(dists):
      row_dists = defaultdict(list)
      for j in range(0, len(sitetypes)):
        if i == j:
          continue
        # Sort by bond
        row_dists[frozenset((sitetypes[i], sitetypes[j]))].append(dists[i, j])
      for pair in row_dists:
        mindists[pair].append(np.min(row_dists[pair]))
    # You want to maximize this in order to make sure every node gets an edge
    self.mindists = {}
    for pair in mindists:
      self.mindists[pair] = np.max(mindists[pair])
    # construct graph
    self.G = self._construct_graph(pos, sitetypes)
    # matcher options
    self._nm = iso.categorical_node_match('n', '')
    self._em = iso.numerical_edge_match('d', 0, rtol, 0)
Exemple #36
0
def subgraph_isomorphism(graph, sub):
    nm = iso.numerical_node_match('label', -1)
    em = iso.numerical_edge_match('label', -1)
    matcher = iso.DiGraphMatcher(graph, sub, node_match=nm, edge_match=em)
    return matcher.subgraph_is_isomorphic()
Exemple #37
0
def graph_isomorphism(graph1, graph2):
    nm = iso.numerical_node_match('label', -1)
    em = iso.numerical_edge_match('label', -1)
    matcher = iso.DiGraphMatcher(graph1, graph2, node_match=nm, edge_match=em)
    return matcher.is_isomorphic()
Exemple #38
0
import networkx as nx
from networkx import Graph, MultiGraph
from ase import Atoms, Atom
from ase.constraints import FixConstraint, FixBondLengths
from ase.data import chemical_symbols
import networkx.algorithms.isomorphism as iso
import numpy as np
import copy
import warnings
try:
    from builtins import super
except (ImportError):
    from __builtin__ import super

sym = np.array(chemical_symbols)
em = iso.numerical_edge_match('bonds', 1)
nm = iso.numerical_node_match('number', 1)


class Gratoms(Atoms):
    """Graph based atoms object.

    An Integrated class for an ASE atoms object with a corresponding
    Networkx Graph.
    """
    def __init__(self,
                 symbols=None,
                 positions=None,
                 numbers=None,
                 tags=None,
                 momenta=None,
Exemple #39
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)
Exemple #40
0
 def __init__(self,pos,sitetypes,env2config,permutations,cutoff,\
              Grtol=0.0,Gatol=0.01,rtol = 0.01,atol=0.0, tol=0.01,grtol=0.01):
     """ Initialize site environment
     
     This class contains local site enrivonment information. This is used
     to find neighborlist in the datum (see GetMapping).
     
     Parameters
     ----------
     pos : n x 3 list or numpy array of (non-scaled) positions. n is the 
         number of atom.
     sitetypes : n list of string. String must be S or A followed by a 
         number. S indicates a spectator sites and A indicates a active 
         sites.
     permutations : p x n list of list of integer. p is the permutation 
         index and n is the number of sites.
     cutoff : float. cutoff used for pooling neighbors. for aesthetics only
     Grtol : relative tolerance in distance for forming an edge in graph
     Gatol : absolute tolerance in distance for forming an edge in graph
     rtol : relative tolerance in rmsd in distance for graph matching
     atol : absolute tolerance in rmsd in distance for graph matching
     tol : maximum tolerance of position RMSD to decide whether two 
         environment are the same
     grtol : tolerance for deciding symmetric nodes
     """
     self.pos = pos
     self.sitetypes = sitetypes
     self.activesiteidx = [
         i for i, s in enumerate(self.sitetypes) if 'A' in s
     ]
     self.formula = defaultdict(int)
     for s in sitetypes:
         self.formula[s] += 1
     self.permutations = permutations
     self.env2config = env2config
     self.cutoff = cutoff
     # Set up site environment matcher
     self.tol = tol
     # Graphical option
     self.Grtol = Grtol
     self.Gatol = Gatol
     #tolerance for grouping nodes
     self.grtol = 1e-3
     # determine minimum distance between sitetypes.
     # This is used to determine the existence of an edge
     dists = squareform(pdist(pos))
     mindists = defaultdict(list)
     for i, row in enumerate(dists):
         row_dists = defaultdict(list)
         for j in range(0, len(sitetypes)):
             if i == j:
                 continue
             # Sort by bond
             row_dists[frozenset(
                 (sitetypes[i], sitetypes[j]))].append(dists[i, j])
         for pair in row_dists:
             mindists[pair].append(np.min(row_dists[pair]))
     # You want to maximize this in order to make sure every node gets an edge
     self.mindists = {}
     for pair in mindists:
         self.mindists[pair] = np.max(mindists[pair])
     # construct graph
     self.G = self._ConstructGraph(pos, sitetypes)
     # matcher options
     self._nm = iso.categorical_node_match('n', '')
     self._em = iso.numerical_edge_match('d', 0, rtol, 0)
                        pred_node = dagList[pred_dag_id]
                        pred_node_name = pred_node[0].name + '_' + str(
                            pred_dag_id)
                        if pred_dag_id in group:  # if in the group, connect them
                            G.add_weighted_edges_from([(name, pred_node_name,
                                                        new_qarg)])
                        else:  # if not in the group connect it to a dumb_node
                            G.add_nodes_from([dumb_node], fill='dumb')
                            G.add_weighted_edges_from([(dumb_node, name,
                                                        new_qarg)])
                            dumb_node = chr(ord(dumb_node) - 1)
                        index += 1
                        i += 1
            # compare with known structures in table_list

            em = iso.numerical_edge_match('weight', 1)
            nm = iso.categorical_node_match('fill', 'dumb')

            index = 0
            found = False
            while index < len(dist_table):
                H = dist_table[index]
                if nx.is_isomorphic(G, H, node_match=nm, edge_match=em):
                    dist_table_dict[index] = dist_table_dict[index] + 1
                    found = True
                    break
                index += 1
            if not found:  # add a new structure
                dist_table.append(G)
                pos = len(dist_table) - 1
                dist_table_dict[pos] = 1
def main():
    # create a rosnode
    rospy.init_node("agent_test", log_level=rospy.DEBUG)

    # create an agent with the intent to control right arm
    test_agent = agent.Agent('right')  # pylint: disable=C0103
    test_agent.subscribe()

    #    B
    # _ BB
    #   BB
    #    B Actual Pyramid
    """
    green_1x4 = kb.Block(length=4, width=1, color="green")
    green_1x4_final_position = Point(x=0.735, y=-0.287, z=0.0)
    blue_1x2 = kb.Block(length=2, width=1, color="blue")
    blue_1x2_final_position = Point(x=0.738, y=-0.240, z=0.0)

    green_1x4_pnp = generate_pick_and_place(
        green_1x4, green_1x4_final_position, 0, 0)

    blue_1x2_pnp = generate_pick_and_place(
        blue_1x2, blue_1x2_final_position, 0, 1)

    fake_action_list = green_1x4_pnp + blue_1x2_pnp + [None]

    green_1x4_desired = Pose2D(x=0.729, y=-0.273, theta=0.0)
    blue_1x2_desired = Pose2D(x=0.723, y=-0.321, theta=math.pi/2)

    green_1x4_block = kb.Block(length=4, width=1, color="green",
                               pose=green_1x4_desired)
    blue_1x2_block = kb.Block(
        length=2, width=1, color="blue", pose=blue_1x2_desired)
    """

    # BBB
    #  B
    #  B
    #  B
    #  B
    # BBB  Barbell
    green_1x2 = kb.Block(length=2, width=1, color="green")
    green_1x2_final_position = Point(x=0.554, y=-0.239, z=0.0)

    blue_1x4 = kb.Block(length=4, width=1, color="blue")
    blue_1x4_final_position = Point(x=.637, y=-0.242, z=0.0)

    red_1x2 = kb.Block(length=2, width=1, color="red")
    red_1x2_final_position = Point(x=0.728, y=-0.247, z=0.0)

    green_1x2_pnp = generate_pick_and_place(green_1x2,
                                            green_1x2_final_position, 0, 1)

    blue_1x4_pnp = generate_pick_and_place(blue_1x4, blue_1x4_final_position,
                                           0, 0)

    red_1x2_pnp = generate_pick_and_place(red_1x2, red_1x2_final_position, 0,
                                          1)

    fake_action_list = green_1x2_pnp + red_1x2_pnp + blue_1x4_pnp

    green_1x2_desired = Pose2D(x=0.807, y=-0.245, theta=math.pi / 2)
    blue_1x4_desired = Pose2D(x=0.729, y=-0.241, theta=0)
    red_1x2_desired = Pose2D(x=0.653, y=-0.232, theta=math.pi / 2)

    green_1x2_block = kb.Block(length=4,
                               width=1,
                               color="green",
                               pose=green_1x2_desired)
    blue_1x4_block = kb.Block(length=4,
                              width=1,
                              color="blue",
                              pose=blue_1x4_desired)
    red_1x2_block = kb.Block(length=2,
                             width=1,
                             color="red",
                             pose=red_1x2_desired)

    expectation = kb.EnvState()
    expectation.add_block(green_1x2_block)
    expectation.add_block(blue_1x4_block)
    expectation.add_block(red_1x2_block)

    errortolerancexy = 0.010
    errortolerancetheta = 0.087

    node_condition1 = iso.categorical_node_match(['length', 'width'], [1, 1])
    node_condition2 = iso.numerical_edge_match(['pose_x', 'pose_y'], [0, 0],
                                               rtol=errortolerancexy)
    node_condition3 = iso.numerical_edge_match(['pose_theta'], [0],
                                               rtol=errortolerancetheta)

    i = 0
    none_count = 0
    while (True):
        action_dict = fake_action_list[i]

        if (action_dict is None):
            none_count += 1
        else:
            rospy.loginfo("Executing action: %s", action_dict['desc'])
            action = action_dict['action']
            constraints = action_dict['constraints']

            test_agent.executor(action, constraints)
            rospy.sleep(0.1)

        i += 1

        if (none_count == 1):
            rospy.loginfo("Finished block PNP!")
            rospy.loginfo("Adding new block to WS EnvState")

        if (none_count == 2):
            rospy.loginfo("Task complete")
            break

    expectation.print_graph()
    test_agent.get_ws().print_graph()
    result1 = nx.is_isomorphic(expectation.ws_state,
                               test_agent.get_ws().ws_state,
                               node_match=node_condition1)
    result2 = nx.is_isomorphic(expectation.ws_state,
                               test_agent.get_ws().ws_state,
                               node_match=node_condition2)
    result3 = nx.is_isomorphic(expectation.ws_state,
                               test_agent.get_ws().ws_state,
                               node_match=node_condition3)
    result = result1 and result2 and result3

    print("Result 1: ", result1, " and Result 2: ", result2, " Result 3: ",
          result3, " and sum ", result)