def opt(g, model="uncorrelated"): h = gt.Graph(g) diam, aspl = diam_aspl(h) while True: print(diam, aspl) tmp = gt.Graph(h) print(random_rewire(tmp, model=model)) tmp_diam, tmp_aspl = diam_aspl(tmp) if tmp_diam < diam or (tmp_diam == diam and tmp_aspl < aspl): h, diam, aspl = tmp, tmp_diam, tmp_aspl
def is_convex(dataset): X = np.genfromtxt('res/benchmark/SSL,set=' + str(dataset) + ',X.tab') #X = (X - np.min(X, axis=0)) / (np.max(X, axis=0) - np.min(X, axis=0)) y = (np.genfromtxt('res/benchmark/SSL,set=' + str(dataset) + ',y.tab')) n = 300 for n_prime in [n]: print("================================") print("n_prime=", n_prime) for q in [0.001, 0.002, 0.005, 0.01, 0.02, 0.05]: print("q=", q) dists = scipy.spatial.distance.cdist(X, X) y = y[:n] W = dists[:n, :n] #np.exp(-(dists) ** 2 / (2 * sigma ** 2)) np.fill_diagonal(W, 0) W[W > np.quantile(W, q)] = np.inf # W2 = np.copy(W) less edges is slower strangely # W2[W2 <= 0.1] = 0 weights = W[(W < np.inf) & (W > 0)].flatten() edges = np.array(np.where((W < np.inf) & (W > 0))).T np.random.seed(0) g = gt.Graph() # construct actual graph g.add_vertex(n) g.add_edge_list(edges) weight_prop = g.new_edge_property("double", vals=weights) comps, hist = gt.topology.label_components(g) print(len(simplicial_vertices(g))) continue paths = shortest_path_cover_logn_apx(g, weight_prop) sum = 0 for i in paths: sum += np.ceil(np.log2(len(i))) print("|S|=", len(paths)) print("#queries<=", sum, "%:", sum / n) pos = list(np.arange(n)[y > 0])[:n_prime] neg = list(np.arange(n)[y <= 0])[:n_prime] print(n, pos, neg) print("p", len(pos)) print("n", len(neg)) pos_hull = closure.compute_hull(g, pos, weight_prop, comps, hist) print(np.sum(pos_hull)) neg_hull = closure.compute_hull(g, neg, weight_prop, comps, hist) print(np.sum(neg_hull)) print( len( set(np.where(pos_hull)[0]).intersection( set(np.where(neg_hull)[0]))) / n)
def test_encounter(hs): exec(open('hotspotter/encounter.py').read()) encounter.rrr() dev_api.dev_reload.reload_all_modules() try: if USE_TESTCACHE: raise KeyError('use_testcache=False') ex2_cxs = helpers.load_testdata('ex2_cxs', uid=hs.get_db_name()) except KeyError: ex2_cxs = encounter.get_chip_encounters(hs) helpers.save_testdata('ex2_cxs', uid=hs.get_db_name()) cxs = ex2_cxs[-1] assert len(cxs) > 1 qcx2_res = encounter.intra_query_cxs(hs, cxs) # Make a graph between the chips graph_netx = encounter.make_chip_graph(qcx2_res) netx.write_dot(graph_netx, 'encounter_graph.dot') try: import graph_tool graph = graph_tool.Graph() except ImportError as ex: print(ex) #encounter.viz_chipgraph(hs, graph, fnum=20, with_images=False) #encounter.viz_chipgraph(hs, graph, fnum=20, with_images=True) df2.update()
def construct_graph_graphtool(M): """ Given an (unweighted, undirected) biadjacency matrix M, construct a graph_tool graph object with the corresponding edges. Returns the graph G as well as a mapping from vertices of G to cells (rows) and mutations (columns) in M. """ M = M.tocoo() G = graph_tool.Graph(directed = False) vtype = G.new_vertex_property("int") label2id = {} for i,j,value in zip(M.row, M.col, M.data): assert value == 1 cell_key = 'cell{}'.format(i) mut_key = 'mut{}'.format(j) if cell_key in label2id: v = label2id[cell_key] else: v = G.add_vertex() label2id[cell_key] = int(v) vtype[v] = 1 if mut_key in label2id: w = label2id[mut_key] else: w = G.add_vertex() label2id[mut_key] = int(w) vtype[w] = 2 G.add_edge(v, w) return G, label2id, vtype
def partition_mst(self): W = self._G.edge_properties['weights'] nW = self._G.new_edge_property('double') self._G.edge_properties['negative_weights'] = nW nW.a = list(-W.get_array()) T = graph_tool.topology.min_spanning_tree(self._G, nW) H = graph_tool.Graph(directed=False) for i, v in enumerate(T): if v == 1: e = graph_tool.util.find_edge(self._G, self._G.edge_index, int(i))[0] H.add_edge(e.source(), e.target()) I = np.nonzero(T.a) K = np.squeeze(np.dstack((I, np.array(W.a)[I]))) # Sort by second column. if K.size == 2: E = [K] else: E = K[K[:, 1].argsort()] P = [] for q in E: e = graph_tool.util.find_edge(self._G, self._G.edge_index, int(q[0]))[0] e_h = H.edge(e.source(), e.target()) H.remove_edge(e_h) C, h = graph_tool.topology.label_components(H) P.append([self._S[p] for p in utils.group_by(np.array(C.a))]) return P
def _extract_all_subtopologies(interactome, iso_counts, terms_dms): r''' Extract he subtopologies of a disease module and add them to ``iso_counts``. Args: interactome (:class:`Interactome <pynteractome.interactome.interactome.Interactome>`): the interactome iso_counts (:class:`IsomorphismCounts <pynteractome.isomorphism_counts.IsomorphismCounts>`): the container of isomorphisms relations. terms_dms (list): TODO ''' if not terms_dms: return last_sent_idx = 0 for idx, (term, subset) in enumerate(terms_dms): idx += 1 if idx % 50 == 0: _update_current_idx(idx - last_sent_idx) last_sent_idx = idx subgraph = gt.Graph(interactome.get_subgraph(subset, genes=True), prune=True) iso_counts.add(subgraph, term, subset) if last_sent_idx < idx: _update_current_idx(idx - last_sent_idx)
def read_dataset(collection_name): path = os.path.join('datasets', collection_name) node_to_graph_ids = [-1] graph_number = 0 with open(os.path.join(path, collection_name + '_graph_indicator.txt'), 'r') as f: li = f.readline().rstrip('\n') while li != '': x = int(li) node_to_graph_ids.append(x - 1) graph_number = max(graph_number, x) li = f.readline().rstrip('\n') graphs = [] for i in range(graph_number): graphs.append(graph_tool.Graph()) prop_maps = [] for gra in graphs: x = gra.new_edge_property('int') prop_maps.append(x) orig_line = 1 with open(os.path.join(path, collection_name + '_A.txt'), 'r') as f: li = f.readline().rstrip('\n') while li != '': x = li.split(', ') x1 = int(x[0]) x2 = int(x[1]) graph_no = node_to_graph_ids[x1] e = graphs[graph_no].add_edge(x1, x2) prop_maps[graph_no][e] = orig_line orig_line += 1 li = f.readline().rstrip('\n') return graphs, prop_maps
def convert_to_graph_tool(G): timer = utils.Timer() timer.tic() gtG = gt.Graph(directed=G.is_directed()) gtG.ep['action'] = gtG.new_edge_property('int') nodes_list = G.nodes() nodes_array = np.array(nodes_list) nodes_id = np.zeros((nodes_array.shape[0], ), dtype=np.int64) for i in range(nodes_array.shape[0]): v = gtG.add_vertex() nodes_id[i] = int(v) # d = {key: value for (key, value) in zip(nodes_list, nodes_id)} d = dict(itertools.izip(nodes_list, nodes_id)) for src, dst, data in G.edges_iter(data=True): e = gtG.add_edge(d[src], d[dst]) gtG.ep['action'][e] = data['action'] nodes_to_id = d timer.toc(average=True, log_at=1, log_str='src.graph_utils.convert_to_graph_tool') return gtG, nodes_array, nodes_to_id
def create_gt_graph_from_sparse_adjacency_matrix(A, is_directed=False, weight_type=None, list_of_vertex_labels=None): N = A.shape[0] A = A.tocoo() G = gt.Graph(directed=is_directed) if list_of_vertex_labels is not None: G.graph_properties['index_of'] = G.new_graph_property('python::object') G.graph_properties['index_of'] = dict() G.vertex_properties['label'] = G.new_vertex_property('string') for n in range(0, N): v = G.add_vertex() G.vertex_properties['label'][v] = list_of_vertex_labels[n] G.graph_properties['index_of'][list_of_vertex_labels[n]] = n else: G.add_vertex(N) if weight_type is not None: G.edge_properties['weight'] = G.new_edge_property(weight_type) for i, j, v in itertools.izip(A.row, A.col, A.data): if (not is_directed and i > j) or is_directed: e = G.add_edge(i, j) if weight_type is not None: G.edge_properties['weight'][e] = v return G
def cli(visualize, path, wide_search, depth_search): """ Command-line user interface function, designed to be program entry. """ with open(path, 'r') as adjlist: content = adjlist.read() graph = gpt.Graph(content.split('\n')) if wide_search is not None: algo = gpt.WideSearch(graph) path, step = algo.search(wide_search) click.echo('Алгоритм поиска в ширину...\nПуть: {}\nШаг: {}'.format( path, step)) if depth_search is not None: if wide_search is not None: print() # Print empty line algo = gpt.RecursiveDepthSearch(graph) path, step = algo.search(depth_search) click.echo( 'Итеративный алгоритм поиска в глубину...\nПуть: {}\nШаг: {}\n'. format(path, step)) algo = gpt.RecursiveDepthSearch(graph) path, step = algo.search(depth_search) click.echo( 'Рекурсивный алгоритм поиска в глубину...\nПуть: {}\nШаг: {}'. format(path, step)) if visualize: graph.visualize()
def createGrpah4(i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12): g = gt.Graph(directed=True) a = g.add_vertex() b = g.add_vertex() c = g.add_vertex() d = g.add_vertex() if (i1 == '1'): g.add_edge(a, b) if (i2 == '1'): g.add_edge(a, c) if (i3 == '1'): g.add_edge(a, d) if (i4 == '1'): g.add_edge(b, a) if (i5 == '1'): g.add_edge(b, c) if (i6 == '1'): g.add_edge(b, d) if (i7 == '1'): g.add_edge(c, a) if (i8 == '1'): g.add_edge(c, b) if (i9 == '1'): g.add_edge(c, d) if (i10 == '1'): g.add_edge(d, a) if (i11 == '1'): g.add_edge(d, b) if (i12 == '1'): g.add_edge(d, c) return g
def create_mock_graph_tool(label='network_label', num_nodes=100, num_edges=100, data={}): edgeList = {} n = graph_tool.Graph() n.gp.label = n.new_gp("string") n.gp.label = label n.vp.name = n.new_vp("string") n.ep.id = n.new_ep("int") for n_id in range(num_nodes): v = n.add_vertex() n.vp.name[v] = hex(n_id) ID = num_nodes for e_id in range(num_edges): n1 = random.randint(0, num_nodes-1) n2 = random.randint(0, num_nodes-2) val = random.choice([1, 1.5, 'a', True]) edgeList[ID] = (n1, n2) e = n.add_edge(n.vertex(n1), n.vertex(n2)) n.ep.id[e] = ID n.ep.value = n.new_ep(GraphToolAdapter.get_gt_type(val)) # TODO: avoid destructive assiginment n.ep.value[e] = val ID += 1 for k, v in data.items(): if k not in n.gp: n.gp[k] = n.new_gp(GraphToolAdapter.get_gt_type(v)) n.gp[k] = v return n, edgeList
def communities_sbm(mob): #create graph g = gt.Graph(directed=True) weight = g.new_edge_property('int') vertices = list(np.unique(list(mob['start_quadkey'].unique()) + list(mob['end_quadkey'].unique()))) #map vertex names to integers v_map = dict(zip(vertices, range(0, len(vertices)))) v_map_i = {v: k for k, v in v_map.items()} #create an edgelist from dataframe (source, target, weight) edgelist = od_df(mob) #trying to convert weights to integers edgelist['weight'] = [int(x) for x in edgelist['weight']] edgelist['from'] = [v_map[x] for x in edgelist['from']] edgelist['to'] = [v_map[x] for x in edgelist['to']] edgelist = edgelist.to_numpy() #add edges to graph node_id = g.add_edge_list(edgelist, hashed=True, eprops=[weight]) #minimize nester block model state = gti.minimize.minimize_nested_blockmodel_dl(g, deg_corr=False, state_args = {'eweight':weight}) #extract partition for each level state = extract_nested_blockmodel(state, g, node_id, v_map_i) return(state)
def networkize_illuminaU133(X, gene_names): # read PPI network. print('reading the network...') table = read_csv(Globals.ppi_file, True) refseq_ids = get_column(table, 0) refseq_ids.extend(get_column(table, 3)) refseq_ids = list(set(refseq_ids)) interactions = np.array(table)[:, [0, 3]] del table print("extracting common genes between expressions and network...") usable_interaction_indices = [ i for i in range(interactions.shape[0]) if interactions[i, 0] in gene_names and interactions[i, 1] in gene_names ] interactions = interactions[usable_interaction_indices, :] del usable_interaction_indices genes = list(np.union1d(interactions[:, 0], interactions[:, 1])) gene_names = list(gene_names) gene_idx = [gene_names.index(genes[i]) for i in range(len(genes))] tmpX = X[:, gene_idx] print("creating graph from network data...") g = gt.Graph(directed=False) vlist = g.add_vertex(len(genes)) for i in range(interactions.shape[0]): tmp_e = g.add_edge(genes.index(interactions[i, 0]), genes.index(interactions[i, 1])) del tmp_e, vlist return (tmpX, g, np.array(genes))
def three_path(self): self.g_c.set_directed(False) sub_three1 = gt.Graph(directed=False) sub_three2 = gt.Graph(directed=False) for n in range(0, 4): sub_three1.add_vertex() sub_three2.add_vertex() edges1 = [[0, 1], [1, 2], [2, 3]] edges2 = [[0, 1], [1, 2], [1, 3]] sub_three1.add_edge_list(edges1) sub_three2.add_edge_list(edges2) sub_iso1 = subgraph_num(sub_three1, self.g_c) sub_iso2 = subgraph_num(sub_three2, self.g_c) num = int(sub_iso1 / 2) + int(sub_iso2 / 6) self.g_c.set_directed(True) return num
def shortest_paths(network): start = time.clock() _net = gt.Graph(network) _net.set_directed(False) counts, bins = st.distance_histogram(_net) print "time: {}".format(time.clock() - start) return counts, bins
def generate_graph_by_gt(after=None, before=None): submissions = [ s for s in Submission.objects.filter( id__in=[comment.submission_id for comment in Comment.objects.all()]).prefetch_related('author')] graph = gt.Graph() graph.vp['author'] = graph.new_vp('string') for submission in submissions: authors = set() if submission.created_at.replace(tzinfo=None) >= after and submission.created_at.replace(tzinfo=None) <= before: authors.add(submission.author.name) authors = authors | set( comment.author.name for comment in Comment.objects.filter( submission=submission, created_at__gte=after, created_at__lte=before).prefetch_related('author')) s_graph = complete_graph(len(authors)) s_graph.vertex_properties['author'] = s_graph.new_vp('string') s_graph.vertex_properties['author_idx'] = s_graph.new_vp('int') authors = list(authors) for author_idx, v in enumerate(s_graph.get_vertices()): s_graph.vertex_properties['author'][v] = authors[author_idx] rv = find_vertex(graph, graph.vp['author'], s_graph.vp['author'][v]) s_graph.vertex_properties['author_idx'][v] = graph.vertex_index[rv[0]] if rv else -1 graph, props = graph_union(graph, s_graph, s_graph.vp['author_idx'], [(graph.vp['author'], s_graph.vp['author'])]) graph.vp['author'] = props[0] return graph
def induce_graph(data, distance='manhattan_inv', invexp_factor=1): """Induce a graph from the dataset with distances as weights.""" # Prepare an empty undirected graph with weights graph = gt.Graph(directed=False) weights = graph.new_edge_property('double') graph.edge_properties['weights'] = weights # Split the distance string to detecet distance, *inv = distance.split('_') # Compute the pairwise distances distances = DISTANCES[distance](data) # If we want to take the inverse exponent, apply that as well if inv and inv[0] == 'inv': distances = invexp_factor * np.exp(-invexp_factor * distances) # Convert the distances from the upper triangular form distances = squareform(distances) # Finally, create a full graph with distances for i in range(distances.shape[0]): for j in range(i + 1, distances.shape[0]): graph.add_edge(i, j) weights[i, j] = distances[i][j] return graph
def test_no_weights(self): adjacency = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) # NetworkX no weights. graph_nx = nx.Graph() graph_nx.add_edge(0, 1) graph_nx.add_edge(1, 2) graph_pg = graphs.Graph.from_networkx(graph_nx) np.testing.assert_allclose(graph_pg.W.toarray(), adjacency) # NetworkX non-existent weight name. graph_nx.edges[(0, 1)]['weight'] = 2 graph_nx.edges[(1, 2)]['weight'] = 2 graph_pg = graphs.Graph.from_networkx(graph_nx) np.testing.assert_allclose(graph_pg.W.toarray(), 2 * adjacency) graph_pg = graphs.Graph.from_networkx(graph_nx, weight='unknown') np.testing.assert_allclose(graph_pg.W.toarray(), adjacency) # Graph-tool no weights. graph_gt = gt.Graph(directed=False) graph_gt.add_edge(0, 1) graph_gt.add_edge(1, 2) graph_pg = graphs.Graph.from_graphtool(graph_gt) np.testing.assert_allclose(graph_pg.W.toarray(), adjacency) # Graph-tool non-existent weight name. prop = graph_gt.new_edge_property("double") prop[(0, 1)] = 2 prop[(1, 2)] = 2 graph_gt.edge_properties["weight"] = prop graph_pg = graphs.Graph.from_graphtool(graph_gt) np.testing.assert_allclose(graph_pg.W.toarray(), 2 * adjacency) graph_pg = graphs.Graph.from_graphtool(graph_gt, weight='unknown') np.testing.assert_allclose(graph_pg.W.toarray(), adjacency)
def command_draw(self): """ Draws the current resulting paths as a directed graph. Usage: draw """ if self.last_res is None: return "No saved paths. Do a search before you try to draw them." edge_list = [[ t.replace('_', ' ') for t in self.db.get_titles_of_ids((val, path[ind + 1])) ] for path in self.last_res for ind, val in enumerate(path[:-1])] graph = gt.Graph() strings = graph.add_edge_list(edge_list, string_vals=True, hashed=True) stats.remove_parallel_edges(graph) fill_color = graph.new_vertex_property('vector<float>', val=[0, 0, 0.640625, 0.9]) fill_color[graph.vertex(0)] = [0, 0.640625, 0, 0.9] fill_color[graph.vertex(len(self.last_res[0]) - 1)] = [0.640625, 0, 0, 0.9] draw.interactive_window( graph, vertex_fill_color=fill_color, vertex_text=strings, vertex_text_position=graph.new_vertex_property('float', val=0), vertex_anchor=graph.new_vertex_property('int', val=0), geometry=(1600, 1200), vertex_font_size=graph.new_vertex_property('float', val=20))
def prepare_cora(directed=False): print("directed", directed) edges = np.genfromtxt('res/cora/cora.edges', dtype=np.int, delimiter=',')[:, :2] - 1 labels = np.genfromtxt('res/cora/cora.node_labels', dtype=np.int, delimiter=',')[:, 1] g = graph_tool.Graph(directed=directed) g.add_edge_list(edges) vfilt = graph_tool.topology.label_largest_component(g, directed=False) labels = labels[vfilt.a.astype(np.bool)] g = graph_tool.GraphView(g, vfilt=vfilt) g.purge_vertices() weight_prop = g.new_edge_property("int", val=1) #spc = shortest_path_cover_logn_apx(g, weight_prop) spc = pickle.load( open("res/cora/largest_comp_new_spc_" + str(directed) + ".p", "rb")) print("spc", len(spc)) pickle.dump( spc, open("res/cora/largest_comp_new_spc_" + str(directed) + ".p", "wb")) #spc = pickle.load(open("res/cora/largest_comp_new_spc_" + str(directed) + ".p", "rb")) return g, labels, spc
def make_dijkstra(joints, dtimes, vel_limits, acc_limits, verbose=False): virtual_start = (-1, -1) #falta velocidade inicial virtual_end = (-2, -1) #falta velocidade final adj = dijkstra_acc.DijkstraAdj(joints, dtimes) for jointsi in range(len(joints) - 1): for u in range(len(joints[jointsi])): for v in range(len(joints[jointsi + 1])): adj.add_link((jointsi, u), (jointsi + 1, v)) for joints0i in range(len(joints[0])): adj.add_link(virtual_start, (0, joints0i)) for jointsi in range(len(joints[-1])): adj.add_link((len(joints) - 1, jointsi), virtual_end) vs = dijkstra_acc.VirtualNode( (-1, -1), tuple(zeros(len(joints[0][0])))) #falta velocidade inicial ve = dijkstra_acc.VirtualNode( (-2, -1), tuple(zeros(len(joints[0][0])))) #falta velocidade final dtimes[0] = 1 cost = dijkstra_acc.DijkstraAccCost(dijkstra_acc.single_vel_distance, vs, ve, dtimes, vel_limits, acc_limits) graph = gt.Graph() weight = graph.new_ep("double") dist = graph.new_vp("double") graph_cost = graph.new_vp("double") point_velocity = graph.new_vp("object") graph.add_vertex(1) point_velocity[graph.vertex(0)] = vs astarvisitor = AstarVisitor(weight, graph, adj, cost, dist, graph_cost, point_velocity, ve) min_costs, predecessors = gt.search.astar_search(g=graph, weight=weight, dist_map=dist, source=graph.vertex(0), visitor=astarvisitor, implicit=True, cost_map=graph_cost) path = [] v = graph.vertex(predecessors[astarvisitor.target]) while v != graph.vertex(0): path = [point_velocity[v][0]] + path v = graph.vertex(predecessors[v]) joint_path = [] for i in range(len(path)): joint_index = path[i][0] joint_configuration = path[i][1] joint_path.append(joints[joint_index][joint_configuration]) if verbose: return joint_path, path, min_costs[astarvisitor.target], adj, cost else: return joint_path
def bread_to_beer_graph(): """Returns a graph-tool Graph for the BreadtoBeer case""" G = gt.Graph(directed=True) G.add_vertex(6) vid = G.new_vertex_property("string") G.vertex_properties["id"] = vid G.vp.id[0] = 'Households' G.vp.id[1] = 'Incineration' G.vp.id[2] = 'Digester' G.vp.id[3] = 'Brewery' G.vp.id[4] = 'Supermarkets' G.vp.id[5] = 'Farm' flow = G.new_edge_property("object") G.edge_properties["flow"] = flow e = G.add_edge(G.vertex(0), G.vertex(1)) G.ep.flow[e] = { 'amount': 20, 'composition': { 'bread': 0.25, 'other waste': 0.75 } } e = G.add_edge(G.vertex(0), G.vertex(2)) G.ep.flow[e] = {'amount': 10, 'composition': {'bread': 1.0}} e = G.add_edge(G.vertex(3), G.vertex(2)) G.ep.flow[e] = {'amount': 20, 'composition': {'sludge': 1.0}} e = G.add_edge(G.vertex(3), G.vertex(4)) G.ep.flow[e] = {'amount': 40, 'composition': {'beer': 1.0}} e = G.add_edge(G.vertex(5), G.vertex(3)) G.ep.flow[e] = {'amount': 9, 'composition': {'barley': 1.0}} split = _split_flows(G) return split
def connected_components(edges, num_nodes): """ Run connected components on the graph encoded by 'edges' and num_nodes. The graph vertex IDs must be CONSECUTIVE. edges: ndarray, shape=(N,2), dtype=np.uint32 num_nodes: Integer, max_node+1. (Allows for graphs which contain nodes that are not referenced in 'edges'.) Returns: ndarray of shape (num_nodes,), labeled by component index from 0..C Note: Uses graph-tool if it's installed; otherwise uses networkx (slower). """ if _graph_tool_available: from graph_tool.topology import label_components g = gt.Graph(directed=False) g.add_vertex(num_nodes) g.add_edge_list(edges) cc_pmap, _hist = label_components(g) return cc_pmap.get_array() else: import networkx as nx g = nx.Graph() g.add_edges_from(edges) cc_labels = np.zeros((num_nodes, ), np.uint32) for i, component_set in enumerate(nx.connected_components(g)): cc_labels[np.array(list(component_set))] = i return cc_labels
def mtx_to_gt(ifname, cutoff): """ Convert distance matrix (csv file) to graphtools graph. Ignore edges below cutoff. --------------------- ifname - the input file name cutoff - the threshold --------------------- Output is a graphtools.Graph instance with approp edges. """ vprint(INFO, "Opening %s as graph tool object (thresh at %.2f)..."%(ifname, cutoff)) m, hdr, _ = read_mtx(ifname, transpose = False, rowname = True, colname = True) g = gt.Graph(directed = False) weight = g.new_edge_property("float") name = g.new_vertex_property("string") for i in range(len(hdr)): v = g.add_vertex() name[v] = hdr[i] for i in range(len(hdr)): for j in range(i+1, len(hdr)): if m[i,j] < cutoff: continue else: v, w = g.vertex(i), g.vertex(j) e = g.add_edge(v,w) weight[e] = m[i,j] g.edge_properties['weight'] = weight g.vertex_properties['name'] = name return g
def bond_graph(self): """ Calculate the `graph_tool.Graph` object corresponding to this molecule. Requires the graph_tool library to be installed Returns: graph_tool.Graph: the (undirected) graph of this molecule """ if hasattr(self, "_bond_graph"): return getattr(self, "_bond_graph") try: import graph_tool as gt except ImportError: raise RuntimeError( "Please install the graph_tool library for graph operations") if self.bonds is None: self.guess_bonds() g = gt.Graph(directed=False) v_el = g.new_vertex_property("int") g.add_edge_list(self.bonds.keys()) e_w = g.new_edge_property("float") v_el.a[:] = self.atomic_numbers g.vertex_properties["element"] = v_el e_w.a[:] = list(self.bonds.values()) g.edge_properties["bond_distance"] = e_w self._bond_graph = g return g
def favites_to_gt(contacts): # parse contact network g = gt.Graph(directed=True) for line in contacts: if isinstance(line, bytes): l = line.decode().strip() else: l = line.strip() if len(l) == 0 or l[0] == '#': continue assert l.startswith('NODE\t') or l.startswith( 'EDGE\t'), "Contact network is not in the FAVITES format" if l.startswith('NODE\t'): continue try: n, u, v, a, d = l.split() u = int(u) v = int(v) except: assert False, "Contact network is not in the FAVITES format" # add to graph g.add_edge(u, v) g.add_edge(v, u) return g
def subgraph_isomorphism_vertex_counts(edge_index, **kwargs): ##### vertex structural identifiers ##### subgraph_dict, induced, num_nodes = kwargs['subgraph_dict'], kwargs['induced'], kwargs['num_nodes'] directed = kwargs['directed'] if 'directed' in kwargs else False G_gt = gt.Graph(directed=directed) G_gt.add_edge_list(list(edge_index.transpose(1,0).cpu().numpy())) gt.stats.remove_self_loops(G_gt) gt.stats.remove_parallel_edges(G_gt) # compute all subgraph isomorphisms sub_iso = gt_topology.subgraph_isomorphism(subgraph_dict['subgraph'], G_gt, induced=induced, subgraph=True, generator=True) ## num_nodes should be explicitly set for the following edge case: ## when there is an isolated vertex whose index is larger ## than the maximum available index in the edge_index counts = np.zeros((num_nodes, len(subgraph_dict['orbit_partition']))) for sub_iso_curr in sub_iso: for i,node in enumerate(sub_iso_curr): # increase the count for each orbit counts[node, subgraph_dict['orbit_membership'][i]] +=1 counts = counts/subgraph_dict['aut_count'] counts = torch.tensor(counts) return counts
def get_distance_node_list(gtG, source_nodes, direction, weights=None): gtG_ = gt.Graph(gtG) v = gtG_.add_vertex() if weights is not None: weights = gtG_.edge_properties[weights] for s in source_nodes: e = gtG_.add_edge(s, int(v)) if weights is not None: weights[e] = 0. if direction == 'to': dist = gt.topology.shortest_distance( gt.GraphView(gtG_, reversed=True), source=gtG_.vertex(int(v)), target=None, weights=weights) elif direction == 'from': dist = gt.topology.shortest_distance( gt.GraphView(gtG_, reversed=False), source=gtG_.vertex(int(v)), target=None, weights=weights) dist = np.array(dist.get_array()) dist = dist[:-1] if weights is None: dist = dist-1 return dist
def convert(self, src_graph): ps = set() ls = [] for i, src_node in src_graph.items(): neighbors = src_node['neighbors'] label = src_node['label'] value = None if type(label) is tuple: value = label[0] else: value = int(label) if label != '' else -1 ls.append((i, value)) for j in neighbors: p = tuple(sorted([i, j])) ps.add(p) # no duplication!! # add edges to a graph dst_graph = graph_tool.Graph(directed=False) for p in ps: dst_graph.add_edge(p[0], p[1]) # add labels to a graph label_property = dst_graph.new_vertex_property('int') for i, label in ls: v = dst_graph.vertex(i) label_property[v] = label dst_graph.vp['label'] = label_property return dst_graph