Python library for the creation and study of hypergraphs with analysis, visualization, and algorithm capabilities
—
Data conversion utilities, HIF format support, statistical reporting functions, and example datasets for experimentation and learning.
HIF (Hypergraph Interchange Format) provides standardized JSON-based serialization for hypergraphs, enabling interoperability and data exchange.
def to_hif(
hg: "Hypergraph",
filename: Optional[str] = None,
network_type: str = "undirected",
metadata: Optional[Dict] = None
) -> Dict:
"""
Convert hypergraph to HIF JSON format.
Parameters:
- hg: Input hypergraph
- filename: Output file path (optional)
- network_type: Network type ("undirected", "directed", "asc")
- metadata: Additional metadata to include
Returns:
HIF dictionary (also saves to file if filename provided)
"""
def from_hif(
hif: Optional[Dict] = None,
filename: Optional[str] = None
) -> "Hypergraph":
"""
Create hypergraph from HIF JSON format.
Parameters:
- hif: HIF dictionary (if reading from memory)
- filename: HIF file path (if reading from file)
Returns:
Hypergraph object created from HIF data
"""Usage example:
import hypernetx as hnx
# Create hypergraph
H = hnx.Hypergraph({'E1': ['A', 'B', 'C'], 'E2': ['B', 'C', 'D']})
# Export to HIF format
hif_data = hnx.to_hif(H, filename='my_hypergraph.json')
# Import from HIF format
H_restored = hnx.from_hif(filename='my_hypergraph.json')
# Or work with HIF data directly
H_from_dict = hnx.from_hif(hif=hif_data)Comprehensive statistical analysis functions for hypergraph structure and properties.
def info(H: "Hypergraph") -> str:
"""
General hypergraph information summary.
Parameters:
- H: Input hypergraph
Returns:
Formatted string with hypergraph statistics
"""
def info_dict(H: "Hypergraph") -> Dict[str, Any]:
"""
Hypergraph information as dictionary.
Parameters:
- H: Input hypergraph
Returns:
Dictionary with hypergraph statistics
"""
def degree_dist(H: "Hypergraph") -> Dict[int, int]:
"""
Node degree distribution.
Parameters:
- H: Input hypergraph
Returns:
Dictionary mapping degrees to counts
"""
def edge_size_dist(H: "Hypergraph") -> Dict[int, int]:
"""
Edge size distribution.
Parameters:
- H: Input hypergraph
Returns:
Dictionary mapping edge sizes to counts
"""
def comp_dist(H: "Hypergraph") -> Dict[int, int]:
"""Connected component size distribution."""
def s_comp_dist(
H: "Hypergraph",
s: int = 1
) -> Dict[int, int]:
"""S-connected component size distribution."""
def toplex_dist(H: "Hypergraph") -> Dict[int, int]:
"""Toplex (maximal edge) size distribution."""
def s_node_diameter_dist(
H: "Hypergraph",
s: int = 1
) -> Dict[int, int]:
"""S-node diameter distribution across components."""
def s_edge_diameter_dist(
H: "Hypergraph",
s: int = 1
) -> Dict[int, int]:
"""S-edge diameter distribution across components."""
def centrality_stats(
H: "Hypergraph",
measures: List[str] = None
) -> Dict[str, Dict]:
"""
Compute various centrality statistics.
Parameters:
- H: Input hypergraph
- measures: List of centrality measures to compute
Returns:
Dictionary with centrality statistics
"""
def dist_stats(distribution: Dict[int, int]) -> Dict[str, float]:
"""
Compute statistics for a distribution.
Parameters:
- distribution: Dictionary mapping values to counts
Returns:
Dictionary with mean, std, min, max, etc.
"""Helper classes and utility functions for data manipulation and processing.
class HNXCount:
"""Counter class optimized for HyperNetX operations."""
def __init__(self, data=None):
"""Initialize counter with optional data."""
def update(self, other):
"""Update counter with additional data."""
def most_common(self, n=None):
"""Return most common elements."""
class DefaultOrderedDict:
"""Ordered dictionary with default factory."""
def __init__(self, default_factory=None):
"""Initialize with default factory function."""
def remove_row_duplicates(df: DataFrame) -> DataFrame:
"""
Remove duplicate rows from DataFrame.
Parameters:
- df: Input DataFrame
Returns:
DataFrame with duplicates removed
"""
def reverse_dictionary(d: Dict) -> Dict:
"""
Reverse a dictionary (values become keys, keys become values).
Parameters:
- d: Input dictionary
Returns:
Reversed dictionary
"""
def not_implemented_for(*args):
"""
Decorator to mark functions as not implemented for certain graph types.
Usage:
@not_implemented_for('directed')
def my_function(H):
# Function implementation
"""Pre-built dataset classes providing standard hypergraph examples for learning and experimentation.
class LesMis:
"""Les Misérables character co-appearance hypergraph."""
def __init__(self):
"""Initialize Les Misérables dataset."""
def hypergraph(self) -> "Hypergraph":
"""Get hypergraph representation."""
def dataframe(self) -> DataFrame:
"""Get raw data as DataFrame."""
def lesmis_hypergraph_from_df(df: DataFrame) -> "Hypergraph":
"""
Create Les Misérables hypergraph from DataFrame.
Parameters:
- df: Les Misérables data DataFrame
Returns:
Hypergraph of character co-appearances
"""
def book_tour(H: "Hypergraph") -> Any:
"""
Create book tour visualization for Les Misérables hypergraph.
Parameters:
- H: Les Misérables hypergraph
Returns:
Interactive visualization
"""
class HarryPotter:
"""Harry Potter character interaction hypergraph."""
def __init__(self):
"""Initialize Harry Potter dataset."""
def hypergraph(self) -> "Hypergraph":
"""Get hypergraph representation."""
class GeneData:
"""Gene interaction and pathway hypergraph."""
def __init__(self):
"""Initialize gene data dataset."""
def hypergraph(self) -> "Hypergraph":
"""Get hypergraph representation."""
class TransmissionProblem:
"""Disease transmission network hypergraph."""
def __init__(self):
"""Initialize transmission problem dataset."""
def hypergraph(self) -> "Hypergraph":
"""Get hypergraph representation."""Usage example with datasets:
import hypernetx as hnx
# Use Les Misérables dataset
lesmis = hnx.LesMis()
H_lesmis = lesmis.hypergraph()
# Basic analysis
print(hnx.info(H_lesmis))
print(f"Degree distribution: {hnx.degree_dist(H_lesmis)}")
print(f"Edge size distribution: {hnx.edge_size_dist(H_lesmis)}")
# Use Harry Potter dataset
hp = hnx.HarryPotter()
H_hp = hp.hypergraph()
# Compare datasets
print(f"Les Mis: {H_lesmis.shape}")
print(f"Harry Potter: {H_hp.shape}")
# Gene data for biological networks
genes = hnx.GeneData()
H_genes = genes.hypergraph()
# Transmission problem for epidemiology
trans = hnx.TransmissionProblem()
H_trans = trans.hypergraph()HyperNetX provides specific exception types for error handling.
class HyperNetXException(Exception):
"""Base exception class for HyperNetX."""
class HyperNetXError(Exception):
"""General error class for HyperNetX operations."""
class HyperNetXNotImplementedError(NotImplementedError):
"""Exception for unimplemented functionality."""Usage in error handling:
import hypernetx as hnx
try:
# Some hypergraph operation
H = hnx.Hypergraph(invalid_data)
except hnx.HyperNetXError as e:
print(f"HyperNetX error: {e}")
except hnx.HyperNetXException as e:
print(f"General HyperNetX exception: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-hypernetx