Giter VIP home page Giter VIP logo

graphriccicurvature's Introduction

GraphRicciCurvature

A Python library to compute Discrete Ricci curvature, Ricci flow, and Ricci community on NetworkX graph.

Open In Colab Binder PyPI version Build Status Documentation Status Downloads License


This work computes the Ollivier-Ricci Curvature[Ni], Ollivier-Ricci Flow[Ni2,Ni3], Forman-Ricci Curvature(or Forman curvature)[Sreejith, Samal], and Ricci community[Ni3] detected by Ollivier-Ricci flow metric.

Curvature is a geometric property to describe the local shape of an object. If we draw two parallel paths on a surface with positive curvature like a sphere, these two paths move closer to each other while for a negatively curved surface like a saddle, these two paths tend to be apart. Currently there are multiple ways to discretize curvature on graph, in this library, we include two of the most frequently used discrete Ricci curvature: Ollivier-Ricci curvature which is based on optimal transportation theory and Forman-Ricci curvature which is base on CW complexes.

In [Ni], edge Ricci curvature is observed to play an important role in the graph structure. An edge with positive curvature represents an edge within a cluster, while a negatively curved edge tent to be a bridge within clusters. Also, negatively curved edges are highly related to graph connectivity, with negatively curved edges removed from a connected graph, the graph soon become disconnected.

Ricci flow is a process to uniformized the edge Ricci curvature of the graph. For a given graph, the Ricci flow gives a "Ricci flow metric" on each edge as edge weights, such that under these edge weights, the Ricci curvature of the graph is mostly equal everywhere. In [Ni3], this "Ricci flow metric" is shown to be able to detect communities.

Both Ricci curvature and Ricci flow metric can act as a graph fingerprint for graph classification. The different graph gives different edge Ricci curvature distributions and different Ricci flow metric.

Video demonstration of Ricci flow for community detection:

Package Requirement

  • NetworkX >= 2.0 (Based Graph library)
  • NetworKit >= 6.1 (Shortest path algorithm)
  • NumPy (POT support)
  • POT (For optimal transportation distance)
  • python-louvain (For faster modularity computation)

Installation

Installing via pip

pip3 install [--user] GraphRicciCurvature
  • From version 0.4.0, NetworKit is required to compute shortest path for density distribution. If the installation of NetworKit failed, please refer to NetworKit' Installation instructions.

Upgrading via pip

To run with the latest code for the best performance, upgrade GraphRicciCurvature to the latest version with pip:

pip3 install [--user] --upgrade GraphRicciCurvature

Getting Started

  • Check the jupyter notebook tutorial on nbviewer or github for a walk through for the basic usage of Ricci curvature, Ricci flow, and Ricci flow for community detection.
  • Or you can run it in directly on binder (no account required) or Google colab (Faster but Google account required).
  • Check the Documentations.
  • Try out sample graphs with precomputed Ricci curvature/flow.

Simple Example

import networkx as nx
from GraphRicciCurvature.OllivierRicci import OllivierRicci
from GraphRicciCurvature.FormanRicci import FormanRicci

print("\n- Import an example NetworkX karate club graph")
G = nx.karate_club_graph()

print("\n===== Compute the Ollivier-Ricci curvature of the given graph G =====")
# 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"])

print("\n===== 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"])

# -----------------------------------
print("\n=====  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("\n=====  Compute Ricci community - by Ricci flow =====")
clustering = orc_OTD.ricci_community()

More example in example.py.


Related Works

Reference

[Ni]: Ni, C.-C., Lin, Y.-Y., Gao, J., Gu, X., and Saucan, E. "Ricci curvature of the Internet topology" (Vol. 26, pp. 2758–2766). Presented at the 2015 IEEE Conference on Computer Communications (INFOCOM), IEEE. arXiv

[Ni2]: Ni, C.-C., Lin, Y.-Y., Gao, J., and Gu, X. "Network Alignment by Discrete Ollivier-Ricci Flow", Graph Drawing 2018, arXiv

[Ni3]: Ni, C.-C., Lin, Y.-Y., Luo, F. and Gao, J. "Community Detection on Networks with Ricci Flow", Scientific Reports 9, 9984 (2019), arXiv

[Sreejith]: Sreejith, R. P., Karthikeyan Mohanraj, Jürgen Jost, Emil Saucan, and Areejit Samal. "Forman Curvature for Complex Networks." Journal of Statistical Mechanics: Theory and Experiment 2016 (6). IOP Publishing: 063206. arxiv

[Samal]: Samal, A., Sreejith, R.P., Gu, J. et al. "Comparative analysis of two discretizations of Ricci curvature for complex networks." Scientific Report 8, 8650 (2018). arXiv

Contact

Please contact Chien-Chun Ni.

Cite

If you use this code in your research, please considering cite our paper:

@article{ni2019community,
  title={Community detection on networks with ricci flow},
  author={Ni, Chien-Chun and Lin, Yu-Yao and Luo, Feng and Gao, Jie},
  journal={Scientific reports},
  volume={9},
  number={1},
  pages={1--12},
  year={2019},
  publisher={Nature Publishing Group}
}

graphriccicurvature's People

Contributors

calincru avatar saibalmars avatar samuelbarrett1234 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphriccicurvature's Issues

NetworkKit attribute issue causes ORC to fail

Hello!

Thanks for assembling this module! I'm trying to run the tutorial notebook (https://github.com/saibalmars/GraphRicciCurvature/blob/master/notebooks/tutorial.ipynb) and it threw an error on the 6th cell: orc.compute_ricci_curvature(). The issue listed was AttributeError: 'networkit.graph.Graph' object has no attribute 'neighbors'. When I looked at the NetworkKit documentation, it seems that neighbors is a deprecated field starting in version 6.0 https://networkit.github.io/news.html (current version is 8.0). I was also able to replicate the issue by running the notebook in the Google Collab link listed at the top of the notebook.

I've attached the full error log as well for your convenience. Let me know if there's anything else you'd like to see from my end.

Thanks!
Anish

RemoteTraceback                           Traceback (most recent call last)
RemoteTraceback: 
"""
Traceback (most recent call last):
  File "/Users/[username]/anaconda3/envs/neuro/lib/python3.7/multiprocessing/pool.py", line 121, in worker
    result = (True, func(*args, **kwds))
  File "/Users/[username]/anaconda3/envs/neuro/lib/python3.7/multiprocessing/pool.py", line 44, in mapstar
    return list(map(*args))
  File "/Users/[username]/[folder]/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py", line 354, in _wrap_compute_single_edge
    return _compute_ricci_curvature_single_edge(*stuff)
  File "/Users/[username]/[folder]/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py", line 342, in _compute_ricci_curvature_single_edge
    x, y, d = _distribute_densities(source, target)
  File "/Users/[username]/[folder]/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py", line 138, in _distribute_densities
    x, source_topknbr = _get_single_node_neighbors_distributions(source, "successors")
  File "/Users/[username]/[folder]/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py", line 79, in _get_single_node_neighbors_distributions
    neighbors = _Gk.neighbors(node)
AttributeError: 'networkit.graph.Graph' object has no attribute 'neighbors'
"""

The above exception was the direct cause of the following exception:

AttributeError                            Traceback (most recent call last)
<ipython-input-6-b39f42f3b911> in <module>
----> 1 orc.compute_ricci_curvature()

~[username]/[folder]/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py in compute_ricci_curvature(self)
    762                                           proc=self.proc, chunksize=self.chunksize, cache_maxsize=self.cache_maxsize,
    763                                           shortest_path=self.shortest_path,
--> 764                                           nbr_topk=self.nbr_topk)
    765         return self.G
    766 

~[username]/[folder]/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py in _compute_ricci_curvature(G, weight, **kwargs)
    502 
    503     # compute Ricci curvature for all edges
--> 504     edge_ricci = _compute_ricci_curvature_edges(G, weight=weight, **kwargs)
    505 
    506     # Assign edge Ricci curvature from result to graph G

~[username]/[folder]/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py in _compute_ricci_curvature_edges(G, weight, edge_list, alpha, method, base, exp_power, proc, chunksize, cache_maxsize, shortest_path, nbr_topk)
    473     # Convert edge index from nk back to nx for final output
    474     output = {}
--> 475     for rc in result:
    476         for k in list(rc.keys()):
    477             output[(nk2nx_ndict[k[0]], nk2nx_ndict[k[1]])] = rc[k]

~/anaconda3/envs/neuro/lib/python3.7/multiprocessing/pool.py in <genexpr>(.0)
    352                     result._set_length
    353                 ))
--> 354             return (item for chunk in result for item in chunk)
    355 
    356     def apply_async(self, func, args=(), kwds={}, callback=None,

~/anaconda3/envs/neuro/lib/python3.7/multiprocessing/pool.py in next(self, timeout)
    746         if success:
    747             return value
--> 748         raise value
    749 
    750     __next__ = next                    # XXX

AttributeError: 'networkit.graph.Graph' object has no attribute 'neighbors'```

Warning: numerical errors at iteration 0

I was trying to use ORC to detect communities in a weighted undirected graph. I encountered two errors:

  • No cutoff point found!

  • Message: 'Neighbor weight sum too small, list:'
    Arguments: ([(0.0, 1), (0.0, 2), (0.0, 3), (0.0, 4), (0.0, 5), (0.0, 6), (0.0, 7), (0.0, 8), (0.0, 9), (0.0, 10), (0.0, 11), (0.0, 12), (0.0, 13), (0.0, 14), (0.0, 15), (0.0, 16), (0.0, 17),)
    Traceback (most recent call last):
    Message: 'Neighbor weight sum too small, list:'
    Arguments: ([(0.0, 0), (0.0, 501), (0.0, 502), (0.0, 503), (0.0, 504), (0.0, 505), (0.0, 506), (0.0, 507), (0.0, 508), (0.0, 509), (0.0, 510), (0.0, 511), (0.0, 512), )
    Process ForkPoolWorker-1:
    Process ForkPoolWorker-6:
    Process ForkPoolWorker-2:

Any help will be highly appreciated!

AttributeError: module 'community' has no attribute 'modularity'

AttributeError Traceback (most recent call last)
in ()
----> 1 cc = orc_football.ricci_community()

2 frames
/usr/local/lib/python3.7/dist-packages/GraphRicciCurvature/OllivierRicci.py in ricci_community(self, cutoff_step, drop_threshold)
838 """
839
--> 840 cc = self.ricci_community_all_possible_clusterings(cutoff_step=cutoff_step, drop_threshold=drop_threshold)
841 assert cc, "No clustering found!"
842

/usr/local/lib/python3.7/dist-packages/GraphRicciCurvature/OllivierRicci.py in ricci_community_all_possible_clusterings(self, cutoff_step, drop_threshold)
882 logger.info("Ricci flow detected, start cutting graph into community...")
883 cut_guesses =
--> 884 get_rf_metric_cutoff(self.G, weight=self.weight, cutoff_step=cutoff_step, drop_threshold=drop_threshold)
885 assert cut_guesses, "No cutoff point found!"
886

/usr/local/lib/python3.7/dist-packages/GraphRicciCurvature/util.py in get_rf_metric_cutoff(G_origin, weight, cutoff_step, drop_threshold)
96 clustering = {c: idx for idx, comp in enumerate(nx.connected_components(G)) for c in comp}
97 # Compute modularity
---> 98 modularity.append(community_louvain.modularity(clustering, G, weight))
99
100 good_cuts = []

AttributeError: module 'community' has no attribute 'modularity'

Calling function ricci_community() has some problem (trying to replicate the tutorial notebook). Maybe the solution is simply this? STACK OVERFLOW Attribute error community has no attribute

RuntimeError and NameError

Hi, maybe there are some of my stupid mistakes.

When I run example.py,it The following error occurred.

    RuntimeError:
    An attempt has been made to start a new process before the
    current process has finished its bootstrapping phase.

    This probably means that you are not using fork to start your
    child processes and you have forgotten to use the proper idiom
    in the main module:

        if __name__ == '__main__':
            freeze_support()
            ...

    The "freeze_support()" line can be omitted if the program
    is not going to be frozen to produce an executable

When I run tutorial notebook,it didn‘t work.

RemoteTraceback Traceback (most recent call last)
RemoteTraceback:
"""
Traceback (most recent call last):
File "C:\Users\Administrator\Anaconda3\lib\multiprocessing\pool.py", line 121, in worker
result = (True, func(*args, **kwds))
File "C:\Users\Administrator\Anaconda3\lib\site-packages\graphriccicurvature-0.3.1-py3.7.egg\GraphRicciCurvature\OllivierRicci.py", line 279, in _wrap_compute_single_edge
return _compute_ricci_curvature_single_edge(*stuff)
File "C:\Users\Administrator\Anaconda3\lib\site-packages\graphriccicurvature-0.3.1-py3.7.egg\GraphRicciCurvature\OllivierRicci.py", line 250, in _compute_ricci_curvature_single_edge
if _apsp[source][target] < EPSILON:
NameError: name '_apsp' is not defined
"""

The above exception was the direct cause of the following exception:

NameError Traceback (most recent call last)
in
----> 1 orc.compute_ricci_curvature()
2 G_orc = orc.G.copy() # save an intermediate result

~\Anaconda3\lib\site-packages\graphriccicurvature-0.3.1-py3.7.egg\GraphRicciCurvature\OllivierRicci.py in compute_ricci_curvature(self)
511 alpha=self.alpha, method=self.method,
512 base=self.base, exp_power=self.exp_power,
--> 513 proc=self.proc, chunksize=self.chunksize)
514 return self.G
515

~\Anaconda3\lib\site-packages\graphriccicurvature-0.3.1-py3.7.egg\GraphRicciCurvature\OllivierRicci.py in _compute_ricci_curvature(G, weight, **kwargs)
356
357 # Assign edge Ricci curvature from result to graph G
--> 358 for rc in edge_ricci:
359 for k in list(rc.keys()):
360 source, target = k

~\Anaconda3\lib\multiprocessing\pool.py in next(self, timeout)
746 if success:
747 return value
--> 748 raise value
749
750 next = next # XXX

NameError: name '_apsp' is not defined

Platform

  • OS: [e.g. Windows]
  • Python [e.g. 3.7]
  • Version [e.g. latest]

Clustering stochastic block model graphs

Hello,

thanks for developing this interesting algorithm!

I'm trying to use your algorithm to cluster stochastic blockmodel graphs, so far with little success.

I used this networkx function to generate the SBM. The parameters are set suck that the average degree is approx. 3.

G = nx.planted_partition_graph(2, 500, 0.00596, 4e-05)

Following your tutorial .ipynb, I do the following to compute the Ricci flow

ricci_flow = OllivierRicci(G,alpha=0.5)
ricci_flow.compute_ricci_flow(iterations=100)

and finally

cc = ricci_flow.ricci_community()

to obtain the clusters.

However, the results I got are not so nice.

Could you please advise me on how to increase the accuracy? Alternatively, could you please share the script you used to generate the SBM results in your paper?

Thanks very much!

IndexError: list index out of range

Hi,I use the latest GraphRicciCurvature v0.4.4,the jupyter notebook demo works well.But when I try to replace Karate_club dataset with my own dataset by

G=nx.read_adjlist("/home/seie/cora.cites")
print(nx.info(G))

I get right information:

Name: Type: Graph Number of nodes: 339 Number of edges: 457 Average degree: 2.8232

Then,I call the method

orc.compute_ricci_curvature()
G_orc = orc.G.copy()

A error happens:

RemoteTraceback                           Traceback (most recent call last)
RemoteTraceback: 
"""
Traceback (most recent call last):
  File "/home/seie/anaconda3/lib/python3.7/multiprocessing/pool.py", line 121, in worker
    result = (True, func(*args, **kwds))
  File "/home/seie/anaconda3/lib/python3.7/multiprocessing/pool.py", line 44, in mapstar
    return list(map(*args))
  File "/home/seie/anaconda3/lib/python3.7/site-packages/GraphRicciCurvature/OllivierRicci.py", line 365, in _wrap_compute_single_edge
    return _compute_ricci_curvature_single_edge(*stuff)
  File "/home/seie/anaconda3/lib/python3.7/site-packages/GraphRicciCurvature/OllivierRicci.py", line 348, in _compute_ricci_curvature_single_edge
    x, y, d = _distribute_densities(source, target)
  File "/home/seie/anaconda3/lib/python3.7/site-packages/GraphRicciCurvature/OllivierRicci.py", line 137, in _distribute_densities
    x, source_topknbr = _get_single_node_neighbors_distributions(source, "successors")
  File "/home/seie/anaconda3/lib/python3.7/site-packages/GraphRicciCurvature/OllivierRicci.py", line 91, in _get_single_node_neighbors_distributions
    heapq.heappush(heap_weight_node_pair, (_base ** (-_get_pairwise_sp(node, nbr) ** _exp_power), nbr))
  File "/home/seie/anaconda3/lib/python3.7/site-packages/GraphRicciCurvature/OllivierRicci.py", line 198, in _get_pairwise_sp
    return _apsp[source][target]
IndexError: list index out of range
"""

The above exception was the direct cause of the following exception:

IndexError                                Traceback (most recent call last)
<ipython-input-183-21532f2f29e1> in <module>
----> 1 orc.compute_ricci_curvature()
      2 G_orc = orc.G.copy()  # save an intermediate result

~/anaconda3/lib/python3.7/site-packages/GraphRicciCurvature/OllivierRicci.py in compute_ricci_curvature(self)
    768                                           proc=self.proc, chunksize=self.chunksize, cache_maxsize=self.cache_maxsize,
    769                                           shortest_path = self.shortest_path,
--> 770                                           nbr_topk=self.nbr_topk)
    771         return self.G
    772 

~/anaconda3/lib/python3.7/site-packages/GraphRicciCurvature/OllivierRicci.py in _compute_ricci_curvature(G, weight, **kwargs)
    517 
    518     # compute Ricci curvature for all edges
--> 519     edge_ricci = _compute_ricci_curvature_edges(G, weight=weight, **kwargs)
    520 
    521     # Assign edge Ricci curvature from result to graph G

~/anaconda3/lib/python3.7/site-packages/GraphRicciCurvature/OllivierRicci.py in _compute_ricci_curvature_edges(G, weight, edge_list, alpha, method, base, exp_power, proc, chunksize, cache_maxsize, shortest_path, nbr_topk)
    483     # Convert edge index from nk back to nx for final output
    484     output = {}
--> 485     for rc in result:
    486         for k in list(rc.keys()):
    487             output[(nk2nx_ndict[k[0]], nk2nx_ndict[k[1]])] = rc[k]

~/anaconda3/lib/python3.7/multiprocessing/pool.py in <genexpr>(.0)
    352                     result._set_length
    353                 ))
--> 354             return (item for chunk in result for item in chunk)
    355 
    356     def apply_async(self, func, args=(), kwds={}, callback=None,

~/anaconda3/lib/python3.7/multiprocessing/pool.py in next(self, timeout)
    746         if success:
    747             return value
--> 748         raise value
    749 
    750     __next__ = next                    # XXX

IndexError: list index out of range

Please help me to solve this problem.

Is this can work with Digraph?

Hello, here is my problem ,when I want to work with Digraph , I got some error message. So I want to know if it can work with Digraph. thanks for you browsing! (^_^)

Kernel dies on my MacBook and multiprocess not run on Windows 10

Hi,

I'm trying to run this package on both my MacBook and Windows 10 machines. However, I cannot get it run on either one.
I'm trying with codes in your example.py, the first example using OllivierRicci().

On my MacBook, the kernel dies as soon as I run 'orc.compute_ricci_curvature()'.
On my Windows 10 desktop, I have to use 'spawn' for multiprocessing as neither 'fork' nor 'forkserver' is available for Windows. The program just hangs in the same line, 'orc.compute_ricci_curvature()'.

Is there any way to get around these issues, on any of the machines? Or this package only runs on particular machines?

Many thanks in advance!

I can't install this package(https://github.com/saibalmars/GraphRicciCurvature.git)

I'm try install with: pip install git+https://github.com/saibalmars/GraphRicciCurvature.git
But result in:
Collecting git+https://github.com/saibalmars/GraphRicciCurvature.git
Cloning https://github.com/saibalmars/GraphRicciCurvature.git to /private/var/folders/yj/cx50wr6972528jw1r3vnr2xc0000gn/T/pip-req-build-_j8hsf6u
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "/anaconda3/lib/python3.6/tokenize.py", line 452, in open
buffer = _builtin_open(filename, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '/private/var/folders/yj/cx50wr6972528jw1r3vnr2xc0000gn/T/pip-req-build-_j8hsf6u/setup.py'

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/yj/cx50wr6972528jw1r3vnr2xc0000gn/T/pip-req-build-_j8hsf6u/

IndexError: invalid index to scalar variable

When I run the example.py, I encounter this error:
/root/miniconda3/lib/python3.8/site-packages/ot/bregman.py:517: UserWarning: Sinkhorn did not converge. You might want to increase the number of iterations numItermax or the regularization parameter reg.
warnings.warn("Sinkhorn did not converge. You might want to "
/root/miniconda3/lib/python3.8/site-packages/ot/bregman.py:517: UserWarning: Sinkhorn did not converge. You might want to increase the number of iterations numItermax or the regularization parameter reg.
warnings.warn("Sinkhorn did not converge. You might want to "
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "/root/miniconda3/lib/python3.8/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
File "/root/miniconda3/lib/python3.8/multiprocessing/pool.py", line 48, in mapstar
return list(map(*args))
File "/apdcephfs/share_1437072/rayan/jobs/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py", line 352, in _wrap_compute_single_edge
return _compute_ricci_curvature_single_edge(*stuff)
File "/apdcephfs/share_1437072/rayan/jobs/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py", line 333, in _compute_ricci_curvature_single_edge
m = _sinkhorn_distance(x, y, d)
File "/apdcephfs/share_1437072/rayan/jobs/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py", line 250, in _sinkhorn_distance
m = ot.sinkhorn2(x, y, d, 1e-1, method='sinkhorn')[0]
IndexError: invalid index to scalar variable.
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "example.py", line 60, in
orc_Sinkhorn.compute_ricci_flow(iterations=10)
File "/apdcephfs/share_1437072/rayan/jobs/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py", line 801, in compute_ricci_flow
self.G = _compute_ricci_flow(G=self.G, weight=self.weight,
File "/apdcephfs/share_1437072/rayan/jobs/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py", line 570, in _compute_ricci_flow
_compute_ricci_curvature(G, weight=weight, **kwargs)
File "/apdcephfs/share_1437072/rayan/jobs/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py", line 504, in _compute_ricci_curvature
edge_ricci = _compute_ricci_curvature_edges(G, weight=weight, **kwargs)
File "/apdcephfs/share_1437072/rayan/jobs/GraphRicciCurvature/GraphRicciCurvature/OllivierRicci.py", line 475, in _compute_ricci_curvature_edges
for rc in result:
File "/root/miniconda3/lib/python3.8/multiprocessing/pool.py", line 448, in
return (item for chunk in result for item in chunk)
File "/root/miniconda3/lib/python3.8/multiprocessing/pool.py", line 868, in next
raise value
IndexError: invalid index to scalar variable.

I can not figure out the reason, please help.

Visualization of the communities in GraphRicciCurvature Tutorial

Hello,
I'm new to GraphRicciCurvature library and want to reproduce the code in GraphRicciCurvature Tutorial with my own graph.
I don't know what is the clustering label in the bellow code:

def draw_graph(G, clustering_label="club"):
    """
    A helper function to draw a nx graph with community.
    """
    complex_list = nx.get_node_attributes(G, clustering_label)

    le = preprocessing.LabelEncoder()
    node_color = le.fit_transform(list(complex_list.values()))

    nx.draw_spring(G, nodelist=G.nodes(),
                   node_color=node_color,
                   cmap=plt.cm.rainbow,
                   alpha=0.8)

Is it possible to use the ricci comunity detection for unsupervised problem?
We don't have any information about the number of communities in my network.

Thank you.

Indexing error when calling compute_ricci_curvature

Hello,

I'm new to using GraphRicciCurvature library,

I'm receiving an error when calling compute_ricci_curvature in this code snippet:

Gd = nx.Graph()
ricci_edge_index_ = np.array(data.edge_index)
ricci_edge_index = [(ricci_edge_index_[0, i],
                     ricci_edge_index_[1, i]) for i in
                    range(np.shape(data.edge_index)[1])]
Gd.add_edges_from(ricci_edge_index)
Gd_OT = OllivierRicci(Gd, alpha=0.5, method="Sinkhorn", verbose="INFO")
print("adding edges finished")
Gd_OT.compute_ricci_curvature()

It breaks in the last line, the trace back as follows:

multiprocessing.pool.RemoteTraceback: 
Traceback (most recent call last):
  File "/opt/miniconda3/envs/ocp-models/lib/python3.6/multiprocessing/pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "/opt/miniconda3/envs/ocp-models/lib/python3.6/multiprocessing/pool.py", line 44, in mapstar
    return list(map(*args))
  File "/home/.local/lib/python3.6/site-packages/GraphRicciCurvature/OllivierRicci.py", line 352, in _wrap_compute_single_edge
    return _compute_ricci_curvature_single_edge(*stuff)
  File "/home/.local/lib/python3.6/site-packages/GraphRicciCurvature/OllivierRicci.py", line 333, in _compute_ricci_curvature_single_edge
    m = _sinkhorn_distance(x, y, d)
  File "/home/.local/lib/python3.6/site-packages/GraphRicciCurvature/OllivierRicci.py", line 250, in _sinkhorn_distance
    m = ot.sinkhorn2(x, y, d, 1e-1, method='sinkhorn')[0]
IndexError: invalid index to scalar variable.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "pipelines.py", line 99, in <module>
    data_cnt)
  File "/home/TLC-GNN/baselines/TLCGNN.py", line 106, in call
    test_edges_false, name, hop = hop)
  File "/home/TLC-GNN/loaddatas.py", line 96, in compute_persistence_image
    ricci_cur = compute_ricci_curvature(data)
  File "/home/TLC-GNN/loaddatas.py", line 116, in compute_ricci_curvature
    Gd_OT.compute_ricci_curvature()
  File "/home/.local/lib/python3.6/site-packages/GraphRicciCurvature/OllivierRicci.py", line 766, in compute_ricci_curvature
    nbr_topk=self.nbr_topk)
  File "/home/.local/lib/python3.6/site-packages/GraphRicciCurvature/OllivierRicci.py", line 504, in _compute_ricci_curvature
    edge_ricci = _compute_ricci_curvature_edges(G, weight=weight, **kwargs)
  File "/home/.local/lib/python3.6/site-packages/GraphRicciCurvature/OllivierRicci.py", line 475, in _compute_ricci_curvature_edges
    for rc in result:
  File "/opt/miniconda3/envs/ocp-models/lib/python3.6/multiprocessing/pool.py", line 347, in <genexpr>
    return (item for chunk in result for item in chunk)
  File "/opt/miniconda3/envs/ocp-models/lib/python3.6/multiprocessing/pool.py", line 735, in next
    raise value
IndexError: invalid index to scalar variable.

Any thought about what could be the reason?

Parameters in the example figure

Hi! I am trying to reproduce the figure as displayed on the homepage.
karate_demo

I used the same data set and assigned weight 1 first, then ran OllivierRicci.compute_ricci_flow using the below code.

orc = OllivierRicci(G, alpha=0.5, verbose="INFO")
G2 = orc.compute_ricci_flow(iterations=100)

However, the histogram of the weights of G2 is not like the figure:
image

I guess it is due to different arguments when running compute_ricci_flow. Could you please share your arguments corresponding to your example figure?

Error in Discrete Ricci Curvature tutorial

I believe there is a small error in the tutorial for Discrete Ricci curvature. The probability distribution is defined as having weight alpha for x and weight 1 - alpha for a neighbor of x, but the weight for the neighbors of x should be divided by the number of neighbors of x so that the total weight is 1.

RuntimeError

Hello! There are some problems occurred when I ran this code in tutorial notebook you gave:

orc.compute_ ricci_ curvature()
G_ Orc = ORC. G.copy() # save an intermediate result

But I didn't have these problems when I ran on binder. The question I asked may be stupid, but I really can't solve it.

The following is the specific content of error reporting:

ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10224/3609495132.py in <module>
----> 1 orc.compute_ricci_curvature()
      2 #G_orc = orc.G.copy()  # save an intermediate result

D:\conda\envs\orc\lib\site-packages\GraphRicciCurvature\OllivierRicci.py in compute_ricci_curvature(self)
    759         """
    760 
--> 761         self.G = _compute_ricci_curvature(G=self.G, weight=self.weight,
    762                                           alpha=self.alpha, method=self.method,
    763                                           base=self.base, exp_power=self.exp_power,

D:\conda\envs\orc\lib\site-packages\GraphRicciCurvature\OllivierRicci.py in _compute_ricci_curvature(G, weight, **kwargs)
    502 
    503     # compute Ricci curvature for all edges
--> 504     edge_ricci = _compute_ricci_curvature_edges(G, weight=weight, **kwargs)
    505 
    506     # Assign edge Ricci curvature from result to graph G

D:\conda\envs\orc\lib\site-packages\GraphRicciCurvature\OllivierRicci.py in _compute_ricci_curvature_edges(G, weight, edge_list, alpha, method, base, exp_power, proc, chunksize, cache_maxsize, shortest_path, nbr_topk)
    457     t0 = time.time()
    458 
--> 459     with mp.get_context('fork').Pool(processes=_proc) as pool:
    460         # WARNING: Now only fork works, spawn will hang.
    461 

D:\conda\envs\orc\lib\multiprocessing\context.py in get_context(self, method)
    237             return self._actual_context
    238         else:
--> 239             return super().get_context(method)
    240 
    241     def set_start_method(self, method, force=False):

D:\conda\envs\orc\lib\multiprocessing\context.py in get_context(self, method)
    191             ctx = _concrete_contexts[method]
    192         except KeyError:
--> 193             raise ValueError('cannot find context for %r' % method) from None
    194         ctx._check_available()
    195         return ctx

ValueError: cannot find context for 'fork'

Platform

  • OS: [Windows]
  • Python [3.9]
  • Version [0.5.3]

Your answer will be of great help to me and looking forward to your answer.
Good luck!

ricciCurvature_singleEdge() TypeError: 'int' object is not subscriptable

Using a basic .gml file with the following format

edge
[
source 1136
target 3710
value 2.000
]

and my code looks like

G = nx.read_gml(file,['utf-8'])
G = nx.Graph(G)
G = ricciCurvature_singleEdge(G, alpha = 0.5, source = '1136', target = '3710', length = 1, verbose = True)

which gives me the error

Type Error: 'int' object is not subscriptable

Not compatible with any version of networkX?

It seems there are slight migration issues. I was trying to run the sample code, and it seems that there are part of the code that are not compatible with networkX 2.x (primarily calling G.node instead of G.nodes) and other parts incompatible with networkX 1.x (swapped order of arguments in one of the function calls).
I have made a couple of fixes to make it work with the newest version of networkX that I could submit if that would be helpful.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.