Skip to content

TemporalData

TemporalData(
    src: Optional[array] = None,
    dst: Optional[array] = None,
    t: Optional[array] = None,
    msg: Optional[array] = None,
    **kwargs,
)

A stream of events describing a temporal graph (a Continuous-Time Dynamic Graph), as PyG's torch_geometric.data.TemporalData.

Each event i is a (temporal) edge from the source node src[i] to the destination node dst[i] at time t[i], with a message (event features) msg[i]. Any other per-event attribute (e.g. labels y) can be passed to the constructor or set afterwards.

Indexing with a string returns an attribute (events["src"]); any other index (an integer, a slice, a list, an integer array or a boolean mask) selects events and returns a new TemporalData in which every array whose first dimension is num_events is indexed, as in PyG.

Parameters:

Name Type Description Default
src Optional[array]

Source node of each event, shape [num_events]

None
dst Optional[array]

Destination node of each event, shape [num_events]

None
t Optional[array]

Timestamp of each event, shape [num_events]

None
msg Optional[array]

Message (features) of each event, shape [num_events, num_msg_features]

None
**kwargs

Additional attributes, e.g. event labels y

{}

Example:

import mlx.core as mx
from mlx_graphs.data import TemporalData

events = TemporalData(
    src=mx.array([1, 2, 3, 4]),
    dst=mx.array([2, 3, 4, 5]),
    t=mx.array([1000, 1010, 1100, 2000]),
    msg=mx.array([[1.0], [1.0], [0.0], [0.0]]),
    y=mx.array([1, 1, 0, 0]),
)
events.num_events
>>> 4
events.num_nodes
>>> 6
train, val, test = events.train_val_test_split(0.25, 0.25)

References

PyG TemporalData

Methods:

Name Description
from_dict

Creates a TemporalData from a dictionary of attributes.

keys

Names of the attributes that are set.

items

(name, value) pairs of the attributes that are set.

__call__

Iterates over (name, value) pairs, restricted to keys if

to_dict

Returns the attributes as a dictionary.

clone

Returns a deep copy, with copies of all the arrays.

size

(src.max(), dst.max()) as in PyG, or one of the two.

index_select

Selects events.

train_val_test_split

Splits the events into training, validation and test sets according to

__cat_dim__

All attributes are concatenated along the first (event) axis.

__inc__

Increment applied to key when batching: num_nodes for

from_data_list

Concatenates several event streams into one, as PyG's

Attributes:

Name Type Description
num_nodes int

The number of nodes, max(src.max(), dst.max()) + 1.

num_events int

The number of events (temporal edges).

num_edges int

Alias of num_events.

edge_index array

The [2, num_events] stack of src and dst (or the

Source code in mlx_graphs/data/temporal.py
def __init__(
    self,
    src: Optional[mx.array] = None,
    dst: Optional[mx.array] = None,
    t: Optional[mx.array] = None,
    msg: Optional[mx.array] = None,
    **kwargs,
):
    object.__setattr__(self, "_store", {})
    self.src = src
    self.dst = dst
    self.t = t
    self.msg = msg
    for key, value in kwargs.items():
        setattr(self, key, value)

num_nodes property

num_nodes: int

The number of nodes, max(src.max(), dst.max()) + 1.

num_events property

num_events: int

The number of events (temporal edges).

num_edges property

num_edges: int

Alias of num_events.

edge_index property

edge_index: array

The [2, num_events] stack of src and dst (or the edge_index attribute if one was set).

from_dict classmethod

from_dict(mapping: dict) -> TemporalData

Creates a TemporalData from a dictionary of attributes.

Source code in mlx_graphs/data/temporal.py
@classmethod
def from_dict(cls, mapping: dict) -> "TemporalData":
    """Creates a :class:`TemporalData` from a dictionary of attributes."""
    return cls(**mapping)

keys

keys() -> list[str]

Names of the attributes that are set.

Source code in mlx_graphs/data/temporal.py
def keys(self) -> list[str]:
    """Names of the attributes that are set."""
    return list(self._store.keys())

items

items()

(name, value) pairs of the attributes that are set.

Source code in mlx_graphs/data/temporal.py
def items(self):
    """``(name, value)`` pairs of the attributes that are set."""
    return self._store.items()

__call__

__call__(*keys: str) -> Iterator

Iterates over (name, value) pairs, restricted to keys if given.

Source code in mlx_graphs/data/temporal.py
def __call__(self, *keys: str) -> Iterator:
    """Iterates over ``(name, value)`` pairs, restricted to ``keys`` if
    given."""
    for key, value in self._store.items():
        if not keys or key in keys:
            yield key, value

to_dict

to_dict() -> dict

Returns the attributes as a dictionary.

Source code in mlx_graphs/data/temporal.py
def to_dict(self) -> dict:
    """Returns the attributes as a dictionary."""
    return dict(self._store)

clone

clone() -> TemporalData

Returns a deep copy, with copies of all the arrays.

Source code in mlx_graphs/data/temporal.py
def clone(self) -> "TemporalData":
    """Returns a deep copy, with copies of all the arrays."""
    return copy.deepcopy(self)

size

size(dim: Optional[int] = None)

(src.max(), dst.max()) as in PyG, or one of the two.

Source code in mlx_graphs/data/temporal.py
def size(self, dim: Optional[int] = None):
    """``(src.max(), dst.max())`` as in PyG, or one of the two."""
    size = (int(self.src.max().item()), int(self.dst.max().item()))
    return size if dim is None else size[dim]

index_select

index_select(
    idx: Union[int, slice, Sequence[int], ndarray, array],
) -> TemporalData

Selects events.

Every array attribute whose first dimension is num_events is indexed; the others are kept as they are.

Parameters:

Name Type Description Default
idx Union[int, slice, Sequence[int], ndarray, array]

An integer (kept as a one-event selection), a slice, a list or array of event positions, or a boolean mask over the events

required

Returns:

Type Description
TemporalData

A new TemporalData with the selected events.

Source code in mlx_graphs/data/temporal.py
def index_select(
    self, idx: Union[int, slice, Sequence[int], np.ndarray, mx.array]
) -> "TemporalData":
    """Selects events.

    Every array attribute whose first dimension is ``num_events`` is
    indexed; the others are kept as they are.

    Args:
        idx: An integer (kept as a one-event selection), a slice, a list or
            array of event positions, or a boolean mask over the events

    Returns:
        A new :class:`TemporalData` with the selected events.
    """
    num_events = self.num_events
    idx = _prepare_index(idx, num_events)
    out = copy.copy(self)
    for key, value in self._store.items():
        if (
            isinstance(value, mx.array)
            and value.ndim > 0
            and value.shape[0] == num_events
        ):
            out._store[key] = value[idx]
    return out

train_val_test_split

train_val_test_split(
    val_ratio: float = 0.15, test_ratio: float = 0.15
) -> tuple[TemporalData, TemporalData, TemporalData]

Splits the events into training, validation and test sets according to time, as in PyG.

The split times are the 1 - val_ratio - test_ratio and 1 - test_ratio quantiles of t, and events are assumed to be sorted by time.

Parameters:

Name Type Description Default
val_ratio float

Proportion of events in the validation set. Default: 0.15

0.15
test_ratio float

Proportion of events in the test set. Default: 0.15

0.15

Returns:

Type Description
tuple[TemporalData, TemporalData, TemporalData]

The training, validation and test events.

Source code in mlx_graphs/data/temporal.py
def train_val_test_split(
    self, val_ratio: float = 0.15, test_ratio: float = 0.15
) -> tuple["TemporalData", "TemporalData", "TemporalData"]:
    """Splits the events into training, validation and test sets according to
    time, as in PyG.

    The split times are the ``1 - val_ratio - test_ratio`` and
    ``1 - test_ratio`` quantiles of ``t``, and events are assumed to be
    sorted by time.

    Args:
        val_ratio: Proportion of events in the validation set. Default:
            ``0.15``
        test_ratio: Proportion of events in the test set. Default: ``0.15``

    Returns:
        The training, validation and test events.
    """
    t = _to_numpy(self.t)
    val_time, test_time = np.quantile(
        t, [1.0 - val_ratio - test_ratio, 1.0 - test_ratio]
    )
    val_idx = int((t <= val_time).sum())
    test_idx = int((t <= test_time).sum())
    return self[:val_idx], self[val_idx:test_idx], self[test_idx:]

__cat_dim__

__cat_dim__(key: str, *args, **kwargs) -> int

All attributes are concatenated along the first (event) axis.

Source code in mlx_graphs/data/temporal.py
def __cat_dim__(self, key: str, *args, **kwargs) -> int:
    """All attributes are concatenated along the first (event) axis."""
    return 0

__inc__

__inc__(key: str, *args, **kwargs) -> Optional[int]

Increment applied to key when batching: num_nodes for src and dst, max + 1 for attributes containing "batch", and no increment otherwise (as PyG).

Source code in mlx_graphs/data/temporal.py
def __inc__(self, key: str, *args, **kwargs) -> Optional[int]:
    """Increment applied to ``key`` when batching: ``num_nodes`` for
    ``src`` and ``dst``, ``max + 1`` for attributes containing ``"batch"``,
    and no increment otherwise (as PyG)."""
    value = self._store.get(key)
    if "batch" in key and isinstance(value, mx.array):
        return int(value.max().item()) + 1 if value.size > 0 else 0
    if key in ("src", "dst"):
        return self.num_nodes
    return None

from_data_list classmethod

from_data_list(data_list: Sequence[TemporalData]) -> TemporalData

Concatenates several event streams into one, as PyG's Batch.from_data_list does for TemporalData.

src and dst of each stream are offset by the number of nodes of the previous streams (see __inc__()), attributes containing "batch" by their number of groups, and all the other array attributes are concatenated as they are. Non-array attributes become lists.

Parameters:

Name Type Description Default
data_list Sequence[TemporalData]

The event streams, with the same attributes

required

Returns:

Type Description
TemporalData

The concatenated events.

Source code in mlx_graphs/data/temporal.py
@classmethod
def from_data_list(cls, data_list: Sequence["TemporalData"]) -> "TemporalData":
    """Concatenates several event streams into one, as PyG's
    ``Batch.from_data_list`` does for ``TemporalData``.

    ``src`` and ``dst`` of each stream are offset by the number of nodes of
    the previous streams (see :meth:`__inc__`), attributes containing
    ``"batch"`` by their number of groups, and all the other array
    attributes are concatenated as they are. Non-array attributes become
    lists.

    Args:
        data_list: The event streams, with the same attributes

    Returns:
        The concatenated events.
    """
    if len(data_list) == 0:
        raise ValueError("Cannot batch an empty list of TemporalData")
    first = data_list[0]
    out = cls()
    for key in first.keys():
        values = [data[key] for data in data_list]
        if not all(isinstance(v, mx.array) for v in values):
            out[key] = values
            continue
        cat_dim = first.__cat_dim__(key)
        if first.__inc__(key) is not None:
            incs = np.cumsum([0] + [data.__inc__(key) for data in data_list])
            values = [v + int(inc) for v, inc in zip(values, incs[:-1])]
        out[key] = mx.concatenate(values, axis=cat_dim)
    return out

from mlx_graphs.data.temporal import TemporalData · mlx_graphs/data/temporal.py