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])
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])
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 build(self): g1 = self.g1 g2 = self.g2 # We will assume integer weights only. g1.add_edge("A", "B", color="green", weight=0, size=0.5) g1.add_edge("A", "B", color="red", weight=1, size=0.35) g1.add_edge("A", "B", color="red", weight=2, size=0.65) g2.add_edge("C", "D", color="green", weight=1, size=0.5) g2.add_edge("C", "D", color="red", weight=0, size=0.45) g2.add_edge("C", "D", color="red", weight=2, size=0.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, 0.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, 0.5], [eq, eq, iso.matchhelpers.close], )
def getBodyIsomorphism(self, rule): """ Applies the isomorphism algorithm on the graphs of this and another rules' bodies. Parameters ---------- rule : AMIERule The other rule to compare. Returns ------- nxiso.DiGraphMatcher The DiGraphMatcher instance of the applied isomorphism algorithm. """ # build graphs for the body of each rule and test for isomorphism self_graph = nx.DiGraph() for body_triple in self._body: self_graph.add_node(body_triple.s) self_graph.add_node(body_triple.o) self_graph.add_edge(body_triple.s, body_triple.o, label=body_triple.p) other_graph = nx.DiGraph() for body_triple in rule.body: other_graph.add_node(body_triple.s) other_graph.add_node(body_triple.o) other_graph.add_edge(body_triple.s, body_triple.o, label=body_triple.p) nm = nxiso.categorical_edge_match("label", "empty") dgm = nxiso.DiGraphMatcher(self_graph, other_graph, edge_match=nm) return dgm
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))
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
def checkSubGraphIsomorphismWithLabels(G1,G2): def checkTupleEquality(tuple_a,tuple_b): if tuple_a[0]==tuple_b[0] and tuple_a[1]==tuple_b[1]: return True elif tuple_a[0]==tuple_b[1] and tuple_a[1]==tuple_b[0]: return True else: return False def nodeMatchWithVertexLabels(dictA,dictB): return checkTupleEquality(dictA['label'],dictB['label']) def findCommonNode(tuple_a,tuple_b): for i in tuple_a: if i in tuple_b: return i def generateLabeledLineGraph(G): lineGraph=nx.line_graph(G) for vertexIndex in lineGraph: lineGraph.node[vertexIndex]['label']=(G.node[vertexIndex[0]]['label'],G.node[vertexIndex[1]]['label']) for n,nbrsdict in lineGraph.adjacency_iter(): for nbr,eattr in nbrsdict.items(): lineGraph.edge[n][nbr]['label']=G.node[findCommonNode(n,nbr)]['label'] return lineGraph em = iso.categorical_edge_match('label', 'miss') lineGraphG1=generateLabeledLineGraph(G1) lineGraphG2=generateLabeledLineGraph(G2) GM=isomorphism.GraphMatcher(lineGraphG2,lineGraphG1,node_match=nodeMatchWithVertexLabels,edge_match=em) return GM.subgraph_is_isomorphic()
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
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))
def checkSubGraphIsomorphismWithLabels(G1,G2): def checkTupleEquality(tuple_a,tuple_b): if tuple_a[0]==tuple_b[0] and tuple_a[1]==tuple_b[1]: return True elif tuple_a[0]==tuple_b[1] and tuple_a[1]==tuple_b[0]: return True else: return False def nodeMatchWithVertexLabels(dictA,dictB): return checkTupleEquality(dictA['label'],dictB['label']) def findCommonNode(tuple_a,tuple_b): for i in tuple_a: if i in tuple_b: return i def generateLabeledLineGraph(G): lineGraph=nx.line_graph(G) for vertexIndex in lineGraph: lineGraph.node[vertexIndex]['label']=(G.node[vertexIndex[0]]['label'],G.node[vertexIndex[1]]['label']) for n,nbrsdict in lineGraph.adjacency_iter(): for nbr,eattr in nbrsdict.items(): lineGraph.edge[n][nbr]['label']=G.node[findCommonNode(n,nbr)]['label'] return lineGraph em = iso.categorical_edge_match('label', 'miss') lineGraphG1=generateLabeledLineGraph(G1) lineGraphG2=generateLabeledLineGraph(G2) GM=isomorphism.GraphMatcher(lineGraphG2,lineGraphG1,node_match=nodeMatchWithVertexLabels,edge_match=em) return GM.subgraph_is_isomorphic()
def get_IsomorphismChecker(G1, G2): nm = lambda x, y: x.element == y.element em = iso.categorical_edge_match('weight', None) return CustomGraphMatcher(G1, G2, node_match=nm, edge_match=em)
def find_schema_id(sub, dico): """ find a schema id for a given schema """ for key in dico.keys(): em = iso.categorical_edge_match('label', 1) if nx.is_isomorphic(dico[key], sub, edge_match=em): return key
def GraphCompare(Graph1, Graph2): if len(Graph1.nodes()) != len(Graph2.nodes()): return False if len(Graph1.edges()) != len(Graph2.edges()): return False em = iso.categorical_edge_match("Type", "") if not nx.is_isomorphic(Graph1, Graph2, edge_match=em): return False return True
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())
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
def are_equivalent_partitions(a, b): """Checks for partition equivalence by checking if the graphs are isomorphic.""" ga = a["graph"] gb = b["graph"] if not iso.faster_could_be_isomorphic(ga, gb): return False em = iso.categorical_edge_match("particle", "exotic") return nx.is_isomorphic(ga, gb, edge_match=em)
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
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
def already_exists(sub, subs): """ returns true if a schema is contained in a list of schema """ exists = False em = iso.categorical_edge_match('label', 1) #nm = iso.categorical_node_match('type', "edu") for compsub in subs: if nx.is_isomorphic(compsub, sub, edge_match=em): exists = True break return exists
def is_subgraph(mc_info) -> bool: nonlocal current_subgraph graph, path = mc_info try: GM = iso.GraphMatcher(graph, current_subgraph, edge_match=iso.categorical_edge_match( ['label'], ['-'])) return GM.subgraph_is_monomorphic() except KeyError: log.debug('Lib-Error in subgraph matching!') return False
def is_isomorphic(graph1, graph2, ignore_active_bonds=False, timeout=5): """Check whether two NX graphs are isomorphic. Contains a timeout because the gm.is_isomorphic() method occasionally gets stuck Arguments: graph1 (nx.Graph): graph 1 graph2 (nx.Graph): graph 2 Keyword Arguments: ignore_active_bonds (bool): timeout (float): Timeout in seconds Returns: (bool): if the graphs are isomorphic """ if ignore_active_bonds: graph1, graph2 = get_graphs_ignoring_active_edges(graph1, graph2) if not isomorphism.faster_could_be_isomorphic(graph1, graph2): return False # Always match on atom types node_match = isomorphism.categorical_node_match('atom_label', 'C') if ignore_active_bonds: gm = isomorphism.GraphMatcher(graph1, graph2, node_match=node_match) else: # Also match on edges edge_match = isomorphism.categorical_edge_match('active', False) gm = isomorphism.GraphMatcher(graph1, graph2, node_match=node_match, edge_match=edge_match) # NX can hang here for not very large graphs, so kill after a timeout def handler(signum, frame): raise TimeoutError signal.signal(signal.SIGALRM, handler) signal.alarm(int(timeout)) try: result = gm.is_isomorphic() # Cancel the timer signal.alarm(0) return result except TimeoutError: logger.error('NX graph matching hanging') return False
def __eq__(self, other: 'NNCFGraph'): nm = iso.categorical_node_match([ NNCFGraph.ID_NODE_ATTR, NNCFGraph.KEY_NODE_ATTR, NNCFGraph.LAYER_ATTRIBUTES ], [None, None, None]) em = iso.categorical_edge_match([ NNCFGraph.ACTIVATION_SHAPE_EDGE_ATTR, NNCFGraph.INPUT_PORT_ID_EDGE_ATTR ], [None, None]) return nx.is_isomorphic(self._nx_graph, other._nx_graph, node_match=nm, edge_match=em)
def __eq__(self, other: 'NNCFGraph'): nm = iso.categorical_node_match([ NNCFGraph.ID_NODE_ATTR, NNCFGraph.KEY_NODE_ATTR, NNCFGraph.OP_EXEC_CONTEXT_NODE_ATTR ], [None, None, None]) em = iso.categorical_edge_match([ NNCFGraph.ACTIVATION_SHAPE_EDGE_ATTR, NNCFGraph.IN_PORT_NAME_EDGE_ATTR ], [None, None]) return nx.is_isomorphic(self._nx_graph, other._nx_graph, node_match=nm, edge_match=em)
def is_isomorph_nx(graph1, graph2): """ graph1, graph2: графы в формате networkx, изоморфность которых проверяется return: True, если графы изоморфны, иначе False """ is_iso = nx.faster_could_be_isomorphic(graph1, graph2) node_match = iso.categorical_node_match('label', 'C') edge_match = iso.categorical_edge_match(['weight', 'label'], [1, '-']) if is_iso: return iso.is_isomorphic(graph1, graph2, node_match=node_match, edge_match=edge_match) return False
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()
def test_monomorphism_edge_match(): G = nx.DiGraph() G.add_node(1) G.add_node(2) G.add_edge(1, 2, label="A") G.add_edge(2, 1, label="B") G.add_edge(2, 2, label="C") SG = nx.DiGraph() SG.add_node(5) SG.add_node(6) SG.add_edge(5, 6, label="A") gm = iso.DiGraphMatcher(G, SG, edge_match=iso.categorical_edge_match("label", None)) assert gm.subgraph_is_monomorphic()
def isIsomorphicGraph(graphA, graphB, colorsMappings): """ check if two graphs are isomorphic regarding with :param graphB: :param colorsMappings: :return: """ tempGraphB = copy.deepcopy(graphB) edgeColor = nx.get_edge_attributes(tempGraphB, "color") attr = {} for edge in nx.edges(tempGraphB): attr[edge] = {"color": colorsMappings[edgeColor[edge]]} nx.set_edge_attributes(tempGraphB, attr) em = iso.categorical_edge_match('color', "red") if nx.is_isomorphic(graphA, tempGraphB, edge_match=em): return True return False
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]
def check_for_fragment(self, job, config, qm): """ Check if fragment exists in the database If not, check current fragment directory if new data is there """ self.dir = f'{config.frag_lib}/{self.hash}' self.map_frag_to_db = {i: i for i in range(self.n_atoms)} have_match = False nm = iso.categorical_node_match( ['elem', 'n_bonds', 'lone_e', 'capping', 'scan'], [0, 0, 0, False, False]) em = iso.categorical_edge_match(['type'], [0]) os.makedirs(self.dir, exist_ok=True) identifiers = [ i for i in sorted(os.listdir(f'{self.dir}')) if i.startswith('ident') ] for id_no, id_file in enumerate(identifiers, start=1): compared = nx.read_gpickle(f"{self.dir}/{id_file}") GM = iso.GraphMatcher(self.graph, compared, node_match=nm, edge_match=em) if self.graph.graph['qm_method'] == compared.graph[ 'qm_method'] and GM.is_isomorphic(): if os.path.isfile(f'{self.dir}/scandata_{id_no}'): self.has_data = True self.map_frag_to_db = GM.mapping else: # has_inp to mean that the input file has been generated # But the scan data has not been collected yet. # This variable is set such that the same input file will # not be generated twice when batch_run = True self.has_inp = True have_match = True self.hash_idx = id_no break if not have_match: self.hash_idx = len(identifiers) + 1 self.id = f'{self.hash}~{self.hash_idx}'
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()
def __init__(self, extralabels=False, isotope=False, element=True, stereo=False): """ :param extralabels: compare hybridization and neighbors count marks on isomorphism procedure :param isotope: compare isotope marks on isomorphism procedure :param element: compare elements symbols and charges on isomorphism procedure :param stereo: compare stereo marks on isomorphism procedure """ gnm_sp, gnm_s, cnm_p = [], [], ['element', 'p_charge'] if isotope: gnm_sp.append('isotope') gnm_s.append('isotope') cnm_p.append('isotope') if element: gnm_sp.extend(['sp_charge', 'element']) gnm_s.extend(['s_charge', 'element']) if extralabels: gnm_sp.extend(['sp_neighbors', 'sp_hyb']) gnm_s.extend(['s_neighbors', 's_hyb']) if stereo: gnm_sp.append('sp_stereo') gnm_s.append('s_stereo') cnm_p.append('p_stereo') self.__node_match = generic_node_match(gnm_sp, [None] * len(gnm_sp), [self.__list_eq] * len(gnm_sp)) self.__node_match_reagents = generic_node_match( gnm_s, [None] * len(gnm_s), [self.__list_eq] * len(gnm_s)) self.__node_match_products = categorical_node_match( cnm_p, [None] * len(cnm_p)) self.__edge_match = generic_node_match('sp_bond', None, self.__list_eq) self.__edge_match_reagents = generic_node_match( 's_bond', None, self.__list_eq) self.__edge_match_products = categorical_edge_match('p_bond', None) self.__pickle = dict(stereo=stereo, extralabels=extralabels, isotope=isotope, element=element)
def max_comp_element(nodes, graph, comp_graph): max_arr = [] em = isomorphism.categorical_edge_match('colour', '') nm = isomorphism.categorical_node_match('text', '') GM = isomorphism.DiGraphMatcher(graph, comp_graph, node_match=nm, edge_match=em) if GM.subgraph_is_isomorphic(): if af.count_nodes(graph) > af.count_nodes(comp_graph): max_arr.append(comp_graph) return max_arr else: max_arr.append(graph) return max_arr else: for obj in nodes: curr_graph = gf.transform_into_graph_algo(obj) max_comp_element_alg(obj, curr_graph, comp_graph, max_arr) return max_arr
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 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 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()
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)
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
def findCommonNode(tuple_a,tuple_b): for i in tuple_a: if i in tuple_b: return i def generateLabeledLineGraph(G): lineGraph=nx.line_graph(G) for vertexIndex in lineGraph: lineGraph.node[vertexIndex]['label']=(G.node[vertexIndex[0]]['label'],G.node[vertexIndex[1]]['label']) for n,nbrsdict in lineGraph.adjacency_iter(): for nbr,eattr in nbrsdict.items(): lineGraph.edge[n][nbr]['label']=G.node[findCommonNode(n,nbr)]['label'] return lineGraph em = iso.categorical_edge_match('label', 'miss') def checkSubGraphIsomorphismWithLabels(G1,G2): if len(G1.nodes())==2 and len(G1.edges())==1: loneEdge=G1.edges()[0] loneEdgetuple=(G1.node[loneEdge[0]]['label'],G1.node[loneEdge[1]]['label']) foundMatch=False for edge in G2.edges(): edgeLabel=(G2.node[edge[0]]['label'],G2.node[edge[1]]['label']) if not foundMatch: foundMatch=checkTupleEquality(edgeLabel,loneEdgetuple) print foundMatch return foundMatch #Returns true if G1 is a subGraph of G2 lineGraphG1=generateLabeledLineGraph(G1) lineGraphG2=generateLabeledLineGraph(G2)