コード例 #1
0
ファイル: projection.py プロジェクト: changminc/IsFAM.net
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
コード例 #2
0
def ___non_isomorphic_graphs_dict(nx_objects):
    # nx_objects =  [nx.relabel.convert_node_labels_to_integers(o, label_attribute='number') for o in objects]

    # Add labels as attributes
    for g in nx_objects:
        node_number = len(g.nodes())
        labels = random.sample(range(node_number), node_number)
        i = 0
        for n in g.nodes():
            g.nodes[n]['number'] = labels[i]
            i += 1

    # Filter out isomorphic graphs
    nm = iso.numerical_node_match('number', 0)

    graphs = dict()
    checked = []
    for g in nx_objects:
        if g not in checked:
            isomorphic = [
                x for x in nx_objects if iso.is_isomorphic(x, g, node_match=nm)
            ]
            graphs[g] = len(isomorphic)
            checked = checked + isomorphic

    return graphs
コード例 #3
0
ファイル: iso.py プロジェクト: knaperek/gits
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)
コード例 #4
0
ファイル: projection.py プロジェクト: caomw/IsFAM.net
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
コード例 #5
0
ファイル: graph.py プロジェクト: mhoffman/CatKit
def isomorphic_molecules(graph0, graph1):
    """Check whether two molecule graphs are isomorphic."""
    em = iso.numerical_edge_match('bonds', 1)
    nm = iso.numerical_node_match('number', 1)

    isomorphic = nx.is_isomorphic(graph0, graph1, edge_match=em, node_match=nm)

    return isomorphic
コード例 #6
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]
コード例 #7
0
    def determine_reward(self, state, features, workflow_vals):
        reward = 0

        if np.shape(state)[0] != np.shape(self.truth_state)[0]:
            self.terminated = False
            return reward
        #print('workflowvals and truth',workflow_vals,self.workflow_vals_truth)
        graph_current = environment.create_DAG(state, features)
        graph_truth = environment.create_DAG(self.truth_state,
                                             self.truth_features)
        nm = iso.numerical_node_match('feat', range(self.node_types))

        if nx.is_isomorphic(graph_current, graph_truth, node_match=nm):
            reward = 1000
        elif self.loss != 0:
            reward = -1
        '''if workflow_vals[-1] == self.workflow_vals_truth[-1]:
            #print('WOW')
            reward = 1000'''
        self.terminated = True
        return reward
コード例 #8
0
ファイル: matching.py プロジェクト: zqhuang2014/CatKit
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
コード例 #9
0
ファイル: analyze.py プロジェクト: bmatejek/network_motifs
def FindUniqueTopologies(traces):
    """
    Find all of the unique topologies within this set of traces. A unique topology
    either differs in graph structure (parent/child) or function called at a node.
    @param traces: the list of traces to compare topologies
    """

    # node labels must match
    node_match = isomorphism.numerical_node_match('label', None)

    unique_graphs = []
    durations = []
    nodes = []

    for trace in traces:
        graph_from_trace = ConstructGraphFromTrace(trace)
        nodes.append(len(trace.nodes))
        durations.append(trace.duration)

        # see if this matches any exists graphs
        unique_graph = True
        for unique_graph in unique_graphs:
            if nx.is_isomorphic(graph_from_trace, unique_graph):
                unique_graph = False
                break

        # create new entry for unique graph
        if unique_graph:
            unique_graphs.append(graph_from_trace)

    print(len(traces))
    print(statistics.mean(nodes))
    print(statistics.pstdev(nodes))
    print(statistics.mean(durations))
    print(statistics.pstdev(durations))
    print(len(unique_graphs))
コード例 #10
0
ファイル: projection_example.py プロジェクト: caomw/IsFAM.net
            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] )
            

    
コード例 #11
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()
コード例 #12
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()
コード例 #13
0
ファイル: gratoms.py プロジェクト: mhoffman/CatKit
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,
                 masses=None,
コード例 #14
0
        if v1 == v2:  # Remove Nodes self to self
            del G_q_od[v1][v2]
        else:  # Modify Weights of Other Nodes & Assign them to Graph G
            # Edge Label
            order_dist = G_q_od[v1][v2]
            order_dist -= 1
            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])
コード例 #15
0
          label='descriptor',
          value='yutz'), ValueError),
    (dict(graph_component='edge',
          query_type='goyish',
          label='descriptor',
          value='yutz'), ValueError)
])
def test_graph_query_params_errors(args, Error):
    with pytest.raises(Error):
        query_params = GraphQueryParams(**args)
        query_params.set_value_type()


@pytest.mark.parametrize('query_param_args,expected_match_function', [
    (dict(graph_component='node', label='a_number', value_type='numerical'),
     iso.numerical_node_match('a_number', np.nan)),
    (dict(graph_component='node', label='a_category',
          value_type='categorical'),
     iso.categorical_node_match('a_category', None)),
    (dict(graph_component='edge', value_type='numerical',
          label='a_number'), iso.numerical_edge_match('a_number', np.nan)),
    (dict(graph_component='edge', value_type='categorical',
          label='a_category'), iso.categorical_edge_match('a_category', None)),
])
def test_graph_query_params_match_fn(query_param_args,
                                     expected_match_function):
    # Comparing byte code idea from
    # https://stackoverflow.com/questions/20059011/check-if-two-python-functions-are-equal
    query_params = GraphQueryParams(**query_param_args)
    if query_params.value is not None:
        query_params.set_value_type()
コード例 #16
0
    nx.draw(G_pat)

    G_subgraphs = build_subgraphs(
        G, induced='vertex'
    )  # In this example, if induced = 'nodes' it won't find any isomorphisms.

    # Categorical match functions
    nm_cat = isomorphism.categorical_node_match("attr", 1)
    em_cat = isomorphism.categorical_edge_match("attr", 1)

    print find_sub_iso(G_subgraphs,
                       G_pat,
                       node_match=nm_cat,
                       edge_match=em_cat)

    # Numerical match functions
    nm_num = isomorphism.numerical_node_match(
        "attr", 0, atol=0.5,
        rtol=1e-05)  # Matches if |x-y|<= atol + abs(y)*rtol
    print find_sub_iso(G_subgraphs, G_pat, node_match=nm_num, edge_match=None)

    # Generic match functions
    op = lambda x, y: x >= y
    nm_gen = isomorphism.generic_node_match("attr", 0, op)
    sub_iso = find_sub_iso(G_subgraphs,
                           G_pat,
                           node_match=nm_gen,
                           edge_match=None)

    if sub_iso:
        print sub_iso[0]["nodes"].values()