CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-hypernetx

Python library for the creation and study of hypergraphs with analysis, visualization, and algorithm capabilities

Pending
Overview
Eval results
Files

core-hypergraph.mddocs/

Core Hypergraph Operations

Primary hypergraph data structure with construction, manipulation, and basic analysis methods. The Hypergraph class provides the foundation for all hypergraph operations in HyperNetX.

Capabilities

Hypergraph Construction

Create hypergraphs from various data sources including pandas DataFrames, dictionaries, lists, and numpy arrays. Supports flexible property and weight specification.

class Hypergraph:
    def __init__(
        self,
        setsystem: Union[DataFrame, Dict, List, ndarray, None] = None,
        default_cell_weight: Union[int, float] = 1,
        edge_col: int = 0,
        node_col: int = 1,
        cell_weight_col: str = "weight",
        misc_cell_properties_col: Optional[str] = None,
        aggregate_by: str = "first",
        properties: Union[DataFrame, Dict, None] = None,
        misc_properties_col: Optional[str] = None,
        weight_prop_col: str = "weight",
        default_weight: Union[int, float] = 1,
        edge_properties: Union[DataFrame, Dict, None] = None,
        misc_edge_properties_col: Optional[str] = None,
        edge_weight_prop_col: str = "weight",
        default_edge_weight: Union[int, float] = 1,
        node_properties: Union[DataFrame, Dict, None] = None,
        misc_node_properties_col: Optional[str] = None,
        node_weight_prop_col: str = "weight",
        default_node_weight: Union[int, float] = 1,
        name: Optional[str] = None,
        **kwargs
    ):
        """
        Create a hypergraph from various data sources.
        
        Parameters:
        - setsystem: Data source (DataFrame, dict of iterables, dict of dicts, list, array)
        - default_cell_weight: Default weight for incidence pairs
        - edge_col, node_col: Column indices for DataFrame input
        - cell_weight_col: Column name for incidence weights
        - misc_cell_properties_col: Column for misc cell properties
        - aggregate_by: Aggregation method for duplicate incidences ("first", "sum", etc.)
        - properties: Combined properties for all objects
        - misc_properties_col: Column for misc properties
        - weight_prop_col: Weight property column name
        - default_weight: Default weight value
        - edge_properties, node_properties: Separate property data
        - misc_edge_properties_col, misc_node_properties_col: Misc property columns
        - edge_weight_prop_col, node_weight_prop_col: Weight property column names
        - default_edge_weight, default_node_weight: Default weights
        - name: Optional hypergraph name
        - **kwargs: Additional keyword arguments for backward compatibility
        """

Alternative Constructors

Class methods for creating hypergraphs from specialized data formats.

@classmethod
def from_bipartite(
    cls,
    B,
    node_id: int = 1,
    name: Optional[str] = None,
    **kwargs
) -> "Hypergraph":
    """Create hypergraph from NetworkX bipartite graph."""

@classmethod
def from_incidence_matrix(
    cls,
    M,
    name: Optional[str] = None,
    **kwargs
) -> "Hypergraph":
    """Create hypergraph from incidence matrix."""

@classmethod
def from_numpy_array(
    cls,
    M: ndarray,
    node_names: Optional[List] = None,
    edge_names: Optional[List] = None,
    name: Optional[str] = None,
    key: Optional[str] = None,
    **kwargs
) -> "Hypergraph":
    """Create hypergraph from numpy array."""

@classmethod
def from_incidence_dataframe(
    cls,
    df: DataFrame,
    name: Optional[str] = None,
    fillna: Any = 0,
    key: Optional[str] = None,
    return_only_dataframe: bool = False,
    **kwargs
) -> "Hypergraph":
    """Create hypergraph from incidence DataFrame."""

Basic Properties and Structure

Access fundamental hypergraph properties and structural information.

def order(self) -> int:
    """Number of nodes in the hypergraph."""

@property
def shape(self) -> tuple:
    """Tuple of (number of nodes, number of edges)."""

def degree(
    self,
    node_uid: Union[str, int],
    s: int = 1,
    max_size: Optional[int] = None
) -> int:
    """
    Node degree (number of edges containing the node).
    
    Parameters:
    - node_uid: Node identifier
    - s: Level for s-degree calculation
    - max_size: Maximum edge size to consider
    
    Returns:
    Node degree
    """

def size(
    self,
    edge: Union[str, int],
    nodeset: Optional[set] = None
) -> int:
    """
    Edge size (number of nodes in the edge).
    
    Parameters:
    - edge: Edge identifier
    - nodeset: Restrict to nodes in this set
    
    Returns:
    Edge size
    """

def dim(self, edge: Union[str, int]) -> int:
    """Edge dimension (size - 1)."""

@property
def edges(self) -> "HypergraphView":
    """View of hypergraph edges."""

@property
def nodes(self) -> "HypergraphView":
    """View of hypergraph nodes."""

@property
def incidences(self) -> "HypergraphView":
    """View of hypergraph incidences (edge-node pairs)."""

@property
def incidence_dict(self) -> Dict[Union[str, int], List]:
    """Dictionary mapping edge UIDs to lists of node UIDs."""

Matrix Representations

Convert hypergraph to various matrix formats for analysis and computation.

def incidence_matrix(
    self,
    index: bool = False,
    weights: bool = False
):
    """
    Sparse incidence matrix representation.
    
    Parameters:
    - index: Include row/column indices
    - weights: Include edge/node weights
    
    Returns:
    Scipy sparse matrix (and indices if requested)
    """

def incidence_dataframe(self, weights: bool = False) -> DataFrame:
    """Incidence matrix as pandas DataFrame."""

def adjacency_matrix(
    self,
    s: int = 1,
    index: bool = False
):
    """
    Node s-adjacency matrix.
    
    Parameters:
    - s: Level of adjacency (nodes connected by edges of size ≥ s+1)
    - index: Include row/column indices
    
    Returns:
    Scipy sparse matrix (and indices if requested)
    """

def edge_adjacency_matrix(
    self,
    s: int = 1,
    index: bool = False
):
    """Edge s-adjacency matrix."""

def auxiliary_matrix(
    self,
    s: int = 1,
    node: bool = True,
    index: bool = False
):
    """Auxiliary matrix for node or edge analysis."""

Adding Elements

Methods to add nodes, edges, and incidences to the hypergraph.

def add_node(
    self,
    node_uid: Union[str, int],
    inplace: bool = True,
    **attr
) -> Optional["Hypergraph"]:
    """Add a single node with optional attributes."""

def add_nodes_from(
    self,
    node_uids: List[Union[str, int]],
    inplace: bool = True
) -> Optional["Hypergraph"]:
    """Add multiple nodes from iterable."""

def add_edge(
    self,
    edge_uid: Union[str, int],
    inplace: bool = True,
    **attr
) -> Optional["Hypergraph"]:
    """Add a single edge with optional attributes."""

def add_edges_from(
    self,
    edge_uids: List[Union[str, int]],
    inplace: bool = True
) -> Optional["Hypergraph"]:
    """Add multiple edges from iterable."""

def add_incidence(
    self,
    edge_uid: Union[str, int],
    node_uid: Union[str, int],
    inplace: bool = True,
    **attr
) -> Optional["Hypergraph"]:
    """Add a single incidence (edge-node pair)."""

def add_incidences_from(
    self,
    incidences: List[tuple],
    inplace: bool = True
) -> Optional["Hypergraph"]:
    """Add multiple incidences from iterable of tuples."""

def add_nodes_to_edges(
    self,
    edge_dict: Dict[Union[str, int], List[Union[str, int]]],
    inplace: bool = True
) -> Optional["Hypergraph"]:
    """Add nodes to edges using dictionary mapping."""

Removing Elements

Methods to remove nodes, edges, and incidences from the hypergraph.

def remove_nodes(
    self,
    node_uids: List[Union[str, int]],
    name: Optional[str] = None,
    inplace: bool = True
) -> Optional["Hypergraph"]:
    """Remove nodes and all incident edges."""

def remove_edges(
    self,
    edge_uids: List[Union[str, int]],
    name: Optional[str] = None,
    inplace: bool = True
) -> Optional["Hypergraph"]:
    """Remove edges from hypergraph."""

def remove_incidences(
    self,
    incidence_uids: List[tuple],
    name: Optional[str] = None,
    inplace: bool = True
) -> Optional["Hypergraph"]:
    """Remove specific incidences (edge-node pairs)."""

def remove_singletons(self, name: Optional[str] = None) -> "Hypergraph":
    """Remove singleton edges (edges with only one node)."""

Property Management

Access and manipulate properties of nodes, edges, and incidences.

def get_properties(
    self,
    uid: Union[str, int, tuple],
    level: int = 0,
    prop_name: Optional[str] = None
) -> Union[Dict[str, Any], Any]:
    """
    Get properties of a hypergraph object.
    
    Parameters:
    - uid: Object identifier (node, edge, or incidence tuple)
    - level: Object level (0=incidence, 1=node, 2=edge)
    - prop_name: Specific property name (returns all if None)
    
    Returns:
    Property dictionary or specific property value
    """

def get_cell_properties(
    self,
    edge_uid: Union[str, int],
    node_uid: Union[str, int],
    prop_name: Optional[str] = None
) -> Union[Dict[str, Any], Any]:
    """Get properties of a specific incidence (cell)."""

Copying and Modification

Create copies and modify hypergraph structure.

def clone(self, name: Optional[str] = None) -> "Hypergraph":
    """Create a deep copy of the hypergraph."""

def rename(
    self,
    edges: Optional[Dict] = None,
    nodes: Optional[Dict] = None,
    name: Optional[str] = None,
    inplace: bool = True
) -> Optional["Hypergraph"]:
    """
    Rename edges and/or nodes.
    
    Parameters:
    - edges: Dictionary mapping old edge names to new names
    - nodes: Dictionary mapping old node names to new names
    - name: New hypergraph name
    - inplace: Modify in place or return new hypergraph
    """

def restrict_to_nodes(
    self,
    nodes: List[Union[str, int]],
    name: Optional[str] = None
) -> "Hypergraph":
    """Create hypergraph restricted to specified nodes."""

def restrict_to_edges(
    self,
    edges: List[Union[str, int]],
    name: Optional[str] = None
) -> "Hypergraph":
    """Create hypergraph restricted to specified edges."""

Set Operations

Combine hypergraphs using set operations.

def sum(
    self,
    other: "Hypergraph",
    name: Optional[str] = None
) -> "Hypergraph":
    """Union of two hypergraphs."""

def union(
    self,
    other: "Hypergraph",
    name: Optional[str] = None
) -> "Hypergraph":
    """Alias for sum operation."""

def difference(
    self,
    other: "Hypergraph",
    name: Optional[str] = None
) -> "Hypergraph":
    """Difference of two hypergraphs."""

def intersection(
    self,
    other: "Hypergraph",
    name: Optional[str] = None
) -> "Hypergraph":
    """Intersection of two hypergraphs."""

Specialized Operations

Advanced operations for hypergraph analysis and transformation.

def dual(
    self,
    name: Optional[str] = None,
    share_properties: bool = True
) -> "Hypergraph":
    """Create dual hypergraph (edges become nodes, nodes become edges)."""

def bipartite(
    self,
    keep_data: bool = False,
    directed: bool = False
):
    """Convert to NetworkX bipartite graph representation."""

def toplexes(self, return_hyp: bool = False):
    """
    Get maximal edges (toplexes) - edges not contained in any other edge.
    
    Parameters:
    - return_hyp: Return as new hypergraph if True, otherwise return set
    
    Returns:
    Set of toplex edge UIDs or new Hypergraph
    """

def singletons(self) -> set:
    """Get singleton edges (edges containing only one node)."""

def edge_size_dist(self) -> Dict[int, int]:
    """Distribution of edge sizes."""

def collapse_edges(
    self,
    use_reps: Optional[Dict] = None,
    use_keys: Optional[str] = None,
    return_new: bool = False,
    name: Optional[str] = None
) -> Optional["Hypergraph"]:
    """Collapse duplicate or similar edges."""

def collapse_nodes(
    self,
    use_reps: Optional[Dict] = None,
    use_keys: Optional[str] = None,
    return_new: bool = False,
    name: Optional[str] = None
) -> Optional["Hypergraph"]:
    """Collapse duplicate or similar nodes."""

def collapse_nodes_and_edges(
    self,
    node_reps: Optional[Dict] = None,
    edge_reps: Optional[Dict] = None,
    node_keys: Optional[str] = None,
    edge_keys: Optional[str] = None,
    return_new: bool = False,
    name: Optional[str] = None
) -> Optional["Hypergraph"]:
    """Collapse both nodes and edges simultaneously."""

Neighborhood and Relationships

Query node and edge relationships and neighborhoods.

def neighbors(
    self,
    node: Union[str, int],
    s: int = 1
) -> set:
    """
    Get s-neighbors of a node.
    
    Parameters:
    - node: Node identifier
    - s: Neighborhood level (nodes connected through edges of size ≥ s+1)
    
    Returns:
    Set of neighboring node UIDs
    """

def edge_neighbors(
    self,
    edge: Union[str, int],
    s: int = 1
) -> set:
    """Get s-neighbors of an edge."""

Connectivity Analysis

Methods for analyzing hypergraph connectivity at different levels.

def is_connected(
    self,
    s: int = 1,
    edges: bool = False
) -> bool:
    """
    Check if hypergraph is s-connected.
    
    Parameters:
    - s: Connectivity level
    - edges: Check edge connectivity instead of node connectivity
    
    Returns:
    Boolean indicating connectivity
    """

def s_connected_components(
    self,
    s: int = 1,
    edges: bool = True,
    return_singletons: bool = False
) -> List[set]:
    """
    Find s-connected components.
    
    Parameters:
    - s: Connectivity level  
    - edges: Return edge components (True) or node components (False)
    - return_singletons: Include singleton components
    
    Returns:
    List of sets containing component members
    """

def s_component_subgraphs(
    self,
    s: int = 1,
    edges: bool = True,
    return_singletons: bool = False,
    name: Optional[str] = None
) -> List["Hypergraph"]:
    """Get subgraphs for each s-connected component."""

def s_components(
    self,
    s: int = 1,
    edges: bool = True,
    return_singletons: bool = True
) -> List[set]:
    """Alias for s_connected_components."""

def connected_components(
    self,
    edges: bool = False
) -> List[set]:
    """Find connected components (s=1)."""

def connected_component_subgraphs(
    self,
    return_singletons: bool = True,
    name: Optional[str] = None
) -> List["Hypergraph"]:
    """Get subgraphs for connected components."""

def components(
    self,
    edges: bool = False
) -> List[set]:
    """Alias for connected_components."""

def component_subgraphs(
    self,
    return_singletons: bool = False,
    name: Optional[str] = None
) -> List["Hypergraph"]:
    """Alias for connected_component_subgraphs."""

Distance and Diameter Analysis

Methods for computing distances and diameters in hypergraphs.

def distance(
    self,
    source: Union[str, int],
    target: Union[str, int],
    s: int = 1
) -> int:
    """
    Shortest path distance between two nodes.
    
    Parameters:
    - source: Source node UID
    - target: Target node UID  
    - s: Distance level (paths through edges of size ≥ s+1)
    
    Returns:
    Shortest path distance
    """

def edge_distance(
    self,
    source: Union[str, int],
    target: Union[str, int],
    s: int = 1
) -> int:
    """Shortest path distance between two edges."""

def diameter(
    self,
    s: int = 1
) -> int:
    """
    Maximum distance between any pair of nodes.
    
    Parameters:
    - s: Diameter level
    
    Returns:
    Hypergraph diameter
    """

def edge_diameter(
    self,
    s: int = 1
) -> int:
    """Maximum distance between any pair of edges."""

def node_diameters(
    self,
    s: int = 1
) -> Dict[Union[str, int], int]:
    """
    All pairwise distances for nodes.
    
    Parameters:
    - s: Distance level
    
    Returns:
    Dictionary of node UIDs to their maximum distances
    """

def edge_diameters(
    self,
    s: int = 1
) -> Dict[Union[str, int], int]:
    """All pairwise distances for edges."""

Advanced Operations

Additional methods for hypergraph analysis and manipulation.

def equivalence_classes(
    self,
    edges: bool = True
) -> List[set]:
    """
    Find equivalence classes of edges or nodes.
    
    Parameters:
    - edges: Find edge equivalence classes (True) or node classes (False)
    
    Returns:
    List of sets containing equivalent elements
    """

def get_linegraph(
    self,
    s: int = 1,
    edges: bool = True
):
    """
    Create line graph representation.
    
    Parameters:
    - s: Level for line graph construction
    - edges: Create edge line graph (True) or node line graph (False)
    
    Returns:
    NetworkX graph representing the line graph
    """

def set_state(
    self,
    **kwargs
):
    """
    Set hypergraph state with keyword arguments.
    
    Parameters:
    - **kwargs: State properties to set
    """

Properties and Special Methods

Property accessors and special method operations.

@property
def dataframe(self) -> DataFrame:
    """Access underlying dataframe representation."""

@property  
def properties(self) -> "PropertyStore":
    """Access property store."""

def __len__(self) -> int:
    """Return number of nodes."""

def __iter__(self):
    """Iterate over nodes."""

def __contains__(self, item) -> bool:
    """Test if item is a node in the hypergraph."""

def __getitem__(self, node):
    """Access neighbors of a node."""

def __eq__(self, other) -> bool:
    """Test equality with another hypergraph."""

def __add__(self, other) -> "Hypergraph":
    """Addition operator (union)."""

def __sub__(self, other) -> "Hypergraph":
    """Subtraction operator (difference)."""

Install with Tessl CLI

npx tessl i tessl/pypi-hypernetx

docs

algorithms.md

analysis-metrics.md

core-hypergraph.md

index.md

utilities.md

visualization.md

tile.json