Skip to content

API Reference

This section provides complete documentation for all Hypergraph-DB classes and methods.

Core Classes

HypergraphDB

hyperdb.HypergraphDB dataclass

HypergraphDB(
    storage_file: Union[str, Path] = "my_hypergraph.hgdb",
    _v_data: Dict[str, Any] = dict(),
    _e_data: Dict[Tuple, Any] = dict(),
    _v_inci: Dict[str, Set[Tuple]] = (
        lambda: defaultdict(set)
    )(),
)

Bases: BaseHypergraphDB

Hypergraph database.

all_v cached property

all_v: List[str]

Return a list of all vertices in the hypergraph.

all_e cached property

all_e: List[Tuple]

Return a list of all hyperedges in the hypergraph.

num_v cached property

num_v: int

Return the number of vertices in the hypergraph.

num_e cached property

num_e: int

Return the number of hyperedges in the hypergraph.

__post_init__

__post_init__()
Source code in hyperdb/hypergraph.py
def __post_init__(self):
    assert isinstance(self.storage_file, (str, Path))
    if isinstance(self.storage_file, str):
        self.storage_file = Path(self.storage_file)
    if self.storage_file.exists():
        self.load(self.storage_file)

load

load(storage_file: Path) -> dict

Load the hypergraph database from the storage file.

Source code in hyperdb/hypergraph.py
def load(self, storage_file: Path) -> dict:
    r"""
    Load the hypergraph database from the storage file.
    """
    try:
        with open(storage_file, "rb") as f:
            data = pkl.load(f)
        self._v_data = data.get("v_data", {})
        self._v_inci = data.get("v_inci", {})
        self._e_data = data.get("e_data", {})
        return True
    except Exception as e:
        return False

save

save(storage_file: Path) -> dict

Save the hypergraph database to the storage file.

Source code in hyperdb/hypergraph.py
def save(self, storage_file: Path) -> dict:
    r"""
    Save the hypergraph database to the storage file.
    """
    data = {
        "v_data": self._v_data,
        "v_inci": self._v_inci,
        "e_data": self._e_data,
    }
    try:
        with open(storage_file, "wb") as f:
            pkl.dump(data, f)
        return True
    except Exception as e:
        return False

v

v(v_id: str, default: Any = None) -> dict

Return the vertex data.

Args: v_id (str): The vertex id. default (Any): The default value if the vertex does not exist.

Source code in hyperdb/hypergraph.py
def v(self, v_id: str, default: Any = None) -> dict:
    r"""
    Return the vertex data.

    Args:
        ``v_id`` (``str``): The vertex id.
        ``default`` (``Any``): The default value if the vertex does not exist.
    """
    assert isinstance(v_id, Hashable), "The vertex id must be hashable."
    try:
        return self._v_data[v_id]
    except KeyError:
        return default

e

e(
    e_tuple: Union[List, Set, Tuple], default: Any = None
) -> dict

Return the hyperedge data.

Args: e_tuple (Union[List, Set, Tuple]): The hyperedge tuple: (v1_name, v2_name, ..., vn_name). default (Any): The default value if the hyperedge does not exist.

Source code in hyperdb/hypergraph.py
def e(self, e_tuple: Union[List, Set, Tuple], default: Any = None) -> dict:
    r"""
    Return the hyperedge data.

    Args:
        ``e_tuple`` (``Union[List, Set, Tuple]``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
        ``default`` (``Any``): The default value if the hyperedge does not exist.
    """
    assert isinstance(
        e_tuple, (set, list, tuple)
    ), "The hyperedge must be a set, list, or tuple of vertex ids."
    e_tuple = self.encode_e(e_tuple)
    try:
        return self._e_data[e_tuple]
    except KeyError:
        return default

encode_e

encode_e(e_tuple: Union[List, Set, Tuple]) -> Tuple

Sort and check the hyperedge tuple.

Args: e_tuple (Union[List, Set, Tuple]): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).

Source code in hyperdb/hypergraph.py
def encode_e(self, e_tuple: Union[List, Set, Tuple]) -> Tuple:
    r"""
    Sort and check the hyperedge tuple.

    Args:
        ``e_tuple`` (``Union[List, Set, Tuple]``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
    """
    assert isinstance(
        e_tuple, (list, set, tuple)
    ), "The hyperedge must be a list, set, or tuple of vertex ids."
    tmp = sorted(list(set(e_tuple)))
    for v_id in tmp:
        assert isinstance(v_id, Hashable), "The vertex id must be hashable."
        assert (
            v_id in self._v_data
        ), f"The vertex {v_id} does not exist in the hypergraph."
    return tuple(tmp)

add_v

add_v(v_id: Any, v_data: Optional[Dict] = None)

Add a vertex to the hypergraph.

Args: v_id (Any): The vertex id. v_data (dict, optional): The vertex data.

Source code in hyperdb/hypergraph.py
def add_v(self, v_id: Any, v_data: Optional[Dict] = None):
    r"""
    Add a vertex to the hypergraph.

    Args:
        ``v_id`` (``Any``): The vertex id.
        ``v_data`` (``dict``, optional): The vertex data.
    """
    assert isinstance(v_id, Hashable), "The vertex id must be hashable."
    if v_data is not None:
        assert isinstance(v_data, dict), "The vertex data must be a dictionary."
    else:
        v_data = {}
    if v_id not in self._v_data:
        self._v_data[v_id] = v_data
        self._v_inci[v_id] = set()
    else:
        self._v_data[v_id].update(v_data)
    self._clear_cache()

add_e

add_e(
    e_tuple: Union[List, Set, Tuple],
    e_data: Optional[Dict] = None,
)

Add a hyperedge to the hypergraph.

Args: e_tuple (Union[List, Set, Tuple]): The hyperedge tuple: (v1_name, v2_name, ..., vn_name). e_data (dict, optional): The hyperedge data.

Source code in hyperdb/hypergraph.py
def add_e(self, e_tuple: Union[List, Set, Tuple], e_data: Optional[Dict] = None):
    r"""
    Add a hyperedge to the hypergraph.

    Args:
        ``e_tuple`` (``Union[List, Set, Tuple]``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
        ``e_data`` (``dict``, optional): The hyperedge data.
    """
    assert isinstance(
        e_tuple, (list, set, tuple)
    ), "The hyperedge must be a list, set, or tuple of vertex ids."
    if e_data is not None:
        assert isinstance(e_data, dict), "The hyperedge data must be a dictionary."
    else:
        e_data = {}
    e_tuple = self.encode_e(e_tuple)
    if e_tuple not in self._e_data:
        self._e_data[e_tuple] = e_data
        for v in e_tuple:
            self._v_inci[v].add(e_tuple)
    else:
        self._e_data[e_tuple].update(e_data)
    self._clear_cache()

remove_v

remove_v(v_id: Any)

Remove a vertex from the hypergraph.

Args: v_id (Any): The vertex id.

Source code in hyperdb/hypergraph.py
def remove_v(self, v_id: Any):
    r"""
    Remove a vertex from the hypergraph.

    Args:
        ``v_id`` (``Any``): The vertex id.
    """
    assert isinstance(v_id, Hashable), "The vertex id must be hashable."
    assert (
        v_id in self._v_data
    ), f"The vertex {v_id} does not exist in the hypergraph."
    del self._v_data[v_id]
    old_e_tuples, new_e_tuples = [], []
    for e_tuple in self._v_inci[v_id]:
        new_e_tuple = self.encode_e(set(e_tuple) - {v_id})
        if len(new_e_tuple) >= 2:
            # todo: maybe new e tuple existing in hg, need to merge to hyperedge information
            self._e_data[new_e_tuple] = deepcopy(self._e_data[e_tuple])
        del self._e_data[e_tuple]
        old_e_tuples.append(e_tuple)
        new_e_tuples.append(new_e_tuple)
    del self._v_inci[v_id]
    for old_e_tuple, new_e_tuple in zip(old_e_tuples, new_e_tuples):
        for _v_id in old_e_tuple:
            if _v_id != v_id:
                self._v_inci[_v_id].remove(old_e_tuple)
                if len(new_e_tuple) >= 2:
                    self._v_inci[_v_id].add(new_e_tuple)
    self._clear_cache()

remove_e

remove_e(e_tuple: Union[List, Set, Tuple])

Remove a hyperedge from the hypergraph.

Args: e_tuple (Union[List, Set, Tuple]): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).

Source code in hyperdb/hypergraph.py
def remove_e(self, e_tuple: Union[List, Set, Tuple]):
    r"""
    Remove a hyperedge from the hypergraph.

    Args:
        ``e_tuple`` (``Union[List, Set, Tuple]``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
    """
    assert isinstance(
        e_tuple, (list, set, tuple)
    ), "The hyperedge must be a list, set, or tuple of vertex ids."
    e_tuple = self.encode_e(e_tuple)
    assert (
        e_tuple in self._e_data
    ), f"The hyperedge {e_tuple} does not exist in the hypergraph."
    for v in e_tuple:
        self._v_inci[v].remove(e_tuple)
    del self._e_data[e_tuple]
    self._clear_cache()

update_v

update_v(v_id: Any, v_data: dict)

Update the vertex data.

Args: v_id (Any): The vertex id. v_data (dict): The vertex data.

Source code in hyperdb/hypergraph.py
def update_v(self, v_id: Any, v_data: dict):
    r"""
    Update the vertex data.

    Args:
        ``v_id`` (``Any``): The vertex id.
        ``v_data`` (``dict``): The vertex data.
    """
    assert isinstance(v_id, Hashable), "The vertex id must be hashable."
    assert isinstance(v_data, dict), "The vertex data must be a dictionary."
    assert (
        v_id in self._v_data
    ), f"The vertex {v_id} does not exist in the hypergraph."
    self._v_data[v_id].update(v_data)
    self._clear_cache()

update_e

update_e(e_tuple: Union[List, Set, Tuple], e_data: dict)

Update the hyperedge data.

Args: e_tuple (Union[List, Set, Tuple]): The hyperedge tuple: (v1_name, v2_name, ..., vn_name). e_data (dict): The hyperedge data.

Source code in hyperdb/hypergraph.py
def update_e(self, e_tuple: Union[List, Set, Tuple], e_data: dict):
    r"""
    Update the hyperedge data.

    Args:
        ``e_tuple`` (``Union[List, Set, Tuple]``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
        ``e_data`` (``dict``): The hyperedge data.
    """
    assert isinstance(
        e_tuple, (list, set, tuple)
    ), "The hyperedge must be a list, set, or tuple of vertex ids."
    assert isinstance(e_data, dict), "The hyperedge data must be a dictionary."
    e_tuple = self.encode_e(e_tuple)
    assert (
        e_tuple in self._e_data
    ), f"The hyperedge {e_tuple} does not exist in the hypergraph."
    self._e_data[e_tuple].update(e_data)
    self._clear_cache()

has_v

has_v(v_id: Any) -> bool

Check if the vertex exists.

Args: v_id (Any): The vertex id.

Source code in hyperdb/hypergraph.py
def has_v(self, v_id: Any) -> bool:
    r"""
    Check if the vertex exists.

    Args:
        ``v_id`` (``Any``): The vertex id.
    """
    assert isinstance(v_id, Hashable), "The vertex id must be hashable."
    return v_id in self._v_data

has_e

has_e(e_tuple: Union[List, Set, Tuple]) -> bool

Check if the hyperedge exists.

Args: e_tuple (Union[List, Set, Tuple]): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).

Source code in hyperdb/hypergraph.py
def has_e(self, e_tuple: Union[List, Set, Tuple]) -> bool:
    r"""
    Check if the hyperedge exists.

    Args:
        ``e_tuple`` (``Union[List, Set, Tuple]``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
    """
    assert isinstance(
        e_tuple, (list, set, tuple)
    ), "The hyperedge must be a list, set, or tuple of vertex ids."
    try:
        e_tuple = self.encode_e(e_tuple)
    except AssertionError:
        return False
    return e_tuple in self._e_data

degree_v

degree_v(v_id: Any) -> int

Return the degree of the vertex.

Args: v_id (Any): The vertex id.

Source code in hyperdb/hypergraph.py
def degree_v(self, v_id: Any) -> int:
    r"""
    Return the degree of the vertex.

    Args:
        ``v_id`` (``Any``): The vertex id.
    """
    assert isinstance(v_id, Hashable), "The vertex id must be hashable."
    assert (
        v_id in self._v_data
    ), f"The vertex {v_id} does not exist in the hypergraph."
    return len(self._v_inci[v_id])

degree_e

degree_e(e_tuple: Union[List, Set, Tuple]) -> int

Return the degree of the hyperedge.

Args: e_tuple (Union[List, Set, Tuple]): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).

Source code in hyperdb/hypergraph.py
def degree_e(self, e_tuple: Union[List, Set, Tuple]) -> int:
    r"""
    Return the degree of the hyperedge.

    Args:
        ``e_tuple`` (``Union[List, Set, Tuple]``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
    """
    assert isinstance(
        e_tuple, (list, set, tuple)
    ), "The hyperedge must be a list, set, or tuple of vertex ids."
    e_tuple = self.encode_e(e_tuple)
    assert (
        e_tuple in self._e_data
    ), f"The hyperedge {e_tuple} does not exist in the hypergraph."
    return len(e_tuple)

nbr_e_of_v

nbr_e_of_v(v_id: Any) -> list

Return the incident hyperedges of the vertex.

Args: v_id (Any): The vertex id.

Source code in hyperdb/hypergraph.py
def nbr_e_of_v(self, v_id: Any) -> list:
    r"""
    Return the incident hyperedges of the vertex.

    Args:
        ``v_id`` (``Any``): The vertex id.
    """
    assert isinstance(v_id, Hashable), "The vertex id must be hashable."
    assert (
        v_id in self._v_data
    ), f"The vertex {v_id} does not exist in the hypergraph."
    return set(self._v_inci[v_id])

nbr_v_of_e

nbr_v_of_e(e_tuple: Union[List, Set, Tuple]) -> list

Return the incident vertices of the hyperedge.

Args: e_tuple (Union[List, Set, Tuple]): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).

Source code in hyperdb/hypergraph.py
def nbr_v_of_e(self, e_tuple: Union[List, Set, Tuple]) -> list:
    r"""
    Return the incident vertices of the hyperedge.

    Args:
        ``e_tuple`` (``Union[List, Set, Tuple]``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
    """
    assert isinstance(
        e_tuple, (list, set, tuple)
    ), "The hyperedge must be a list, set, or tuple of vertex ids."
    e_tuple = self.encode_e(e_tuple)
    assert (
        e_tuple in self._e_data
    ), f"The hyperedge {e_tuple} does not exist in the hypergraph."
    return set(e_tuple)

nbr_v

nbr_v(v_id: Any, exclude_self=True) -> list

Return the neighbors of the vertex.

Args: v_id (Any): The vertex id.

Source code in hyperdb/hypergraph.py
def nbr_v(self, v_id: Any, exclude_self=True) -> list:
    r"""
    Return the neighbors of the vertex.

    Args:
        ``v_id`` (``Any``): The vertex id.
    """
    assert isinstance(v_id, Hashable), "The vertex id must be hashable."
    assert (
        v_id in self._v_data
    ), f"The vertex {v_id} does not exist in the hypergraph."
    nbrs = set()
    for e_tuple in self._v_inci[v_id]:
        nbrs.update(e_tuple)
    if exclude_self:
        nbrs.remove(v_id)
    return set(nbrs)

The main class for creating and manipulating hypergraphs. Provides all essential operations for vertices, hyperedges, and persistence.

Key Features: - Add, remove, and update vertices and hyperedges - Query relationships and neighborhood information
- Persistence with save/load functionality - Built-in visualization capabilities

BaseHypergraphDB

hyperdb.BaseHypergraphDB dataclass

BaseHypergraphDB(
    storage_file: Union[str, Path] = "my_hypergraph.hgdb",
)

Base class for hypergraph database.

storage_file class-attribute instance-attribute

storage_file: Union[str, Path] = field(
    default="my_hypergraph.hgdb", compare=False
)

all_v cached property

all_v: List[str]

Return a list of all vertices in the hypergraph.

all_e cached property

all_e: List[Tuple]

Return a list of all hyperedges in the hypergraph.

num_v cached property

num_v: int

Return the number of vertices in the hypergraph.

num_e cached property

num_e: int

Return the number of hyperedges in the hypergraph.

save

save(file_path: Union[str, Path])

Save the hypergraph to a file.

Args: file_path (Union[str, Path]): The file path to save the hypergraph.

Source code in hyperdb/base.py
def save(self, file_path: Union[str, Path]):
    r"""
    Save the hypergraph to a file.

    Args:
        ``file_path`` (``Union[str, Path]``): The file path to save the hypergraph.
    """
    raise NotImplementedError

save_as

save_as(format: str, file_path: Union[str, Path])

Save the hypergraph to a specific format.

Args: format (str): The export format (e.g., "json", "csv", "graphml"). file_path (Union[str, Path]): The file path to export the hypergraph.

Source code in hyperdb/base.py
def save_as(self, format: str, file_path: Union[str, Path]):
    r"""
    Save the hypergraph to a specific format.

    Args:
        ``format`` (``str``): The export format (e.g., "json", "csv", "graphml").
        ``file_path`` (``Union[str, Path]``): The file path to export the hypergraph.
    """
    raise NotImplementedError

load staticmethod

load(file_path: Union[str, Path])

Load the hypergraph from a file.

Args: file_path (Union[str, Path]): The file path to load the hypergraph from.

Source code in hyperdb/base.py
@staticmethod
def load(self, file_path: Union[str, Path]):
    r"""
    Load the hypergraph from a file.

    Args:
        ``file_path`` (``Union[str, Path]``): The file path to load the hypergraph from.
    """
    raise NotImplementedError

load_from

load_from(format: str, file_path: Union[str, Path])

Load a hypergraph from a specific format.

Args: format (str): The import format (e.g., "json", "csv", "graphml"). file_path (Union[str, Path]): The file path to import the hypergraph from.

Source code in hyperdb/base.py
def load_from(self, format: str, file_path: Union[str, Path]):
    r"""
    Load a hypergraph from a specific format.

    Args:
        ``format`` (``str``): The import format (e.g., "json", "csv", "graphml").
        ``file_path`` (``Union[str, Path]``): The file path to import the hypergraph from.
    """
    raise NotImplementedError

v

v(v_id: Any, default: Any = None) -> dict

Return the vertex data.

Args: v_id (Any): The vertex id. default (Any): The default value if the vertex does not exist.

Source code in hyperdb/base.py
def v(self, v_id: Any, default: Any = None) -> dict:
    r"""
    Return the vertex data.

    Args:
        ``v_id`` (``Any``): The vertex id.
        ``default`` (``Any``): The default value if the vertex does not exist.
    """
    raise NotImplementedError

e

e(
    e_tuple: Union[List, Set, Tuple], default: Any = None
) -> dict

Return the hyperedge data.

Args: e_tuple (Union[List, Set, Tuple]): The hyperedge tuple: (v1_name, v2_name, ..., vn_name). default (Any): The default value if the hyperedge does not exist.

Source code in hyperdb/base.py
def e(self, e_tuple: Union[List, Set, Tuple], default: Any = None) -> dict:
    r"""
    Return the hyperedge data.

    Args:
        ``e_tuple`` (``Union[List, Set, Tuple]``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
        ``default`` (``Any``): The default value if the hyperedge does not exist.
    """
    raise NotImplementedError

encode_e

encode_e(e_tuple: Union[List, Set, Tuple]) -> Tuple

Sort and check the hyperedge tuple.

Args: e_tuple (Union[List, Set, Tuple]): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).

Source code in hyperdb/base.py
def encode_e(self, e_tuple: Union[List, Set, Tuple]) -> Tuple:
    r"""
    Sort and check the hyperedge tuple.

    Args:
        ``e_tuple`` (``Union[List, Set, Tuple]``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
    """
    raise NotImplementedError

add_v

add_v(v_id: Any, v_data: Optional[Dict] = None)

Add a vertex to the hypergraph.

Args: v_id (Any): The vertex id. v_data (Dict, optional): The vertex data. Defaults to None.

Source code in hyperdb/base.py
def add_v(self, v_id: Any, v_data: Optional[Dict] = None):
    r"""
    Add a vertex to the hypergraph.

    Args:
        ``v_id`` (``Any``): The vertex id.
        ``v_data`` (``Dict``, optional): The vertex data. Defaults to None.
    """
    raise NotImplementedError

add_e

add_e(e_tuple: Tuple, e_data: Optional[Dict] = None)

Add a hyperedge to the hypergraph.

Args: e_tuple (Tuple): The hyperedge tuple: (v1_name, v2_name, ..., vn_name). e_data (Dict, optional): The hyperedge data.

Source code in hyperdb/base.py
def add_e(self, e_tuple: Tuple, e_data: Optional[Dict] = None):
    r"""
    Add a hyperedge to the hypergraph.

    Args:
        ``e_tuple`` (``Tuple``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
        ``e_data`` (``Dict``, optional): The hyperedge data.
    """
    raise NotImplementedError

remove_v

remove_v(v_id: Any)

Remove a vertex from the hypergraph.

Args: v_id (Any): The vertex id.

Source code in hyperdb/base.py
def remove_v(self, v_id: Any):
    r"""
    Remove a vertex from the hypergraph.

    Args:
        ``v_id`` (``Any``): The vertex id.
    """
    raise NotImplementedError

remove_e

remove_e(e_tuple: Tuple)

Remove a hyperedge from the hypergraph.

Args: e_tuple (Tuple): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).

Source code in hyperdb/base.py
def remove_e(self, e_tuple: Tuple):
    r"""
    Remove a hyperedge from the hypergraph.

    Args:
        ``e_tuple`` (``Tuple``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
    """
    raise NotImplementedError

update_v

update_v(v_id: Any)

Update the vertex data.

Args: v_id (Any): The vertex id.

Source code in hyperdb/base.py
def update_v(self, v_id: Any):
    r"""
    Update the vertex data.

    Args:
        ``v_id`` (``Any``): The vertex id.
    """
    raise NotImplementedError

update_e

update_e(e_tuple: Tuple)

Update the hyperedge data.

Args: e_tuple (Tuple): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).

Source code in hyperdb/base.py
def update_e(self, e_tuple: Tuple):
    r"""
    Update the hyperedge data.

    Args:
        ``e_tuple`` (``Tuple``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
    """
    raise NotImplementedError

has_v

has_v(v_id: Any) -> bool

Return True if the vertex exists in the hypergraph.

Args: v_id (Any): The vertex id.

Source code in hyperdb/base.py
def has_v(self, v_id: Any) -> bool:
    r"""
    Return True if the vertex exists in the hypergraph.

    Args:
        ``v_id`` (``Any``): The vertex id.
    """
    raise NotImplementedError

has_e

has_e(e_tuple: Tuple) -> bool

Return True if the hyperedge exists in the hypergraph.

Args: e_tuple (Tuple): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).

Source code in hyperdb/base.py
def has_e(self, e_tuple: Tuple) -> bool:
    r"""
    Return True if the hyperedge exists in the hypergraph.

    Args:
        ``e_tuple`` (``Tuple``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
    """
    raise NotImplementedError

degree_v

degree_v(v_id: Any) -> int

Return the degree of the vertex.

Args: v_id (Any): The vertex id.

Source code in hyperdb/base.py
def degree_v(self, v_id: Any) -> int:
    r"""
    Return the degree of the vertex.

    Args:
        ``v_id`` (``Any``): The vertex id.
    """
    raise NotImplementedError

degree_e

degree_e(e_tuple: Tuple) -> int

Return the degree of the hyperedge.

Args: e_tuple (Tuple): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).

Source code in hyperdb/base.py
def degree_e(self, e_tuple: Tuple) -> int:
    r"""
    Return the degree of the hyperedge.

    Args:
        ``e_tuple`` (``Tuple``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
    """
    raise NotImplementedError

nbr_e_of_v

nbr_e_of_v(v_id: Any) -> list

Return the hyperedge neighbors of the vertex.

Args: v_id (Any): The vertex id.

Source code in hyperdb/base.py
def nbr_e_of_v(self, v_id: Any) -> list:
    r"""
    Return the hyperedge neighbors of the vertex.

    Args:
        ``v_id`` (``Any``): The vertex id.
    """
    raise NotImplementedError

nbr_v_of_e

nbr_v_of_e(e_tuple: Tuple) -> list

Return the vertex neighbors of the hyperedge.

Args: e_tuple (Tuple): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).

Source code in hyperdb/base.py
def nbr_v_of_e(self, e_tuple: Tuple) -> list:
    r"""
    Return the vertex neighbors of the hyperedge.

    Args:
        ``e_tuple`` (``Tuple``): The hyperedge tuple: (v1_name, v2_name, ..., vn_name).
    """
    raise NotImplementedError

nbr_v

nbr_v(v_id: Any) -> list

Return the vertex neighbors of the vertex.

Args: v_id (Any): The vertex id.

Source code in hyperdb/base.py
def nbr_v(self, v_id: Any) -> list:
    r"""
    Return the vertex neighbors of the vertex.

    Args:
        ``v_id`` (``Any``): The vertex id.
    """
    raise NotImplementedError

draw

draw(
    port: int = 8080,
    open_browser: bool = True,
    blocking: bool = True,
)

Draw the hypergraph data of the current HyperDB instance

Args:
port: Server port number, defaults to 8080
open_browser: Whether to automatically open the browser, defaults to True blocking: Whether to block the main thread, defaults to True. Set to False for non-blocking mode.

Returns: HypergraphViewer instance

Source code in hyperdb/base.py
def draw(self, port: int = 8080, open_browser: bool = True, blocking: bool = True):
    """
    Draw the hypergraph data of the current HyperDB instance

    Args:  
        ``port``: Server port number, defaults to 8080  
        ``open_browser``: Whether to automatically open the browser, defaults to True
        ``blocking``: Whether to block the main thread, defaults to True. Set to False for non-blocking mode.

    Returns:
        HypergraphViewer instance
    """
    from .draw import draw_hypergraph

    return draw_hypergraph(
        hypergraph_db=self,
        port=port,
        open_browser=open_browser,
        blocking=blocking
    )

sub

sub(v_name_list: List[str])

Return the sub-hypergraph.

Args: v_name_list (List[str]): The list of vertex ids.

Source code in hyperdb/base.py
def sub(self, v_name_list: List[str]):
    r"""
    Return the sub-hypergraph.

    Args:
        ``v_name_list`` (``List[str]``): The list of vertex ids.
    """
    raise NotImplementedError

sub_from_v

sub_from_v(v_id: Any, depth: int)

Return the sub-hypergraph from the vertex.

Args: v_id (Any): The vertex id. depth (int): The depth of the sub-hypergraph.

Source code in hyperdb/base.py
def sub_from_v(self, v_id: Any, depth: int):
    r"""
    Return the sub-hypergraph from the vertex.

    Args:
        ``v_id`` (``Any``): The vertex id.
        ``depth`` (``int``): The depth of the sub-hypergraph.
    """
    raise NotImplementedError

query_v

query_v(filters: Dict[str, Any]) -> List[str]

Query and return vertices that match the given filters.

Args: filters (Dict[str, Any]): A dictionary of conditions to filter vertices.

Source code in hyperdb/base.py
def query_v(self, filters: Dict[str, Any]) -> List[str]:
    r"""
    Query and return vertices that match the given filters.

    Args:
        ``filters`` (``Dict[str, Any]``): A dictionary of conditions to filter vertices.
    """
    raise NotImplementedError

query_e

query_e(filters: Dict[str, Any]) -> List[Tuple]

Query and return hyperedges that match the given filters.

Args: filters (Dict[str, Any]): A dictionary of conditions to filter hyperedges.

Source code in hyperdb/base.py
def query_e(self, filters: Dict[str, Any]) -> List[Tuple]:
    r"""
    Query and return hyperedges that match the given filters.

    Args:
        ``filters`` (``Dict[str, Any]``): A dictionary of conditions to filter hyperedges.
    """
    raise NotImplementedError

stats

stats() -> dict

Return basic statistics of the hypergraph.

Source code in hyperdb/base.py
def stats(self) -> dict:
    r"""
    Return basic statistics of the hypergraph.
    """
    raise NotImplementedError

The foundational base class that defines the core hypergraph structure and basic operations.

Quick Reference

Vertex Operations

Method Description
add_v(vid, attr=None) Add a vertex with optional attributes
remove_v(vid) Remove a vertex and all connected hyperedges
update_v(vid, attr) Update vertex attributes
v[vid] Access vertex attributes
all_v Get all vertex IDs
num_v Get total number of vertices

Hyperedge Operations

Method Description
add_e(vertices, attr=None) Add a hyperedge connecting multiple vertices
remove_e(eid) Remove a hyperedge
update_e(eid, attr) Update hyperedge attributes
e[eid] Access hyperedge attributes
all_e Get all hyperedge IDs
num_e Get total number of hyperedges

Query Operations

Method Description
d_v(vid) Get degree of a vertex (number of incident hyperedges)
d_e(eid) Get size of a hyperedge (number of vertices)
N_v(vid) Get all vertices connected to a vertex via hyperedges
N_e(vid) Get all hyperedges containing a vertex
N_v_of_e(eid) Get all vertices in a hyperedge

Persistence Operations

Method Description
save(filepath) Save hypergraph to file
load(filepath) Load hypergraph from file
copy() Create a deep copy of the hypergraph

Visualization

Method Description
show(port=8080) Launch interactive web visualization

Usage Examples

Basic Operations

from hyperdb import HypergraphDB

# Create hypergraph
hg = HypergraphDB()

# Add vertices
hg.add_v(1, {"name": "Alice"})
hg.add_v(2, {"name": "Bob"})
hg.add_v(3, {"name": "Charlie"})

# Add hyperedges
hg.add_e((1, 2), {"relation": "friends"})
hg.add_e((1, 2, 3), {"relation": "team"})

# Query operations
print(f"Alice's degree: {hg.d_v(1)}")
print(f"Alice's neighbors: {hg.N_v(1)}")
print(f"Alice's hyperedges: {hg.N_e(1)}")

Advanced Queries

# Find all vertices with specific attributes
data_scientists = [vid for vid in hg.all_v 
                   if hg.v[vid].get("profession") == "Data Scientist"]

# Find large collaborations (hyperedges with many vertices)
large_teams = [eid for eid in hg.all_e if hg.d_e(eid) >= 4]

# Find vertices that appear in multiple hyperedges
highly_connected = [vid for vid in hg.all_v if hg.d_v(vid) >= 3]

Working with Attributes

# Rich vertex attributes
hg.add_v("person1", {
    "name": "Dr. Smith",
    "age": 45,
    "skills": ["Python", "Machine Learning", "Statistics"],
    "publications": 127,
    "h_index": 42
})

# Rich hyperedge attributes
hg.add_e(("person1", "person2", "person3"), {
    "type": "research_paper",
    "title": "Advanced Hypergraph Algorithms",
    "year": 2024,
    "venue": "ICML",
    "impact_factor": 3.2,
    "citations": 15
})

Error Handling

The API includes comprehensive error handling:

try:
    hg.add_v(1, {"name": "Alice"})
    hg.add_v(1, {"name": "Bob"})  # Raises error - vertex already exists
except ValueError as e:
    print(f"Error: {e}")

try:
    hg.remove_v(999)  # Raises error - vertex doesn't exist
except KeyError as e:
    print(f"Error: {e}")

Performance Considerations

  • Vertex IDs: Use hashable types (int, str, tuple) for best performance
  • Batch Operations: Add multiple vertices/edges at once when possible
  • Memory Usage: Large attribute dictionaries increase memory usage
  • Persistence: Use pickle format for fastest save/load operations

Type Hints

Hypergraph-DB includes comprehensive type hints for better IDE support:

from typing import Set, Dict, Any, Tuple, List
from hyperdb import HypergraphDB

# The API is fully typed
hg: HypergraphDB = HypergraphDB()
vertex_id: int = 1
attributes: Dict[str, Any] = {"name": "Alice"}
vertices: Tuple[int, ...] = (1, 2, 3)