PPINetwork¶
- class graph.PPINetwork.PPINetwork(data: dict | None = None, G: networkx.Graph | None = None, score_attr: str = 'score')[source]¶
Bases:
objectA protein-protein interaction (PPI) network wrapper around NetworkX graphs.
This class provides a comprehensive interface for working with PPI networks, including network construction from STRING data, computation of global, node-level, and edge-level metrics, export to various formats, and enrichment analysis (GSEA).
- G¶
The underlying NetworkX graph object.
- Type:
nx.Graph
- node_metrics_df¶
DataFrame containing node-level metrics.
- Type:
pd.DataFrame
- edge_metrics_df¶
DataFrame containing edge-level metrics.
- Type:
pd.DataFrame
- graph_metrics¶
Dictionary of global network metrics.
- Type:
dict
- gsea_results_df¶
GSEA enrichment results.
- Type:
pd.DataFrame
- ranked_genes_df¶
Genes ranked by a network metric.
- Type:
pd.DataFrame
- score_attr¶
Name of the edge attribute used as the interaction score.
- Type:
str
Example
>>> loader = StringLoader(protein_query=["TP53", "BRCA1"], species=9606) >>> data = loader.retrieve_data().standardize_data_format().get_data() >>> ppin = PPINetwork(data=data) >>> ppin.compute_all_node_metrics() >>> print(ppin.node_metrics_df.head())
- compute_all_edge_metrics(weighted=True) pandas.DataFrame[source]¶
Computes all edge-level metrics and returns a DataFrame with the results.
- compute_all_global_metrics(weighted=True) dict[source]¶
Computes all global metrics and returns a dictionary with the results.
- compute_all_metrics(weighted=True) tuple[pandas.DataFrame, pandas.DataFrame, dict, networkx.Graph][source]¶
Calls all metric computation methods and returns the results as DataFrames and dictionaries.
- compute_all_node_metrics(weighted=True) pandas.DataFrame[source]¶
Computes all node-level metrics and returns a DataFrame with the results.
- compute_average_clustering(weighted=True) float[source]¶
Returns the average clustering coefficient of the network.
- compute_average_neighbor_degree(weighted=True) Dict[str, float][source]¶
Computes the average neighbor degree of each node in the network.
- compute_average_shortest_path_length(weighted=True) float[source]¶
Returns the average shortest path length of the network.
- compute_betweenness_centrality(weighted=True) Dict[str, float][source]¶
Computes the betweenness centrality of each node in the network.
- compute_bridging_centrality(weighted=True) Dict[str, float][source]¶
Computes a simple bridging centrality.
- It combines:
betweenness centrality
bridging coefficient
- compute_closeness_centrality(weighted=True) Dict[str, float][source]¶
Computes the closeness centrality of each node in the network.
- compute_clustering_coefficient(weighted=True) Dict[str, float][source]¶
Computes the clustering coefficient of each node in the network.
- compute_communities(weighted=True) Dict[str, int][source]¶
Computes communities in the network using the greedy modularity maximization algorithm.
- compute_community_roles() pandas.DataFrame[source]¶
Computes the community roles in the network. Using the method described in Guimerà & Amaral (2005), it calculates: - within_community_degree - participation_coefficient - within_module_z_score
- compute_connected_components() Tuple[dict[Any, Any], dict[Any, Any]][source]¶
Computes the connected components of the network.
- compute_core_number() Dict[str, float][source]¶
Computes the core number of each node in the network.
- compute_edge_betweenness_centrality(weighted=True) dict[tuple[_Node, _Node], float] | Any[source]¶
Computes the edge betweenness centrality of each edge in the network.
- compute_eigenvector_centrality(weighted=True) Dict[str, float][source]¶
Computes the eigenvector centrality of each node in the network.
- compute_harmonic_centrality(weighted=True) Dict[str, float][source]¶
Computes the harmonic centrality of each node in the network.
- compute_katz_centrality(alpha=0.01, beta=1.0, weighted=True) Dict[str, float][source]¶
Computes the Katz centrality of each node in the network.
- compute_largest_component_size() int[source]¶
Returns the size of the largest connected component in the network.
- compute_node_removal_impact() pandas.DataFrame[source]¶
Computes the impact of removing each node on the network.
- compute_number_connected_components() int[source]¶
Returns the number of connected components in the network.
- compute_pagerank(weighted=True) Dict[str, float][source]¶
Computes the pagerank of each node in the network.
- compute_weighted_degree() Dict[str, int][source]¶
Computes the weighted degree of each node in the network using the ‘confidence’ edge attribute.
- export_for_cytoscape(output_dir: str, basename='ppi_network', include_tables=True, include_graph_metrics=True) dict[str, str][source]¶
Exports the network in Cytoscape-compatible files.
- Main output:
<basename>.graphml
- Optional companion files:
<basename>_nodes.csv
<basename>_edges.csv
<basename>_graph_metrics.json
- The GraphML file can be loaded in Cytoscape Desktop with:
File > Import > Network from File
- get_consensus_hub_proteins(top_n=10, attributes=None) pandas.DataFrame[source]¶
Returns hub proteins using a consensus score.
The score is the average percentile rank across several metrics.
- get_edges_metric_value(attr: str) Tuple[List[Any], List[str]][source]¶
Read all edges metric values sorted by the same metric in descending order. Also return edge identifiers in the same order.
- get_hub_proteins(node_attribute: str, top_n=10, ascending=False) pandas.DataFrame[source]¶
Returns top hub proteins according to one node attribute.
- Example attributes:
degree
weighted_degree
betweenness_centrality
closeness_centrality
harmonic_centrality
eigenvector_centrality
pagerank
katz_centrality
core_number
bridging_centrality
within_module_z_score
participation_coefficient
largest_component_loss
- get_nodes_metric_value(metric: str, sort: bool = False) Tuple[List[Any], List[str]][source]¶
Read all nodes metric values. If sort=True, values are sorted by the same metric in descending order.
- get_nodes_preferred_names() List[str][source]¶
Return a list of preferred names for all nodes in the network.
- get_numeric_edge_attrs() List[str][source]¶
Return edge attributes that contain at least one finite numeric value.
- get_numeric_node_attrs() List[str][source]¶
Return node attributes that contain at least one finite numeric value
- networkx_to_cytoscape_elements(node_color_attr='pagerank', node_size_attr='degree', edge_width_attr='score', cmap_name='viridis', min_node_size=35, max_node_size=100, min_edge_width=1, max_edge_width=10) list[dict[str, Any]][source]¶
Convert a NetworkX graph into Cytoscape.js elements.
Initial node color is based on node_color_attr. Initial node size is based on node_size_attr. Initial edge width is based on edge_width_attr.
The generated HTML can later recompute these values interactively.
- plot_gsea_dotplot(gsea_results_df: pandas.DataFrame, column: str = 'FDR q-val', title: str = 'GSEA enrichment dotplot', cutoff: float = 0.25, top_term: int = 10, size: float = 6, figsize: tuple = (6, 5), cmap: str = 'viridis', show_ring: bool = False) str[source]¶
Plot GSEA results as a dotplot using GSEApy.
- Parameters:
gsea_results_df – Result DataFrame returned by run_gsea(). Usually pre_res.res2d.
column – Column used to color the dots. For preranked GSEA use usually: - “FDR q-val” - “NOM p-val” Defaults to “FDR q-val”.
title – Plot title. Defaults to “GSEA enrichment dotplot”.
cutoff – Only terms with column value <= cutoff are shown. Defaults to 0.25.
top_term – Number of top enriched terms to show. Defaults to 10.
size – Dot size scaling. Defaults to 6.
figsize – Figure size (width, height). Defaults to (6, 5).
cmap – Matplotlib colormap. Defaults to “viridis”.
show_ring – Whether to draw an outer ring around dots. Defaults to False.
- Returns:
Base64-encoded PNG image as a data URI.
- Return type:
str
- Raises:
ValueError – If gsea_results_df is empty.
ValueError – If the specified column is not found in gsea_results_df.
- prepare_string_weights() networkx.Graph[source]¶
- Adds two edge attributes:
confidence: normalized DB score
distance: inverse confidence, useful for shortest paths
The new STRING APIs give already normalized scores, but for coherence and back compatibility, the confidence will still be calculated as score / 1000 if the max score is greater than 1.
- run_gsea(node_attribute: str, gene_sets: str = 'Reactome_2022', gene_symbol_attr: str = 'preferredName', min_size: int = 5, max_size: int = 1000, permutation_num: int = 1000, threads: int = 4, seed: int = 42, outdir: str | None = None, ascending: bool = False) Tuple[pandas.DataFrame, pandas.DataFrame][source]¶
Run preranked GSEA using a node metric as ranking score.
- Parameters:
node_attribute – Node metric used to rank genes. Examples: - “degree” - “weighted_degree” - “degree_centrality” - “betweenness_centrality” - “closeness_centrality” - “eigenvector_centrality” - “pagerank” - “bridging_centrality” - “core_number”
gene_sets – Gene set collection used by GSEApy. Defaults to “Reactome_2022”. Examples: - “Reactome_2022” - “KEGG_2021_Human” - “GO_Biological_Process_2023” - Path to a .gmt file - Dictionary of custom gene sets
gene_symbol_attr – Node attribute containing the gene symbol. In STRING networks this is “preferredName”. Defaults to “preferredName”.
min_size – Minimum gene-set size. Defaults to 5.
max_size – Maximum gene-set size. Defaults to 1000.
permutation_num – Number of permutations. Defaults to 1000.
threads – Number of CPU threads. Defaults to 4.
seed – Random seed. Defaults to 42.
outdir – Output directory. If None, GSEApy does not write files to disk. Defaults to None.
ascending – If False, highest scores are placed at the top of the ranked list. This is usually correct for centrality-based GSEA. Defaults to False.
- Returns:
A tuple of (ranked_genes_df, gsea_results_df).
- Return type:
Tuple[pd.DataFrame, pd.DataFrame]
- Raises:
ValueError – If node_attribute is not found in node attributes.
ValueError – If gene_symbol_attr is not found in node attributes.
ValueError – If no valid gene-score pairs are available for GSEA.