### Install GraphRicciCurvature via pip Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/readme.md Install the library using pip. For larger graphs and versions 0.4.0+, NetworKit installation is crucial and may require building from source. ```bash pip3 install [--user] GraphRicciCurvature ``` -------------------------------- ### Install and Import Dependencies Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Install the required packages and import necessary libraries for graph processing and curvature computation. ```python # colab setting !pip install GraphRicciCurvature !pip install scikit-learn # import sys # sys.path.append("../") import networkx as nx import numpy as np import math # matplotlib setting %matplotlib inline import matplotlib.pyplot as plt # to print logs in jupyter notebook import logging logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.ERROR) # load GraphRicciCuravture package from GraphRicciCurvature.OllivierRicci import OllivierRicci from GraphRicciCurvature.FormanRicci import FormanRicci # load python-louvain for modularity computation import community.community_louvain as community_louvain # for ARI computation from sklearn import preprocessing, metrics ``` -------------------------------- ### Verify Package Version Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Check the installed version of the GraphRicciCurvature package. ```python import GraphRicciCurvature print(GraphRicciCurvature.__version__) ``` -------------------------------- ### Execute Graph Surgery with Specific Cutoffs Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Examples of applying the surgery function with different threshold values. ```python draw_graph(my_surgery(G_rf, cut=1.5)) ``` ```python draw_graph(my_surgery(G_rf, cut=1.0)) ``` -------------------------------- ### Compute Ollivier-Ricci Curvature for Karate Club Graph Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md Example demonstrating the initialization of the OllivierRicci container and the computation of Ricci curvature for a standard NetworkX graph. ```python >>> G = nx.karate_club_graph() >>> orc = OllivierRicci(G, alpha=0.5, verbose="INFO") >>> orc.compute_ricci_curvature() >>> orc.G[0][1] {'weight': 1.0, 'ricciCurvature': 0.11111111071683011} ``` -------------------------------- ### Compute Ollivier-Ricci Curvature Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/readme.md Import necessary libraries and compute the Ollivier-Ricci curvature for a NetworkX graph. This example uses the karate club graph. ```python 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 Ollivier-Ricci and Forman-Ricci Curvature Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/index.md This snippet demonstrates how to compute both Ollivier-Ricci and Forman-Ricci curvatures for a NetworkX graph. Ensure NetworkX is installed and the GraphRicciCurvature library is imported. ```python 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 ===== ``` ```python # 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"]) ``` ```python print("\n===== Compute the Forman-Ricci curvature of the given graph G ===== ``` ```python 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 Ollivier-Ricci and Forman-Ricci Curvature Source: https://github.com/saibalmars/graphriccicurvature/blob/master/README.md This snippet demonstrates how to compute both Ollivier-Ricci and Forman-Ricci curvatures for a NetworkX graph. Ensure NetworkX is installed and import the necessary classes. The OllivierRicci class requires an alpha parameter, while FormanRicci does not. ```python 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 ===== ``` -------------------------------- ### Get Ricci Flow Metric Cutoff for Communities Source: https://context7.com/saibalmars/graphriccicurvature/llms.txt Automatically identifies potential community cutoff points by analyzing modularity changes as edges are removed based on Ricci flow metrics. Helps in selecting optimal thresholds for community detection. ```python import networkx as nx from GraphRicciCurvature.OllivierRicci import OllivierRicci from GraphRicciCurvature.util import get_rf_metric_cutoff G = nx.karate_club_graph() # Compute Ricci flow orc = OllivierRicci(G, alpha=0.5, method="OTD", verbose="INFO") orc.compute_ricci_flow(iterations=50) # Find good cutoff points automatically good_cuts = get_rf_metric_cutoff( orc.G, weight="weight", cutoff_step=0.025, # Step size for scanning drop_threshold=0.01 # Minimum modularity drop ) print(f"Suggested cutoff points: {good_cuts}") # Use the first (best) cutoff for community detection ``` -------------------------------- ### GET /util/get_rf_metric_cutoff Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md Calculates optimal clustering cutoff points for a graph based on Ricci flow metrics. ```APIDOC ## GET /util/get_rf_metric_cutoff ### Description Get good clustering cutoff points for Ricci flow metric by detecting the change of modularity while removing edges. ### Parameters #### Path Parameters - **G_origin** (NetworkX graph) - Required - A graph with “weight” as Ricci flow metric to cut. #### Query Parameters - **weight** (str) - Optional - The edge weight used as Ricci flow metric. (Default value = “weight”) - **cutoff_step** (float) - Optional - The step size to find the good cutoff points. - **drop_threshold** (float) - Optional - At least drop this much to considered as a drop for good_cut. ### Response #### Success Response (200) - **good_cuts** (list of float) - A list of possible cutoff points, usually the first one is considered the best cut. ``` -------------------------------- ### Load and Prepare Sample Graph Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Load the Zachary's Karate Club graph and remove existing edge weights to create an unweighted graph. ```python G = nx.karate_club_graph() for (n1, n2, d) in G.edges(data=True): d.clear() # remove edge weight ``` -------------------------------- ### Initialize Ollivier-Ricci Flow Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Configure the OllivierRicci class with specific parameters to prepare for Ricci flow computation. ```python # Start a Ricci flow with Lin-Yau's probability distribution setting with 4 process. orf = OllivierRicci(G, alpha=0.5, base=1, exp_power=0, proc=4, verbose="INFO") ``` -------------------------------- ### Initialize OllivierRicci Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Creates an OllivierRicci instance with verbose logging enabled. ```python orc_polbooks = OllivierRicci(G_polbooks,verbose="INFO") ``` -------------------------------- ### OllivierRicci Class Initialization and Usage Source: https://context7.com/saibalmars/graphriccicurvature/llms.txt Demonstrates how to initialize the OllivierRicci class and compute Ricci curvature for all edges in a graph. Includes parameters for curvature computation and accessing results. ```APIDOC ## OllivierRicci Class ### Description The main class for computing Ollivier-Ricci curvature based on optimal transportation distance between probability distributions on neighboring nodes. It supports multiple transportation methods and parallel processing for efficient computation on large graphs. ### Method Initialization of the OllivierRicci class. ### Endpoint N/A (Class initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Initialization Parameters - **G** (networkx.Graph) - The input graph. - **alpha** (float) - Mass retention at source node (0-1). Default is 0.5. - **method** (str) - Options: "OTD", "ATD", "Sinkhorn", "OTDSinkhornMix". Default is "OTD". - **weight** (str) - Edge weight attribute name. Default is "weight". - **proc** (int) - Number of processors for multiprocessing. Default is 1. - **verbose** (str) - Logging level: "INFO", "TRACE", "DEBUG", "ERROR". Default is "INFO". ### Request Example ```python import networkx as nx from GraphRicciCurvature.OllivierRicci import OllivierRicci G = nx.karate_club_graph() orc = OllivierRicci( G, alpha=0.5, method="OTD", weight="weight", proc=4, verbose="INFO" ) ``` ### Response #### Success Response (200) An instance of the OllivierRicci class with computed curvatures. #### Response Example ```python # Access edge curvature print(f"Edge (0,1) curvature: {orc.G[0][1]['ricciCurvature']}") # Output: Edge (0,1) curvature: 0.11111111071683011 # Access node curvature (average of adjacent edges) print(f"Node 0 curvature: {orc.G.nodes[0]['ricciCurvature']}") ``` ``` -------------------------------- ### Initialize Forman-Ricci Curvature Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Instantiate the FormanRicci class to prepare a graph for Forman-Ricci curvature computation. ```python frc = FormanRicci(G, verbose="TRACE") ``` -------------------------------- ### Initialize Ollivier-Ricci Curvature Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Instantiate the OllivierRicci class to prepare a graph for curvature computation. ```python orc = OllivierRicci(G, alpha=0.5, verbose="TRACE") ``` -------------------------------- ### Clean Graph Ricci Curvature Data Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Removes pre-computed Ricci curvature and resets edge weights to 1. This function is useful for starting Ricci flow computations from scratch. ```python def clean_graph(G): for n1, n2 in G.edges(): del G[n1][n2]["ricciCurvature"] del G[n1][n2]["original_RC"] G[n1][n2]["weight"]=1 for n in G.nodes(): del G.nodes[n]["ricciCurvature"] ``` -------------------------------- ### OllivierRicci Class Initialization and Ricci Flow Computation Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md Demonstrates how to initialize the OllivierRicci class and compute the Ricci flow for a graph. It also shows how to access computed Ricci curvature values for edges. ```APIDOC ## Compute Ollivier-Ricci Flow ### Description Computes the Ollivier-Ricci flow for a given graph and allows access to the computed Ricci curvature values for edges. ### Method `OllivierRicci.compute_ricci_flow(iterations)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python G = nx.karate_club_graph() orc_OTD = OllivierRicci(G, alpha=0.5, method="OTD", verbose="INFO") orc_OTD.compute_ricci_flow(iterations=10) print(orc_OTD.G[0][1]) ``` ### Response #### Success Response (200) Returns the graph object with updated edge attributes including 'ricciCurvature'. #### Response Example ```json { "weight": 0.06399135316908759, "ricciCurvature": 0.18608249978652802, "original_RC": 0.11111111071683011 } ``` ``` -------------------------------- ### OllivierRicci Initialization Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md Initializes the OllivierRicci container with a NetworkX graph and configurable parameters for curvature computation. ```APIDOC ## OllivierRicci Initialization ### Description Initializes a container to compute Ollivier-Ricci curvature/flow. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **G** (*NetworkX graph*) – A given directional or undirectional NetworkX graph. - **weight** (*str*) – The edge weight used to compute Ricci curvature. (Default value = "weight") - **alpha** (*float*) – The parameter for the discrete Ricci curvature, range from 0 ~ 1. (Default value = 0.5) - **method** (*{"OTD", "ATD", "Sinkhorn", "OTDSinkhornMix"}*) – The optimal transportation distance computation method. (Default value = "OTDSinkhornMix") - **base** (*float*) – Base variable for weight distribution. (Default value = math.e) - **exp_power** (*float*) – Exponential power for weight distribution. (Default value = 2) - **proc** (*int*) – Number of processor used for multiprocessing. (Default value = cpu_count()) - **chunksize** (*int*) – Chunk size for multiprocessing, set None for auto decide. (Default value = None) - **shortest_path** (*{"all_pairs", "pairwise"}*) – Method to compute shortest path. (Default value = all_pairs) - **cache_maxsize** (*int*) – Max size for LRU cache for pairwise shortest path computation. Set this to None for unlimited cache. (Default value = 1000000) - **nbr_topk** (*int*) – Only take the top k edge weight neighbors for density distribution. (Default value = 3000) - **verbose** (*{"INFO", "TRACE", "DEBUG", "ERROR"}*) – Verbose level. (Default value = "ERROR") ``` -------------------------------- ### Upgrade GraphRicciCurvature via pip Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/readme.md Upgrade to the latest version of the library for the best performance using pip. ```bash pip3 install [--user] --upgrade GraphRicciCurvature ``` -------------------------------- ### Initialize Ollivier Ricci Computation Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Initializes the OllivierRicci class with a cleaned graph. Set verbose to 'INFO' to see computation details. ```python orc_football = OllivierRicci(G_football,verbose="INFO") ``` -------------------------------- ### Print Graph Information Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Display the basic properties of the loaded graph object. ```python print(G) ``` -------------------------------- ### OllivierRicci Class Initialization Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Initializes the Ricci curvature computation object with specific parameters for probability distribution and transportation methods. ```APIDOC ## OllivierRicci Initialization ### Description Initializes the OllivierRicci object to compute curvature on a graph G. ### Parameters - **alpha** (float) - Optional - Probability distribution mass share [0~1]. Default: 0.5 - **base** (float) - Optional - Base variable for weight distribution. Default: math.e - **exp_power** (float) - Optional - Exponential power for weight distribution. Default: 0 - **method** (string) - Optional - Transportation method: ["OTD", "ATD", "Sinkhorn"]. Default: "Sinkhorn" ### Request Example ```python orf2 = OllivierRicci(G, alpha=0.5, base=math.e, exp_power=1, verbose="ERROR") ``` ``` -------------------------------- ### Display Forman-Ricci Results Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Use the visualization helper to display Forman-Ricci curvature results. ```python show_results(G_frc,curvature="formanCurvature") ``` -------------------------------- ### Compute Forman-Ricci Curvature Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Execute the Forman-Ricci curvature computation and store the results. ```python frc.compute_ricci_curvature() G_frc = frc.G.copy() # save an intermediate result ``` -------------------------------- ### Compute All Possible Community Clusterings Source: https://context7.com/saibalmars/graphriccicurvature/llms.txt Generates all possible community clusterings by varying the cutoff point. Useful for exploring community structures at different granularities. Requires Ricci flow computation beforehand. ```python import networkx as nx from GraphRicciCurvature.OllivierRicci import OllivierRicci G = nx.karate_club_graph() orc = OllivierRicci(G, alpha=0.5, method="OTD", verbose="INFO") orc.compute_ricci_flow(iterations=50) # Get all possible clusterings all_clusterings = orc.ricci_community_all_possible_clusterings( cutoff_step=0.025, drop_threshold=0.01 ) print(f"Number of possible clusterings: {len(all_clusterings)}") for cutoff, clustering in all_clusterings: num_communities = len(set(clustering.values())) print(f"Cutoff {cutoff:.4f}: {num_communities} communities") ``` -------------------------------- ### Load Political Books Graph Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Loads the political books graph from a GEXF file. This is used for fine-tuning community detection on graphs with less obvious structures. ```python G_polbooks_raw = nx.read_gexf(urlopen("https://raw.githubusercontent.com/saibalmars/RicciFlow-SampleGraphs/master/polbooks_rf_sinkhorn_e2_20.gexf")) G_polbooks = G_polbooks_raw.copy() ``` -------------------------------- ### Tune Exp Power for Ricci Community Detection Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Initialize OllivierRicci with exp_power=1 and compute the Ricci community. Adjusting exp_power can change the ARI and modularity curves. ```python orc_polbooks1 = OllivierRicci(G_polbooks,exp_power=1,verbose="ERROR") cc1 = orc_polbooks1.ricci_community() ``` -------------------------------- ### Load and Clean Football Graph Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Loads the football graph from a GEXF file and cleans it using the clean_graph function. Ensure networkx and urlopen are imported. ```python G_football_raw = nx.read_gexf(urlopen("https://raw.githubusercontent.com/saibalmars/RicciFlow-SampleGraphs/master/football_rf_sinkhorn_e2_20.gexf")) G_football = G_football_raw.copy() clean_graph(G_football) ``` -------------------------------- ### Compute Ollivier-Ricci Curvature Source: https://context7.com/saibalmars/graphriccicurvature/llms.txt Initializes the OllivierRicci class to compute curvature for all edges in a graph. Requires a NetworkX graph and supports various transportation methods and multiprocessing. ```python import networkx as nx from GraphRicciCurvature.OllivierRicci import OllivierRicci # Create or load a graph G = nx.karate_club_graph() # Initialize OllivierRicci with parameters orc = OllivierRicci( G, alpha=0.5, # Mass retention at source node (0-1) method="OTD", # Options: "OTD", "ATD", "Sinkhorn", "OTDSinkhornMix" weight="weight", # Edge weight attribute name proc=4, # Number of processors for multiprocessing verbose="INFO" # Logging: "INFO", "TRACE", "DEBUG", "ERROR" ) # Compute Ricci curvature for all edges orc.compute_ricci_curvature() # Access edge curvature print(f"Edge (0,1) curvature: {orc.G[0][1]['ricciCurvature']}") # Output: Edge (0,1) curvature: 0.11111111071683011 # Access node curvature (average of adjacent edges) print(f"Node 0 curvature: {orc.G.nodes[0]['ricciCurvature']}") ``` -------------------------------- ### Import Utility for Graph Cutting Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Imports necessary functions for graph manipulation, specifically for cutting graphs based on cutoff values. This is a prerequisite for advanced community detection techniques. ```python from urllib.request import urlopen from GraphRicciCurvature.util import cut_graph_by_cutoff ``` -------------------------------- ### Visualize graph communities Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Helper function to draw a NetworkX graph with nodes colored by community labels. ```python 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) draw_graph(G_rf) ``` -------------------------------- ### Compute Forman-Ricci Curvature (Augmented Method) Source: https://context7.com/saibalmars/graphriccicurvature/llms.txt Calculates Forman-Ricci curvature for a NetworkX graph using the augmented method, which considers triangles. Edge weights can be specified. Access computed curvatures directly from graph nodes and edges. ```python import networkx as nx from GraphRicciCurvature.FormanRicci import FormanRicci G = nx.karate_club_graph() # Initialize with augmented method (default, considers triangles) frc = FormanRicci( G, weight="weight", # Edge weight attribute method="augmented", # Options: "1d" or "augmented" verbose="ERROR" ) # Compute Forman-Ricci curvature frc.compute_ricci_curvature() # Access edge curvature print(f"Edge (0,1) Forman curvature: {frc.G[0][1]['formanCurvature']}") print(f"Edge (0,2) Forman curvature: {frc.G[0][2]['formanCurvature']}") # Access node curvature (average of adjacent edges) print(f"Node 0 Forman curvature: {frc.G.nodes[0]['formanCurvature']}") ``` -------------------------------- ### Compute Ricci Flow on Karate Club Graph Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Initializes and computes Ricci flow on the karate club graph with specified parameters. Use this to analyze graph curvature and prepare for community detection. ```python orf2 = OllivierRicci(G, alpha=0.5, base=math.e, exp_power=1, verbose="ERROR") orf2.compute_ricci_flow(iterations=50) G_rf2 = orf2.G.copy() ``` -------------------------------- ### Automate Clustering Accuracy Check Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Iterates through potential cutoff points to evaluate clustering quality. ```python def check_accuracy(G_origin, weight="weight", clustering_label="value", plot_cut=True): """To check the clustering quality while cut the edges with weight using different threshold Parameters ---------- G_origin : NetworkX graph A graph with ``weight`` as Ricci flow metric to cut. weight: float The edge weight used as Ricci flow metric. (Default value = "weight") clustering_label : str Node attribute name for ground truth. plot_cut: bool To plot the good guessed cut or not. """ G = G_origin.copy() modularity, ari = [], [] maxw = max(nx.get_edge_attributes(G, weight).values()) cutoff_range = np.arange(maxw, 1, -0.025) for cutoff in cutoff_range: edge_trim_list = [] for n1, n2 in G.edges(): if G[n1][n2][weight] > cutoff: edge_trim_list.append((n1, n2)) G.remove_edges_from(edge_trim_list) ``` -------------------------------- ### Visualize Ricci Curvature Results Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Display edge curvature values and plot histograms for curvature and edge weight distributions. ```python def show_results(G, curvature="ricciCurvature"): # Print the first five results print("Karate Club Graph, first 5 edges: ") for n1,n2 in list(G.edges())[:5]: print("Ricci curvature of edge (%s,%s) is %f" % (n1 ,n2, G[n1][n2][curvature])) # Plot the histogram of Ricci curvatures plt.subplot(2, 1, 1) ricci_curvtures = nx.get_edge_attributes(G, curvature).values() plt.hist(ricci_curvtures,bins=20) plt.xlabel('Ricci curvature') plt.title("Histogram of Ricci Curvatures (Karate Club)") # Plot the histogram of edge weights plt.subplot(2, 1, 2) weights = nx.get_edge_attributes(G, "weight").values() plt.hist(weights,bins=20) plt.xlabel('Edge weight') plt.title("Histogram of Edge weights (Karate Club)") plt.tight_layout() show_results(G_orc) ``` -------------------------------- ### Draw Graph with Detected Communities Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Visualizes the graph with communities cut by a specified cutoff. The clustering_label should be set to 'value' to display community assignments. ```python draw_graph(cut_graph_by_cutoff(orc_football.G,cutoff=cc[0]),clustering_label="value") ``` -------------------------------- ### Compute Curvature on Large Graphs with Multiprocessing Source: https://context7.com/saibalmars/graphriccicurvature/llms.txt Leverage parallel processing and the OTDSinkhornMix method to compute curvature efficiently on large-scale graphs. ```python import networkx as nx from GraphRicciCurvature.OllivierRicci import OllivierRicci import multiprocessing # Generate a large random graph G_large = nx.random_regular_graph(8, 1000) # 1000 nodes, degree 8 # Use multiple processors for faster computation orc = OllivierRicci( G_large, alpha=0.5, method="OTDSinkhornMix", # Hybrid method for large graphs proc=multiprocessing.cpu_count(), # Use all available CPUs nbr_topk=3000, # Limit neighbors for density computation verbose="INFO" ) # Compute curvature orc.compute_ricci_curvature() # Analyze curvature distribution curvatures = [orc.G[u][v]["ricciCurvature"] for u, v in orc.G.edges()] print(f"Edges computed: {len(curvatures)}") print(f"Mean curvature: {sum(curvatures)/len(curvatures):.4f}") print(f"Min curvature: {min(curvatures):.4f}") print(f"Max curvature: {max(curvatures):.4f}") ``` -------------------------------- ### Ricci Community Detection (All Possible Clusterings) Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md Provides a method to detect all possible community clusterings by considering various cutoff points derived from the Ricci flow metric. It returns a list of cutoff-clustering pairs. ```APIDOC ## Detect All Possible Ricci Communities ### Description Detects all possible community clusterings by iteratively removing edge weights based on the Ricci flow metric and observing modularity drops. This function returns a list of all identified cutoff-clustering pairs. ### Method `OllivierRicci.ricci_community_all_possible_clusterings(cutoff_step=0.025, drop_threshold=0.01)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **cutoff_step** (*float*) – The step size used to find significant cutoff points. Defaults to 0.025. * **drop_threshold** (*float*) – The minimum modularity drop required to consider a point as a significant cutoff. Defaults to 0.01. ### Request Example ```python G = nx.karate_club_graph() orc = OllivierRicci(G, alpha=0.5, verbose="INFO") orc.compute_ricci_flow(iterations=50) cc = orc.ricci_community_all_possible_clusterings() print(f"The number of possible clusterings: {len(cc)}") ``` ### Response #### Success Response (200) Returns a list of tuples, where each tuple contains a cutoff value (float) and a dictionary representing a community clustering. #### Response Example ```json [ { "cutoff": 0.025, "clustering": { "0": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33] } }, { "cutoff": 0.05, "clustering": { "0": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], "1": [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33] } } ] ``` ``` -------------------------------- ### Compute Curvature for Directed Graphs Source: https://context7.com/saibalmars/graphriccicurvature/llms.txt Utilize Ollivier-Ricci curvature on directed graphs by initializing with a DiGraph object. ```python import networkx as nx from GraphRicciCurvature.OllivierRicci import OllivierRicci # Create a directed graph Gd = nx.DiGraph() Gd.add_edges_from([ (0, 1), (1, 2), (2, 3), (1, 3), (3, 1), (0, 2) ]) # Compute Ollivier-Ricci curvature for directed graph orc = OllivierRicci(Gd, alpha=0.5, verbose="ERROR") orc.compute_ricci_curvature() # Print curvature for each directed edge for n1, n2 in Gd.edges(): rc = orc.G[n1][n2]["ricciCurvature"] print(f"Edge ({n1} -> {n2}): curvature = {rc:.6f}") # Output: # Edge (0 -> 1): curvature = 0.500000 # Edge (0 -> 2): curvature = 0.500000 # Edge (1 -> 2): curvature = 0.500000 # Edge (1 -> 3): curvature = 0.000000 # Edge (2 -> 3): curvature = 0.500000 # Edge (3 -> 1): curvature = 0.000000 ``` -------------------------------- ### BibTeX Citation Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/readme.md LaTeX citation format for the community detection research paper. ```latex @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} } ``` -------------------------------- ### Check Accuracy After Tuning Exp Power Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Check the accuracy of the graph after tuning the exp_power parameter. This helps in evaluating the impact of exp_power on community detection results. ```python check_accuracy(orc_polbooks1.G,clustering_label="value") ``` -------------------------------- ### Retrieve All Possible Ricci Clusterings Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md Generates a list of all potential community clusterings based on different Ricci flow cutoff points. ```default >>> G = nx.karate_club_graph() >>> orc = OllivierRicci(G, alpha=0.5, verbose="INFO") >>> orc.compute_ricci_flow(iterations=50) >>> cc = orc.ricci_community_all_possible_clusterings() >>> print("The number of possible clusterings: %d" % len(cc)) The number of possible clusterings: 3 ``` -------------------------------- ### Compute Forman-Ricci Curvature for Karate Club Graph Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md Initializes the FormanRicci class with the karate club graph and computes the Ricci curvature for all nodes and edges. The result is stored in the graph object. ```python G = nx.karate_club_graph() frc = FormanRicci(G) frc.compute_ricci_curvature() frc.G[0][2] ``` -------------------------------- ### Compute Ollivier-Ricci and Forman-Ricci Curvature Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/readme.md Calculates curvature metrics for a graph G. Requires the OllivierRicci or FormanRicci classes to be initialized with the graph object. ```python 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"]) ``` -------------------------------- ### ricci_community_all_possible_clusterings Source: https://context7.com/saibalmars/graphriccicurvature/llms.txt Retrieves all possible community clusterings detected at different cutoff points, returned as a list of (cutoff, clustering) pairs. ```APIDOC ## ricci_community_all_possible_clusterings ### Description Get all possible community clusterings detected at different cutoff points. Returns a list of (cutoff, clustering) pairs from coarse to fine granularity. ### Parameters #### Query Parameters - **cutoff_step** (float) - Optional - Step size for scanning cutoff points. - **drop_threshold** (float) - Optional - Minimum modularity drop threshold. ``` -------------------------------- ### set_verbose Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md Sets the verbosity level for the Ollivier-Ricci computation process. ```APIDOC ## set_verbose(verbose) ### Description Set the verbose level for this process. ### Method `set_verbose` ### Endpoint N/A (Method of the OllivierRicci object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **verbose** (*{"INFO", "TRACE", "DEBUG", "ERROR"}*) – Verbose level. (Default value = "ERROR") ``` -------------------------------- ### Display Ricci Flow Results Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Visualizes the results of the Ricci flow computation, showing the first few edges and their calculated Ricci curvature. This helps in understanding the curvature distribution across the graph. ```python show_results(G_rf2) ``` -------------------------------- ### Compute Ricci Flow Metric and Community Detection Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/index.md This snippet shows how to compute the Ricci flow metric using Optimal Transportation Distance (OTD) and then perform community detection based on Ricci flow. It requires the GraphRicciCurvature library and NetworkX. ```python # ----------------------------------- print("\n===== Compute Ricci flow metric - Optimal Transportation Distance ===== ``` ```python 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 ===== ``` ```python clustering = orc_OTD.ricci_community()) ``` -------------------------------- ### Compute Forman-Ricci Curvature (1D Method) Source: https://context7.com/saibalmars/graphriccicurvature/llms.txt Calculates Forman-Ricci curvature using the 1-dimensional method, which only considers vertices and edges, excluding triangles. Useful for comparing with the augmented method or for graphs where higher-order structures are not relevant. ```python import networkx as nx from GraphRicciCurvature.FormanRicci import FormanRicci G = nx.karate_club_graph() # Use 1D method (only considers vertices and edges) frc_1d = FormanRicci(G, method="1d", verbose="ERROR") frc_1d.compute_ricci_curvature() # Compare with augmented method frc_aug = FormanRicci(G, method="augmented", verbose="ERROR") frc_aug.compute_ricci_curvature() print("Edge (0,1) curvature comparison:") print(f" 1D method: {frc_1d.G[0][1]['formanCurvature']}") print(f" Augmented: {frc_aug.G[0][1]['formanCurvature']}") ``` -------------------------------- ### Compute Ollivier-Ricci Curvature Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Execute the curvature computation and store the results in a copy of the graph. ```python orc.compute_ricci_curvature() G_orc = orc.G.copy() # save an intermediate result ``` -------------------------------- ### Display Ricci flow results Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Visualizes the graph results after Ricci flow computation. ```python show_results(G_rf) ``` -------------------------------- ### Utility Functions - get_rf_metric_cutoff Source: https://context7.com/saibalmars/graphriccicurvature/llms.txt Automatically identifies optimal cutoff points for community detection by analyzing modularity changes. ```APIDOC ## get_rf_metric_cutoff ### Description Automatically find good cutoff points for community detection by analyzing modularity changes as edges are removed. ### Parameters #### Query Parameters - **G** (NetworkX Graph) - Required - The input graph. - **weight** (string) - Optional - Edge weight attribute. - **cutoff_step** (float) - Optional - Step size for scanning. - **drop_threshold** (float) - Optional - Minimum modularity drop. ``` -------------------------------- ### Ricci Community Detection Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md Explains how to detect community clustering using the Ricci flow metric. This method identifies communities by observing modularity drops as edge weights are iteratively removed. ```APIDOC ## Detect Ricci Community ### Description Detects community clustering in a graph based on the Ricci flow metric. Communities are identified by monitoring the drop in modularity as edge weights are iteratively reduced. ### Method `OllivierRicci.ricci_community(cutoff_step=0.025, drop_threshold=0.01)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **cutoff_step** (*float*) – The step size used to find significant cutoff points. Defaults to 0.025. * **drop_threshold** (*float*) – The minimum modularity drop required to consider a point as a significant cutoff. Defaults to 0.01. ### Request Example ```python G = nx.karate_club_graph() orc = OllivierRicci(G, alpha=0.5, verbose="INFO") orc.compute_ricci_flow(iterations=50) cc = orc.ricci_community() print(f"The detected community label of node 0: {cc[1][0]}") ``` ### Response #### Success Response (200) Returns a tuple containing the cutoff value and a dictionary representing the community clustering. #### Response Example ```json { "cutoff": 0.05, "clustering": { "0": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], "1": [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33] } } ``` ``` -------------------------------- ### Compute Ollivier-Ricci Flow Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md Calculates the Ricci flow for a NetworkX graph using the OTD method. ```default >>> G = nx.karate_club_graph() >>> orc_OTD = OllivierRicci(G, alpha=0.5, method="OTD", verbose="INFO") >>> orc_OTD.compute_ricci_flow(iterations=10) >>> orc_OTD.G[0][1] {'weight': 0.06399135316908759, 'ricciCurvature': 0.18608249978652802, 'original_RC': 0.11111111071683011} ``` -------------------------------- ### Compute Ricci Community Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Performs community detection by automatically computing Ricci flow with 10 iterations. ```python cc = orc_polbooks.ricci_community() ``` -------------------------------- ### Set Verbose Level Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md Utility function to control the verbosity of the GraphRicciCurvature library's output. ```APIDOC ## Set Verbose Level ### Description Configures the level of detail for output messages from the GraphRicciCurvature library. ### Method `GraphRicciCurvature.util.set_verbose(verbose)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **verbose** (*string*) – The desired verbosity level. Options are "INFO", "TRACE", "DEBUG", "ERROR". Defaults to "ERROR". - "INFO": Shows only iteration process logs. - "TRACE": Shows detailed iteration process logs. - "DEBUG": Shows all output logs. - "ERROR": Only shows logs when an error occurs. ### Request Example ```python GraphRicciCurvature.util.set_verbose("INFO") ``` ### Response #### Success Response (200) No explicit return value, but the library's output behavior is updated. #### Response Example None ``` -------------------------------- ### Compute Ricci Flow Iterations Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Set verbosity to ERROR and compute Ricci flow. This is useful for tuning the number of iterations to compress curves in a graph. ```python orc_polbooks.set_verbose("ERROR") orc_polbooks.compute_ricci_flow() ``` -------------------------------- ### Draw Graph with Hierarchical Cutoff Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Visualizes the graph structure using a lower cutoff value, demonstrating hierarchical community detection. This can reveal nested community structures within the graph. ```python draw_graph(my_surgery(G_rf2, cut=1.11)) ``` -------------------------------- ### Detect Communities using Ricci Flow Source: https://github.com/saibalmars/graphriccicurvature/blob/master/notebooks/tutorial.ipynb Calls the ricci_community method to detect communities and identify cutpoints. The function returns a tuple containing the cutpoint and a dictionary of communities. ```python cc = orc_football.ricci_community() ``` -------------------------------- ### Class: OllivierRicci Source: https://github.com/saibalmars/graphriccicurvature/blob/master/doc/source/GraphRicciCurvature.md The OllivierRicci class computes the Ollivier-Ricci curvature for nodes and edges in a NetworkX graph. ```APIDOC ## Class: OllivierRicci ### Description A class to compute the Ollivier-Ricci curvature of a given NetworkX graph. Node Ricci curvature is defined as the average of all its adjacency edges. ### Constructor Parameters - **G** (NetworkX graph) - Required - The input graph. - **weight** (str) - Optional - Edge weight attribute. (Default: "weight") - **alpha** (float) - Optional - (Default: 0.5) - **method** (str) - Optional - (Default: "OTDSinkhornMix") - **base** (float) - Optional - (Default: 2.718281828459045) - **exp_power** (int) - Optional - (Default: 2) - **proc** (int) - Optional - (Default: 16) - **chunksize** (int) - Optional - (Default: None) - **shortest_path** (str) - Optional - (Default: "all_pairs") - **cache_maxsize** (int) - Optional - (Default: 1000000) - **nbr_topk** (int) - Optional - (Default: 3000) - **verbose** (str) - Optional - (Default: "ERROR") ``` -------------------------------- ### Detect Communities via Ricci Flow Source: https://context7.com/saibalmars/graphriccicurvature/llms.txt Identifies graph communities by analyzing modularity drops during the removal of high-weight edges. Requires prior computation of Ricci flow. ```python import networkx as nx from GraphRicciCurvature.OllivierRicci import OllivierRicci G = nx.karate_club_graph() # Compute Ricci flow first orc = OllivierRicci(G, alpha=0.5, method="OTD", verbose="INFO") orc.compute_ricci_flow(iterations=50) # Detect communities cutoff, clustering = orc.ricci_community( cutoff_step=0.025, # Step size for finding cutoff points drop_threshold=0.01 # Minimum modularity drop threshold ) print(f"Best cutoff value: {cutoff:.4f}") print(f"Number of communities: {len(set(clustering.values()))}") # clustering is a dict: {node: community_id} for node in [0, 1, 33, 32]: print(f"Node {node} -> Community {clustering[node]}") # Output: # Best cutoff value: 1.2875 # Number of communities: 2 # Node 0 -> Community 0 # Node 1 -> Community 0 ```