Skip to content

GraphStore

GraphStore()

Bases: ABC

Abstract store of the edges of a graph, following PyG's GraphStore.

Subclasses implement _put_edge_index(), _get_edge_index(), _remove_edge_index() and get_all_edge_attrs(); edges are exchanged as pairs of np.ndarray (mx.array is accepted when putting).

Example:

from mlx_graphs.data import InMemoryGraphStore

graph_store = InMemoryGraphStore()
graph_store.put_edge_index(
    data.edge_index, layout="coo", size=(data.num_nodes, data.num_nodes)
)
colptr, row, perm = graph_store.csc()

Methods:

Name Description
get_all_edge_attrs

The attributes of all the stored edges.

put_edge_index

Adds edges, as a [2, num_edges] array or a pair of arrays

get_edge_index

The edges of edge_type as stored (layout=None) or

remove_edge_index

Removes the edges of edge_type.

num_nodes

(num_src_nodes, num_dst_nodes) of edge_type.

num_edges

Number of edges of edge_type.

coo

(row, col) of edge_type, in the original edge order for

csc

(colptr, row, perm) of edge_type: the in-edges of every

csr

(rowptr, col, perm) of edge_type (out-edges of every

Source code in mlx_graphs/data/graph_store.py
def __init__(self):
    self._csc_cache: dict[
        Any, tuple[np.ndarray, np.ndarray, Optional[np.ndarray]]
    ] = {}

get_all_edge_attrs abstractmethod

get_all_edge_attrs() -> list[EdgeAttr]

The attributes of all the stored edges.

Source code in mlx_graphs/data/graph_store.py
@abstractmethod
def get_all_edge_attrs(self) -> list[EdgeAttr]:
    """The attributes of all the stored edges."""

put_edge_index

put_edge_index(
    edge_index: Union[array, ndarray, tuple],
    edge_type: Any = None,
    layout: EdgeLayout = "coo",
    size: Optional[tuple[int, int]] = None,
    is_sorted: bool = False,
) -> bool

Adds edges, as a [2, num_edges] array or a pair of arrays ((row, col) for COO, (row, colptr) for CSC, (rowptr, col) for CSR).

Parameters:

Name Type Description Default
edge_index Union[array, ndarray, tuple]

The edges.

required
edge_type Any

Their type (None for homogeneous graphs).

None
layout EdgeLayout

"coo", "csc" or "csr".

'coo'
size Optional[tuple[int, int]]

(num_src_nodes, num_dst_nodes). Inferred from the largest node ids if not given (isolated nodes with larger ids are then missed).

None
is_sorted bool

Whether COO edges are sorted by destination.

False
Source code in mlx_graphs/data/graph_store.py
def put_edge_index(
    self,
    edge_index: Union[mx.array, np.ndarray, tuple],
    edge_type: Any = None,
    layout: EdgeLayout = "coo",
    size: Optional[tuple[int, int]] = None,
    is_sorted: bool = False,
) -> bool:
    """Adds edges, as a ``[2, num_edges]`` array or a pair of arrays
    (``(row, col)`` for COO, ``(row, colptr)`` for CSC, ``(rowptr, col)``
    for CSR).

    Args:
        edge_index: The edges.
        edge_type: Their type (``None`` for homogeneous graphs).
        layout: ``"coo"``, ``"csc"`` or ``"csr"``.
        size: ``(num_src_nodes, num_dst_nodes)``. Inferred from the
            largest node ids if not given (isolated nodes with larger
            ids are then missed).
        is_sorted: Whether COO edges are sorted by destination.
    """
    first, second = (_host(edge_index[0]), _host(edge_index[1]))
    if size is None:
        if layout == "coo":
            n = int(max(first.max(initial=-1), second.max(initial=-1))) + 1
            size = (n, n)
        elif layout == "csc":
            size = (int(first.max(initial=-1)) + 1, second.size - 1)
        else:
            size = (first.size - 1, int(second.max(initial=-1)) + 1)
    attr = EdgeAttr(edge_type, layout, is_sorted, size)
    self._csc_cache.pop(edge_type, None)
    return self._put_edge_index((first, second), attr)

get_edge_index

get_edge_index(
    edge_type: Any = None, layout: Optional[EdgeLayout] = None
) -> tuple[ndarray, ndarray]

The edges of edge_type as stored (layout=None) or converted to layout.

Source code in mlx_graphs/data/graph_store.py
def get_edge_index(
    self, edge_type: Any = None, layout: Optional[EdgeLayout] = None
) -> tuple[np.ndarray, np.ndarray]:
    """The edges of ``edge_type`` as stored (``layout=None``) or
    converted to ``layout``."""
    attr = self._get_attr(edge_type)
    if layout is None or layout == attr.layout:
        out = self._get_edge_index(attr)
        assert out is not None
        return out
    if layout == "coo":
        return self.coo(edge_type)
    if layout == "csc":
        colptr, row, _ = self.csc(edge_type)
        return row, colptr
    rowptr, col, _ = self.csr(edge_type)
    return rowptr, col

remove_edge_index

remove_edge_index(edge_type: Any = None) -> bool

Removes the edges of edge_type.

Source code in mlx_graphs/data/graph_store.py
def remove_edge_index(self, edge_type: Any = None) -> bool:
    """Removes the edges of ``edge_type``."""
    self._csc_cache.pop(edge_type, None)
    try:
        attr = self._get_attr(edge_type)
    except KeyError:
        return False
    return self._remove_edge_index(attr)

num_nodes

num_nodes(edge_type: Any = None) -> tuple[int, int]

(num_src_nodes, num_dst_nodes) of edge_type.

Source code in mlx_graphs/data/graph_store.py
def num_nodes(self, edge_type: Any = None) -> tuple[int, int]:
    """``(num_src_nodes, num_dst_nodes)`` of ``edge_type``."""
    size = self._get_attr(edge_type).size
    assert size is not None
    return size

num_edges

num_edges(edge_type: Any = None) -> int

Number of edges of edge_type.

Source code in mlx_graphs/data/graph_store.py
def num_edges(self, edge_type: Any = None) -> int:
    """Number of edges of ``edge_type``."""
    attr = self._get_attr(edge_type)
    first, second = self._get_edge_index(attr)  # type: ignore
    return int(
        first.size
        if attr.layout == "coo"
        else (first.size if attr.layout == "csc" else second.size)
    )

coo

coo(edge_type: Any = None) -> tuple[ndarray, ndarray]

(row, col) of edge_type, in the original edge order for edges stored as COO.

Source code in mlx_graphs/data/graph_store.py
def coo(self, edge_type: Any = None) -> tuple[np.ndarray, np.ndarray]:
    """``(row, col)`` of ``edge_type``, in the original edge order for
    edges stored as COO."""
    attr = self._get_attr(edge_type)
    first, second = self._get_edge_index(attr)  # type: ignore
    if attr.layout == "coo":
        return first, second
    if attr.layout == "csc":
        col = np.repeat(np.arange(second.size - 1), np.diff(second))
        return first, col
    row = np.repeat(np.arange(first.size - 1), np.diff(first))
    return row, second

csc

csc(edge_type: Any = None) -> tuple[ndarray, ndarray, Optional[ndarray]]

(colptr, row, perm) of edge_type: the in-edges of every node, and the position in the stored COO edges of every CSC entry (None if the stored edges need no permutation). Cached.

Source code in mlx_graphs/data/graph_store.py
def csc(
    self, edge_type: Any = None
) -> tuple[np.ndarray, np.ndarray, Optional[np.ndarray]]:
    """``(colptr, row, perm)`` of ``edge_type``: the in-edges of every
    node, and the position in the stored COO edges of every CSC entry
    (``None`` if the stored edges need no permutation). Cached."""
    if edge_type in self._csc_cache:
        return self._csc_cache[edge_type]
    attr = self._get_attr(edge_type)
    first, second = self._get_edge_index(attr)  # type: ignore
    num_dst = attr.size[1]  # type: ignore
    if attr.layout == "csc":
        out = (second, first, None)
    else:
        row, col = self.coo(edge_type)
        if attr.layout == "coo" and attr.is_sorted:
            perm = None
        else:
            perm = np.argsort(col, kind="stable")
            row, col = row[perm], col[perm]
        out = (_ptr(col, num_dst), row, perm)
    self._csc_cache[edge_type] = out
    return out

csr

csr(edge_type: Any = None) -> tuple[ndarray, ndarray, Optional[ndarray]]

(rowptr, col, perm) of edge_type (out-edges of every node).

Source code in mlx_graphs/data/graph_store.py
def csr(
    self, edge_type: Any = None
) -> tuple[np.ndarray, np.ndarray, Optional[np.ndarray]]:
    """``(rowptr, col, perm)`` of ``edge_type`` (out-edges of every
    node)."""
    attr = self._get_attr(edge_type)
    if attr.layout == "csr":
        rowptr, col = self._get_edge_index(attr)  # type: ignore
        return rowptr, col, None
    row, col = self.coo(edge_type)
    perm = np.argsort(row, kind="stable")
    return _ptr(row[perm], attr.size[0]), col[perm], perm  # type: ignore

from mlx_graphs.data import GraphStore · mlx_graphs/data/graph_store.py