def test_ricci_community_all_possible_clusterings(): G = nx.karate_club_graph() orc = OllivierRicci(G, exp_power=1, alpha=0.5) orc.compute_ricci_flow(iterations=40) cc = orc.ricci_community_all_possible_clusterings() cuts = [x[0] for x in cc] clusterings = [x[1] for x in cc] cuts_ans = [1.4196268583579972, 1.2196268583579943, 1.1446268583579933, 1.119626858357993, 1.0946268583579926] clusterings_ans = [{0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12: 0, 13: 0, 17: 0, 19: 0, 21: 0, 4: 1, 5: 1, 6: 1, 10: 1, 16: 1, 32: 2, 33: 2, 8: 2, 14: 2, 15: 2, 18: 2, 20: 2, 22: 2, 23: 2, 24: 2, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2}, {0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12: 0, 13: 0, 17: 0, 19: 0, 21: 0, 4: 1, 5: 1, 6: 1, 10: 1, 16: 1, 32: 2, 33: 2, 8: 2, 14: 2, 15: 2, 18: 2, 20: 2, 22: 2, 23: 2, 24: 2, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2}, {0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12: 0, 13: 0, 17: 0, 19: 0, 21: 0, 4: 1, 5: 1, 6: 1, 10: 1, 16: 1, 32: 2, 33: 2, 8: 2, 14: 2, 15: 2, 18: 2, 20: 2, 22: 2, 23: 2, 24: 2, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2}, {0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12: 0, 13: 0, 17: 0, 19: 0, 21: 0, 4: 1, 5: 1, 6: 1, 10: 1, 16: 1, 32: 2, 33: 2, 8: 2, 14: 2, 15: 2, 18: 2, 20: 2, 22: 2, 23: 2, 24: 2, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2}, {0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12: 0, 13: 0, 17: 0, 19: 0, 21: 0, 4: 1, 5: 1, 6: 1, 10: 1, 16: 1, 32: 2, 33: 2, 8: 2, 14: 2, 15: 2, 18: 2, 20: 2, 22: 2, 23: 2, 24: 2, 25: 2, 26: 2, 27: 2, 28: 2, 29: 2, 30: 2, 31: 2} ] npt.assert_array_almost_equal(cuts, cuts_ans) assert clusterings == clusterings_ans
def ricciCurvature(G, alpha=0.5): import time t0 = time.time() orc = OllivierRicci(G, alpha) orc.compute_ricci_curvature() H = orc.G t1 = time.time() print('Ricci curvature process computed in ' + str(t1 - t0) + ' seconds.') return H
def get_curvatures_as_dict(graph, method = "OTD"): graph.remove_edges_from(nx.selfloop_edges(graph)) orc = OllivierRicci(graph, alpha=0.5, verbose="INFO", method=method) s = time.time() G = orc.compute_ricci_curvature() time_elapsed = time.time() - s print ('time for curvature computation: {}'.format(time_elapsed)) curvatures = {e: G[e[0]][e[1]]["ricciCurvature"] for e in G.edges()} return curvatures, time_elapsed
def test_ricci_community(): G = nx.karate_club_graph() orc = OllivierRicci(G, exp_power=1, alpha=0.5) cut, clustering = orc.ricci_community() cut_ans = 1.116777972153555 clustering_ans = {0: 0, 1: 0, 2: 0, 3: 0, 7: 0, 9: 0, 11: 0, 12: 0, 13: 0, 17: 0, 19: 0, 21: 0, 4: 1, 5: 1, 6: 1, 10: 1, 16: 1, 8: 2, 30: 2, 32: 3, 33: 3, 14: 3, 15: 3, 18: 3, 20: 3, 22: 3, 23: 4, 24: 4, 25: 4, 26: 4, 27: 4, 28: 4, 29: 4, 31: 4} npt.assert_array_almost_equal(cut, cut_ans) assert clustering == clustering_ans
def test_compute_ricci_curvature_directed(): Gd = nx.DiGraph() Gd.add_edges_from([(0, 1), (1, 2), (2, 3), (1, 3), (3, 1)]) orc = OllivierRicci(Gd, method="OTD", alpha=0.5) Gout = orc.compute_ricci_curvature() rc = list(nx.get_edge_attributes(Gout, "ricciCurvature").values()) ans = [ -0.49999999999999956, -3.842615114990622e-11, 0.49999999996158007, 0.49999999992677135, 0.7499999999364129 ] npt.assert_array_almost_equal(rc, ans)
def test_compute_ricci_flow(): G = nx.karate_club_graph() orc = OllivierRicci(G, method="OTD", alpha=0.5) Gout = orc.compute_ricci_flow(iterations=3) rf = list(nx.get_edge_attributes(Gout, "weight").values()) ans = [0.584642, 1.222957, 0.828566, 1.893597, 2.179315, 2.179315, 0.814135, 1.647656, 1.893597, 0.906430, 0.916791, 0.798319, 0.760511, 0.829311, 0.760511, 2.477847, 0.937765, 0.681481, 0.612859, 0.568307, 0.675702, 0.702774, 0.675702, 1.484889, 0.843498, 0.753397, 1.098413, 0.868616, 0.646627, 2.061065, 1.425968, 1.924123, 0.292387, 0.487378, 0.446435, 0.509673, 0.101477, 0.108645, 0.509673, 0.246037, 0.246037, 0.228701, 1.309931, 1.213249, 1.317511, 2.149341, 0.712759, 0.811386, 0.712759, 0.811386, 0.712759, 0.811386, 2.245314, 0.712759, 0.811386, 0.712759, 0.811386, 0.947310, 0.518039, 0.857636, 1.525740, 1.429449, 0.180896, 0.692919, 0.724545, 0.639637, 0.281116, 1.427853, 1.622385, 0.807457, 1.386869, 1.372091, 1.320579, 1.324087, 1.276729, 1.843012, 1.721982, 0.412472] npt.assert_array_almost_equal(rf, ans)
def test_compute_ricci_curvature(): G = nx.karate_club_graph() orc = OllivierRicci(G, method="OTD", alpha=0.5) Gout = orc.compute_ricci_curvature() rc = list(nx.get_edge_attributes(Gout, "ricciCurvature").values()) ans = [0.111111, -0.143750, 0.041667, -0.114583, -0.281250, -0.281250, 0.062500, -0.200000, -0.114583, 0.062500, -0.000000, 0.062500, 0.062500, -0.031250, 0.062500, -0.427083, 0.044444, 0.166667, 0.194444, 0.244444, 0.166667, 0.111111, 0.166667, -0.041667, 0.050000, 0.125000, 0.100000, 0.100000, 0.200000, -0.175000, 0.033333, -0.233333, 0.416667, 0.250000, 0.216667, 0.291667, 0.500000, 0.500000, 0.291667, 0.375000, 0.375000, 0.375000, -0.025000, 0.011765, -0.044118, -0.288235, 0.125000, 0.088235, 0.125000, 0.088235, 0.125000, 0.088235, -0.254902, 0.125000, 0.088235, 0.125000, 0.088235, 0.100000, 0.225000, 0.200000, -0.066667, -0.076471, 0.500000, 0.125000, 0.083333, 0.166667, 0.375000, -0.073529, -0.147059, 0.166667, -0.068627, -0.041667, -0.014706, -0.041667, -0.044118, -0.166667, -0.122549, 0.267157] npt.assert_array_almost_equal(rc, ans)
def calculate_ricci_filtration( graph, useNodeWeight=True, attribute_out='f', alpha=0.5, ): """Calculate a filtration based on Ollivier's Ricci curvature for a given graph. The computation is done using the library GraphRicciCurvature Parameters ---------- graph: Input graph attribute_out: Specifies the attribute name for storing the result of the calculation. This name will pertain to *both* vertices and edges. alpha: Parameter used to compute the Ricci curvature. Was set to 0.5 by Zhao and Wang. Returns ------- Copy of the input graph, with vertex weights and edge weights added as attributes `attribute_out`, respectively. """ graph = ig.Graph.copy(graph) #Convert the graph to a networkx graph (so that the GraphRicciCurvature library can be used) G = networkx.Graph([(edge.source, edge.target, { 'weight': 1 }) for edge in graph.es]) orc = OllivierRicci(G, alpha=0.5, verbose="INFO") res = orc.compute_ricci_curvature() edge_weights = [] node_weights = [10] * len(graph.vs) for edge in graph.es: u = edge.source v = edge.target edge_weights.append(orc.G[u][v]["ricciCurvature"]) node_weights[u] = min(node_weights[u], orc.G[u][v]["ricciCurvature"]) node_weights[v] = min(node_weights[v], orc.G[u][v]["ricciCurvature"]) graph.es[attribute_out] = edge_weights if useNodeWeight: graph.vs[attribute_out] = node_weights else: graph.vs[attribute_out] = np.min(edge_weights) return graph
def ricci_curvature_weight_generator(graph, alpha): """ Function to retrieve the Ricci curvature for all of the edges. """ print(" ") print("Ricci curvature calculation started.") print(" ") graph_copy = graph.copy() graph_copy.remove_edges_from(nx.selfloop_edges(graph_copy)) orc = OllivierRicci(graph_copy, alpha=0.5) G = orc.compute_ricci_curvature() print("Curvature calculated") edges = nx.edges(graph) weights = {e: calculate_weigth(e, G, alpha) for e in tqdm(edges)} weights_prime = {(e[1], e[0]): value for e, value in weights.items()} weights.update(weights_prime) print(" ") return weights
def flow_and_show(graph, iterations, color_attribute = None): orf = OllivierRicci(graph, alpha=0.5, base=1, exp_power=0, proc=4, verbose="ERROR", weight="weight") print("Applying ricci flow for {} iterations".format(iterations)) plt.figure(1) G = orf.compute_ricci_flow(iterations=iterations) show_results(G) if color_attribute is not None: print('various projections of the original graph') my_mds_paths(graph, coloring_attribute=color_attribute) print('various projections of the graph after Ricci flow has been applied') my_mds_paths(G, coloring_attribute=color_attribute) else: print('various projections of the original graph') my_mds_paths(graph) print('various projections of the graph after Ricci flow has been applied') my_mds_paths(G) return G
def test_compute_ricci_curvature_ATD(): G = nx.karate_club_graph() orc = OllivierRicci(G, alpha=0.5, method="ATD", verbose="INFO") orc.compute_ricci_curvature() Gout = orc.compute_ricci_curvature() rc = list(nx.get_edge_attributes(Gout, "ricciCurvature").values()) ans = [ -0.343750, -0.437500, -0.265625, -0.250000, -0.390625, -0.390625, -0.195312, -0.443750, -0.250000, 0.000000, -0.140625, -0.287500, -0.109375, -0.291667, -0.109375, -0.640625, -0.311111, -0.175926, -0.083333, -0.166667, 0.000000, -0.166667, 0.000000, -0.333333, -0.241667, -0.137500, -0.220000, -0.125000, -0.160000, -0.400000, -0.200000, -0.479167, 0.020833, 0.041667, -0.100000, -0.041667, 0.055556, -0.062500, -0.041667, 0.000000, 0.000000, -0.075000, -0.275000, -0.300000, -0.176471, -0.464706, 0.000000, -0.073529, 0.000000, -0.073529, 0.000000, -0.073529, -0.421569, 0.000000, -0.073529, 0.000000, -0.073529, -0.200000, -0.200000, -0.125000, -0.291667, -0.335294, -0.055556, -0.208333, -0.194444, -0.194444, 0.062500, -0.176471, -0.375000, -0.166667, -0.245098, -0.197917, -0.227941, -0.250000, -0.294118, -0.430556, -0.455882, -0.355392 ] npt.assert_array_almost_equal(rc, ans)
def main(): # import an example NetworkX karate club graph G = nx.karate_club_graph() # compute the Ollivier-Ricci curvature of the given graph G orc = OllivierRicci(G, alpha=0.5, verbose="INFO") orc.compute_ricci_curvature() print( "Karate Club Graph: The Ollivier-Ricci curvature of edge (0,1) is %f" % orc.G[0][1]["ricciCurvature"]) # compute the Forman-Ricci curvature of the given graph G frc = FormanRicci(G) frc.compute_ricci_curvature() print("Karate Club Graph: The Forman-Ricci curvature of edge (0,1) is %f" % frc.G[0][1]["formanCurvature"]) # ----------------------------------- # Compute Ricci flow metric - Optimal Transportation Distance G = nx.karate_club_graph() orc_OTD = OllivierRicci(G, alpha=0.5, method="OTD", verbose="INFO") orc_OTD.compute_ricci_flow(iterations=10)
print(dataid) p_inter=inter_offset+(dataid%prob_num)*inter_step p_intra=intra_offset+(dataid/prob_num)*intra_step inter_idx=adj>p_inter intra_idx=adj>p_intra inter_idx[c4:,c3:c4],inter_idx[c3:c4,c4:]=False,False inter_idx[c1:c3,c3:c4],inter_idx[c3:c4,c1:c3]=False,False inter_idx[c1:c4,c4:],inter_idx[c4:,c1:c4]=False,False inter_idx[:c1,:c1]=intra_idx[:c1,:c1] inter_idx[c1:c2,c1:c2]=intra_idx[c1:c2,c1:c2] inter_idx[c2:c3,c2:c3]=intra_idx[c2:c3,c2:c3] inter_idx[c3:c4,c3:c4]=intra_idx[c3:c4,c3:c4] inter_idx[c4:c5,c4:c5]=intra_idx[c4:c5,c4:c5] adj_b=inter_idx adj_b.flat[:end:n_num+1]=False edge_index=[(i,j) for i in range(n_num) for j in range(n_num) if adj_b[i,j]] Gd=nx.Graph() Gd.add_edges_from(edge_index) Gd_OT=OllivierRicci(Gd, alpha=0.5, method="OTD", verbose="INFO") Gd = Gd_OT.compute_ricci_curvature() ricci_list=[] for n1,n2 in Gd.edges(): ricci_list.append([n1,n2,Gd[n1][n2]['ricciCurvature']]) ricci_list.append([n2,n1,Gd[n1][n2]['ricciCurvature']]) ricci_list=sorted(ricci_list) w_mul=torch.tensor([i[2] for i in ricci_list]) data=Data(x=x,edge_index=torch.tensor(edge_index).transpose(0,1),y=y) data.w_mul=torch.tensor(w_mul,dtype=torch.float) data_list[dataid]=data SynDataset(root='../data/Rand_nnodes'+str(n_num),name='Rand_nnodes'+str(n_num),data_list=data_list)
frc_temp.append(G) np.save(path1+"lig_IDM_graphs/"+pdbid+"_ollivier_15_C_ligand.npy", orc_temp) np.save(path1+"lig_IDM_graphs/"+pdbid+"_forman_15_C_ligand.npy", frc_temp) """ for i in range(len(all_comb)): print("Processing: {:20}".format(comb_d[i])) for pdbid in train_list_2013["arr_0"]: print("Processing v2013: {:4}".format(pdbid)) orc_temp = [] frc_temp = [] for c in np.linspace(0, 15, 150): G = gen_lignet(all_comb[i], pdbid, c, path2) if G.number_of_edges() > 0: orc = OllivierRicci(G, alpha=0.5) orc.compute_ricci_curvature() frc = FormanRicci(G) frc.compute_ricci_curvature() orc_temp.append(orc.G) frc_temp.append(frc.G) else: orc_temp.append(G) frc_temp.append(G) nx.write_gpickle([orc_temp, frc_temp], path2 + "lig_IDM_graphs/" + pdbid + "_15_" + comb_d[i] + "_ligand.gpickle") for pdbid in test_list_2013["arr_0"]: print("Processing v2013: ", pdbid) orc_temp = []
def flow(graph, iterations): orf = OllivierRicci(graph, alpha=0.5, base=1, exp_power=0, proc=4, verbose="ERROR", weight="weight") G = orf.compute_ricci_flow(iterations=iterations) return G
for tup in orc.G.edges: i, j = tup[0], tup[1] ollivier_curv_vals[i][j] = map_curvature_val( orc.G[i][j]['ricciCurvature'], alpha=4) forman_curv_vals[i][j] = map_curvature_val( frc.G[i][j]['formanCurvature'], alpha=4) else: ########################################### TRYING TO REPLACE A WITH RICCI CURVATURE ########################################### G = G_from_data_file(dataset) args.data = dataset X, Y, A, idx_train, idx_val, idx_test = utils.load_data(args) ollivier_curv_vals, forman_curv_vals = csr_matrix( A.shape).toarray(), csr_matrix(A.shape).toarray() orc = OllivierRicci(G, alpha=0.5, verbose="INFO") orc.compute_ricci_curvature() frc = FormanRicci(G) frc.compute_ricci_curvature() for tup in orc.G.edges: i, j = tup[0], tup[1] ollivier_curv_vals[i][j] = map_curvature_val( orc.G[i][j]['ricciCurvature'], alpha=4) forman_curv_vals[i][j] = map_curvature_val( frc.G[i][j]['formanCurvature'], alpha=4) K = A.shape[1] if X is None else X.shape[0] nC = Y.shape[1] W = None if args.weighted: W = utils.calc_class_weights(Y[..., idx_train, :])
import networkx as nx from GraphRicciCurvature.OllivierRicci import OllivierRicci from GraphRicciCurvature.FormanRicci import FormanRicci # import an example NetworkX karate club graph G = nx.karate_club_graph() # compute the Ollivier-Ricci curvature of the given graph G orc = OllivierRicci(G, alpha=0.5, verbose="INFO") orc.compute_ricci_curvature() print("Karate Club Graph: The Ollivier-Ricci curvature of edge (0,1) is %f" % orc.G[0][1]["ricciCurvature"]) # compute the Forman-Ricci curvature of the given graph G frc = FormanRicci(G) frc.compute_ricci_curvature() print("Karate Club Graph: The Forman-Ricci curvature of edge (0,1) is %f" % frc.G[0][1]["formanCurvature"]) # ----------------------------------- # Construct a directed graph example Gd = nx.DiGraph() Gd.add_edges_from([(1, 2), (2, 3), (3, 4), (2, 4), (4, 2)]) # compute the Ollivier-Ricci curvature of the given directed graph Gd orc_directed = OllivierRicci(Gd) orc_directed.compute_ricci_curvature() for n1, n2 in Gd.edges(): print("Directed Graph: The Ollivier-Ricci curvature of edge(%d,%d) id %f" % (n1, n2, orc_directed.G[n1][n2]["ricciCurvature"])) # compute the Forman-Ricci curvature of the given directed graph Gd frc_directed = FormanRicci(Gd)
def create_train(threshold, cutoff, num_of_gaps): # Creates a feature vector of x with dimensions: number of PDBIDs x 36 combinations x 101 x 20. #print("Creating Training Set...") #feature_x = [] train_list = np.load("ORC PLB IDM 2016/train_list.npz", allow_pickle=True) for i in range(a, b + 1): pdbid = train_list["arr_0"][i] print("Processing: ", pdbid) data = np.load("ORC PLB IDM 2016/Complexes/" + pdbid + "_complex_" + str(cutoff) + ".npz", allow_pickle=True) pro_data, lig_data = data['PRO'], data['LIG'] pro_hvy_atom = ['C', 'N', 'O', 'S'] lig_hvy_atom = ['C', 'N', 'O', 'S', 'P', 'F', 'Cl', 'Br', 'I'] pro_coords, lig_coords = [], [] for p in pro_hvy_atom: temp = [] for proatm in pro_data: for j in range(len(proatm['typ'])): pt = str(proatm['typ'][j]).replace(" ", "") pt = pt.upper() if pt == p: temp.append(proatm['pos'][j]) pro_coords.append(temp) for q in lig_hvy_atom: temp = [] for ligatm in lig_data: for j in range(len(ligatm['typ'])): lt = str(ligatm['typ'][j]).replace(" ", "") lt = lt.upper() if lt == q: temp.append(ligatm['pos'][j]) lig_coords.append(temp) X_graphs = [] for i in range(0, len(pro_coords)): for j in range(0, len(lig_coords)): temp_feature = [] # generate graph with protein and ligand atom combination and specified cutoff distance for l in np.linspace(0, threshold, num_of_gaps): #l = 7.4 #print(pro_hvy_atom[i],"--",lig_hvy_atom[j], ": ", l, end="\r") G = nx.Graph() G = gen_graph(pro_coords[i], lig_coords[j], pro_hvy_atom[i], lig_hvy_atom[j], l) #vertices = np.zeros(G.number_of_nodes()) if G.number_of_edges() > 0: orc = OllivierRicci(G, alpha=0.5) orc.compute_ricci_curvature() temp_feature.append(orc.G) else: temp_feature.append(G) """ for v in orc.G.nodes(): try: vertices[v] = orc.G.nodes[v]["ricciCurvature"] except: vertices[v] = 0 # Binning the vertex ORCs index = np.linspace(-1, 1, num_of_bins) bins = np.zeros(num_of_bins) for v in range(len(vertices)): for ind in range(len(index)-1): if vertices[v] >= index[ind] and vertices[v] < index[ind+1]: bins[ind] += 1 temp_feature.append(bins) """ X_graphs.append(temp_feature) #feature_x.append(X_feature) np.save( "ORC PLB IDM 2016/train_graphs/" + pdbid + "_" + str(cutoff) + "_" + str(threshold) + ".npy", X_graphs)
def test_compute_ricci_curvature_edges(): G = nx.karate_club_graph() orc = OllivierRicci(G, method="OTD", alpha=0.5) output = orc.compute_ricci_curvature_edges([(0, 1)]) npt.assert_almost_equal(output[0, 1], 0.111111)
from nodemass import undirected_to_dag from surgery import surgery from display import show_results from animate_surgery import simple_update, simple_animation G = nx.watts_strogatz_graph(32, 4, 0.75) H = undirected_to_dag(G) plt.clf() nx.draw_shell(H, with_labels=True) plt.savefig('Hstart.png') orc = OllivierRicci(H, alpha=0.5, beta=1, delta=0, base=1, exp_power=0, proc=4, verbose="INFO") G_orc = orc.G.copy() orf = OllivierRicci(H, alpha=0.5, beta=1, delta=0, base=1, exp_power=0, proc=4, verbose="INFO") orf.compute_ricci_flow(iterations=50) G_rf = orf.G.copy(G)
def compute_ricci_curvature(graph): graph_copy = graph.copy() graph_copy.remove_edges_from(nx.selfloop_edges(graph_copy)) orc = OllivierRicci(graph_copy, alpha=0.5) G = orc.compute_ricci_curvature() return G