Skip to content

Events

An Event is the first sleap-io annotation with a temporal extent. Every other annotation type — Instance, Centroid, BoundingBox, SegmentationMask, LabelImage, ROI — is strictly per-frame and lives on a single LabeledFrame. An Event instead spans a range of frames: a (video, start_frame, end_frame, type) interval. It models anything with a duration — behavior bouts, stimulus epochs, physiological events, feeding bouts, review flags.

A behavior bout is just one kind of event, so the vocabulary is deliberately generic (EventType) rather than behavior-specific.

Event is abstract — use UserEvent (human-annotated) or PredictedEvent (model output).

Event types (the catalog)

An EventType is a lightweight controlled-vocabulary entry — the "ethogram" for behavior, or any labeled span more generally. Like Track and Identity it is name-matched across separately-loaded files and merges, and carries free-form string metadata (e.g. a UI color):

>>> import sleap_io as sio
>>> attack = sio.EventType(
...     name="attack",
...     description="One mouse attacks another.",
...     metadata={"color": "#e6194b"},
... )
>>> print(attack.name)
attack
>>> print(attack.matches(sio.EventType(name="attack")))  # matched by name
True

Frame convention (inclusive)

start_frame and end_frame are both inclusive: the event covers every frame in [start_frame, end_frame] and spans end_frame - start_frame + 1 frames. Omitting end_frame yields an instantaneous single-frame event (end_frame is filled to start_frame):

>>> import sleap_io as sio
>>> video = sio.Video(filename="clip.mp4")
>>> bout = sio.UserEvent(type="attack", video=video, start_frame=100, end_frame=140)
>>> print(bout.n_frames)      # inclusive: 140 - 100 + 1
41
>>> print(bout.contains(140))  # inclusive at both ends
True
>>> print(bout.frames)         # a lazy range aligned to any framewise scores
range(100, 141)
>>> point = sio.UserEvent(type="light_on", video=video, start_frame=200)
>>> print(point.is_instantaneous, point.end_frame)
True 200

A string passed as type is auto-promoted to EventType(name=...), so you do not have to build the catalog entry by hand for quick construction.

Participants: subject and target

Each event optionally names up to two participants, each a Track (a within-video trajectory) or an Identity (a cross-video animal):

  • subject — who the event is about. None means a frame-level event with no individual (e.g. a stimulus epoch).
  • target — who the event is directed at. None means the event is non-directed / individual ("self" in behavior-scoring terms).

is_directed reports whether a target is set:

>>> import sleap_io as sio
>>> video = sio.Video(filename="clip.mp4")
>>> mouse1, mouse2 = sio.Track(name="mouse1"), sio.Track(name="mouse2")
>>> attack = sio.UserEvent(
...     type="attack", video=video, start_frame=100, end_frame=140,
...     subject=mouse1, target=mouse2,
... )
>>> print(attack.is_directed)
True
>>> rear = sio.UserEvent(type="rear", video=video, start_frame=50, subject=mouse1)
>>> print(rear.is_directed)  # target is None -> non-directed ("self")
False

Overlapping events

Events are a flat set of intervals, not a per-frame partition: they may overlap in time, even for the same subject. overlaps tests whether two events share a video and their inclusive spans intersect (events in different videos never overlap):

>>> import sleap_io as sio
>>> video = sio.Video(filename="clip.mp4")
>>> a = sio.UserEvent(type="rear", video=video, start_frame=0, end_frame=10)
>>> b = sio.UserEvent(type="freeze", video=video, start_frame=8, end_frame=20)
>>> print(a.overlaps(b))
True

User vs. predicted events

PredictedEvent adds two independent, optional confidence fields. A predictor sets whichever it produces (a framewise trace, an event-level scalar, both, or neither); neither is derived from the other:

  • scores — a framewise confidence trace of shape (n_frames,), stored as float32 and aligned element-wise to frames.
  • score — a scalar event-level confidence.
>>> import sleap_io as sio
>>> video = sio.Video(filename="clip.mp4")
>>> pred = sio.PredictedEvent(
...     type="attack", video=video, start_frame=100, end_frame=104,
...     scores=[0.6, 0.8, 0.9, 0.7, 0.5],  # per-frame, len == n_frames
...     score=0.74,                         # event-level scalar
... )
>>> print(pred.is_predicted, pred.scores.dtype, len(pred.scores))
True float32 5
>>> user = sio.UserEvent(type="attack", video=video, start_frame=100, end_frame=104)
>>> print(user.is_predicted)
False

Fields

Field Type Description
type EventType Catalog entry; a bare string is auto-promoted
video Video The video the event occurs in
start_frame int First frame (inclusive)
end_frame int \| None Last frame (inclusive); defaults to start_frame
subject Track \| Identity \| None Who the event is about
target Track \| Identity \| None Who the event is directed at (None = self)
name str Human-readable name for this event instance
source str Annotation source identifier
metadata dict[str, str] Arbitrary string-keyed metadata
scores np.ndarray \| None (PredictedEvent) framewise (n_frames,) trace, float32
score float \| None (PredictedEvent) scalar event-level confidence

On Labels

Events and their catalog live on the top-level container as two lists, Labels.events and Labels.event_types — siblings of videos / tracks / suggestions, not nested on any LabeledFrame (an event may cover frames that carry no pose labels). Constructing a Labels auto-collects the catalog (deduped by name) and any Track / Identity used as a participant, exactly like tracks are collected from instances:

>>> import sleap_io as sio
>>> video = sio.Video(filename="clip.mp4")
>>> mouse1, mouse2 = sio.Track(name="mouse1"), sio.Track(name="mouse2")
>>> labels = sio.Labels(
...     videos=[video],
...     tracks=[mouse1, mouse2],
...     events=[
...         sio.UserEvent(type="attack", video=video, start_frame=100,
...                       end_frame=140, subject=mouse1, target=mouse2),
...         sio.UserEvent(type="rear", video=video, start_frame=120, subject=mouse2),
...     ],
... )
>>> [et.name for et in labels.event_types]   # catalog auto-collected from events
>>> len(labels.get_events(type="attack"))
>>> len(labels.events_at(video, 130))        # events whose span covers frame 130

get_events filters by video, subject, type (an EventType or a bare name), frame_idx (events whose span covers that frame), and predicted. events_at is the shorthand for "what is happening at this frame?". copy() and merge() carry events across too: merging rebinds each event's video / subject / target / type onto the merged catalogs and dedupes the catalog by name. Events themselves are deduped by identity — (video, start_frame, end_frame, type name, subject, target, predicted?) — so re-merging the same source is idempotent (confidence scores are not part of the identity, so an exact re-merge keeps the first copy).

SLP persistence

Events persist to SLP in format 2.6+ via two additive, presence-guarded HDF5 groups (older readers ignore them; event-free files are byte-identical):

  • /event_types — the catalog (a name string dataset, an optional description, and an optional entity-attribute-value meta_* table), mirroring /identity.
  • /events — a columnar struct-of-arrays (one dataset per field, like /bboxes) plus a ragged CSR pair (scores flat float32 + score_offsets) for the optional framewise PredictedEvent.scores. Participants are stored as a (kind, idx) pair (0=none/self, 1=track, 2=identity). The scalar score column and both trace datasets are written only when some event uses them, so unused features cost zero bytes.
labels.save("behavior.slp")            # writes /event_types + /events (format 2.6)
loaded = sio.load_slp("behavior.slp")  # events + catalog fully reconstructed
loaded.events, loaded.event_types

See also

  • Poses and Embeddings: the Track and Identity catalogs that events reference as participants.
  • Labels & Frames: the top-level container holding labels.events / labels.event_types and the get_events() / events_at() queries.

API reference

sleap_io.EventType

A type of event in the catalog (controlled vocabulary).

A lightweight catalog object like Track / Identity: it is referenced by Events and matched across separately-loaded files and merges by name. Examples: a behavior ("attack", "rear"), a stimulus ("light_on"), a physiological event ("seizure"), or any labeled span.

Attributes:

Name Type Description
name

Human-readable name for this event type (e.g. "attack"). Not required to be unique, but name is how event types are matched across files and merges.

description

Optional longer human-readable description of what this event type represents. Empty by default.

metadata

Arbitrary string-keyed, string-valued metadata (e.g. {"color": "#e6194b", "directed": "true"}). Empty by default.

Notes

EventType objects use object-identity equality (eq=False), matching Track / Identity. Use matches() (default method="name") to compare event types across files, where Python object identity is not meaningful.

Methods:

Name Description
__init__

Method generated by attrs for class EventType.

__repr__

Return a readable string representation.

__setattr__

Method generated by attrs for class EventType.

matches

Check if this event type matches another event type.

Source code in sleap_io/model/event.py
@define(eq=False)
class EventType:
    """A type of event in the catalog (controlled vocabulary).

    A lightweight catalog object like `Track` / `Identity`: it is referenced by
    `Event`s and matched across separately-loaded files and merges by ``name``.
    Examples: a behavior (``"attack"``, ``"rear"``), a stimulus (``"light_on"``), a
    physiological event (``"seizure"``), or any labeled span.

    Attributes:
        name: Human-readable name for this event type (e.g. ``"attack"``). Not
            required to be unique, but ``name`` is how event types are matched across
            files and merges.
        description: Optional longer human-readable description of what this event
            type represents. Empty by default.
        metadata: Arbitrary string-keyed, string-valued metadata (e.g.
            ``{"color": "#e6194b", "directed": "true"}``). Empty by default.

    Notes:
        `EventType` objects use object-identity equality (``eq=False``), matching
        `Track` / `Identity`. Use `matches()` (default ``method="name"``) to compare
        event types across files, where Python object identity is not meaningful.
    """

    name: str = field(default="", validator=instance_of(str))
    description: str = field(default="", validator=instance_of(str))
    metadata: dict[str, str] = field(factory=dict, validator=instance_of(dict))

    def matches(self, other: "EventType", method: str = "name") -> bool:
        """Check if this event type matches another event type.

        Args:
            other: Another event type to compare with.
            method: Matching method:

                - ``"name"`` (default): match by the `name` attribute, which
                  survives serialization and cross-file merges.
                - ``"identity"``: match by Python object identity (same object).

        Returns:
            True if the event types match according to the specified method.

        Raises:
            ValueError: If `method` is not one of the supported values.
        """
        if method == "name":
            return self.name == other.name
        elif method == "identity":
            return self is other
        else:
            raise ValueError(f"Unknown matching method: {method}")

    def __repr__(self) -> str:
        """Return a readable string representation."""
        return f'EventType(name="{self.name}")'

__annotations__ = {'name': 'str', 'description': 'str', 'metadata': 'dict[str, str]'} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__attrs_own_setattr__ = True class-attribute

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

__attrs_props__ = ClassProps(is_exception=False, is_slotted=True, has_weakref_slot=True, is_frozen=False, kw_only=<KeywordOnly.NO: 'no'>, collected_fields_by_mro=True, added_init=True, added_repr=False, added_eq=False, added_ordering=False, hashability=<Hashability.LEAVE_ALONE: 'leave_alone'>, added_match_args=True, added_str=False, added_pickling=True, on_setattr_hook=<function pipe.<locals>.wrapped_pipe at 0x7f08471ce840>, field_transformer=None) class-attribute

Effective class properties as derived from parameters to attr.s() or define() decorators.

This is the same data structure that attrs uses internally to decide how to construct the final class.

Warning:

This feature is currently **experimental** and is not covered by our
strict backwards-compatibility guarantees.

Attributes:

Name Type Description
is_exception bool

Whether the class is treated as an exception class.

is_slotted bool

Whether the class is slotted <slotted classes>.

has_weakref_slot bool

Whether the class has a slot for weak references.

is_frozen bool

Whether the class is frozen.

kw_only KeywordOnly

Whether / how the class enforces keyword-only arguments on the __init__ method.

collected_fields_by_mro bool

Whether the class fields were collected by method resolution order. That is, correctly but unlike dataclasses.

added_init bool

Whether the class has an attrs-generated __init__ method.

added_repr bool

Whether the class has an attrs-generated __repr__ method.

added_eq bool

Whether the class has attrs-generated equality methods.

added_ordering bool

Whether the class has attrs-generated ordering methods.

hashability Hashability

How hashable <hashing> the class is.

added_match_args bool

Whether the class supports positional match <match> over its fields.

added_str bool

Whether the class has an attrs-generated __str__ method.

added_pickling bool

Whether the class has attrs-generated __getstate__ and __setstate__ methods for pickle.

on_setattr_hook Callable[[Any, Attribute[Any], Any], Any] | None

The class's __setattr__ hook.

field_transformer Callable[[Attribute[Any]], Attribute[Any]] | None

The class's field transformers <transform-fields>.

.. versionadded:: 25.4.0

__doc__ = 'A type of event in the catalog (controlled vocabulary).\n\nA lightweight catalog object like `Track` / `Identity`: it is referenced by\n`Event`s and matched across separately-loaded files and merges by ``name``.\nExamples: a behavior (``"attack"``, ``"rear"``), a stimulus (``"light_on"``), a\nphysiological event (``"seizure"``), or any labeled span.\n\nAttributes:\n name: Human-readable name for this event type (e.g. ``"attack"``). Not\n required to be unique, but ``name`` is how event types are matched across\n files and merges.\n description: Optional longer human-readable description of what this event\n type represents. Empty by default.\n metadata: Arbitrary string-keyed, string-valued metadata (e.g.\n ``{"color": "#e6194b", "directed": "true"}``). Empty by default.\n\nNotes:\n `EventType` objects use object-identity equality (``eq=False``), matching\n `Track` / `Identity`. Use `matches()` (default ``method="name"``) to compare\n event types across files, where Python object identity is not meaningful.\n' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 38 class-attribute

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('name', 'description', 'metadata') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'sleap_io.model.event' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__slots__ = ('name', 'description', 'metadata', '__weakref__') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = () class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__weakref__ property

list of weak references to the object

__init__(name='', description='', metadata=NOTHING)

Method generated by attrs for class EventType.

Source code in sleap_io/model/event.py
"""Data structures for frame-spanning event annotations.

Unlike every other annotation in sleap-io (`Instance`, `Centroid`, `BoundingBox`,
`SegmentationMask`, `LabelImage`, `ROI`), which are strictly per-frame and live on a
single `LabeledFrame`, an `Event` is the first annotation with a *temporal extent*: a
``(video, start_frame, end_frame, type)`` interval. Events model anything with a
duration -- behavior bouts, stimulus epochs, physiological events, feeding bouts,
review flags -- and are stored on ``Labels.events`` rather than on any one frame.

The class hierarchy mirrors the detection-modality pattern:
    - `EventType` -- a catalog / controlled-vocabulary entry (the "ethogram"),
      lightweight and name-matched like `Track` / `Identity`.

__repr__()

Return a readable string representation.

Source code in sleap_io/model/event.py
def __repr__(self) -> str:
    """Return a readable string representation."""
    return f'EventType(name="{self.name}")'

__setattr__(name, val)

Method generated by attrs for class EventType.

matches(other, method='name')

Check if this event type matches another event type.

Parameters:

Name Type Description Default
other EventType

Another event type to compare with.

required
method str

Matching method:

  • "name" (default): match by the name attribute, which survives serialization and cross-file merges.
  • "identity": match by Python object identity (same object).
'name'

Returns:

Type Description
bool

True if the event types match according to the specified method.

Raises:

Type Description
ValueError

If method is not one of the supported values.

Source code in sleap_io/model/event.py
def matches(self, other: "EventType", method: str = "name") -> bool:
    """Check if this event type matches another event type.

    Args:
        other: Another event type to compare with.
        method: Matching method:

            - ``"name"`` (default): match by the `name` attribute, which
              survives serialization and cross-file merges.
            - ``"identity"``: match by Python object identity (same object).

    Returns:
        True if the event types match according to the specified method.

    Raises:
        ValueError: If `method` is not one of the supported values.
    """
    if method == "name":
        return self.name == other.name
    elif method == "identity":
        return self is other
    else:
        raise ValueError(f"Unknown matching method: {method}")

sleap_io.Event

A labeled event spanning a range of frames in a video.

A frame-spanning annotation for anything with a temporal extent: behavior bouts, stimulus epochs, physiological events, review flags, etc. Unlike per-frame annotations, events live on Labels.events (not on a single LabeledFrame), since an event may cover frames that carry no pose labels.

The interval is inclusive on both ends: the event covers every frame in [start_frame, end_frame]. end_frame defaults to start_frame (an instantaneous, single-frame event) when not given.

Participants are optional and each may be a Track (a within-video trajectory) or an Identity (a cross-video animal):

  • subject -- who the event is about. None means a frame-level event with no individual (e.g. a stimulus epoch).
  • target -- who the event is directed at. None means the event is non-directed / individual ("self" in behavior-scoring terms).

Attributes:

Name Type Description
type

The EventType catalog entry for this event. A bare string is auto-promoted to EventType(name=...).

video

The Video the event occurs in.

start_frame

First frame of the event (inclusive).

end_frame

Last frame of the event (inclusive). Defaults to start_frame (an instantaneous event) when None. Must be >= start_frame.

subject

Optional Track or Identity the event is about. None means a frame-level event with no individual.

target

Optional Track or Identity the event is directed at. None means a non-directed / individual event ("self").

name

Optional human-readable name for this specific event instance.

source

Annotation source identifier.

metadata

Arbitrary string-keyed, string-valued metadata. Empty by default.

Notes

Events use object-identity equality (two Event objects are only equal if they are the same object in memory).

This class is abstract. Use UserEvent or PredictedEvent instead.

Methods:

Name Description
__attrs_post_init__

Guard abstract instantiation, fill end_frame, and validate the span.

__init__

Method generated by attrs for class Event.

__repr__

Method generated by attrs for class Event.

__setattr__

Method generated by attrs for class Event.

contains

Whether a frame index falls within this event's inclusive span.

overlaps

Whether this event overlaps another in the same video.

Source code in sleap_io/model/event.py
@define(eq=False)
class Event:
    """A labeled event spanning a range of frames in a video.

    A frame-spanning annotation for anything with a temporal extent: behavior bouts,
    stimulus epochs, physiological events, review flags, etc. Unlike per-frame
    annotations, events live on ``Labels.events`` (not on a single `LabeledFrame`),
    since an event may cover frames that carry no pose labels.

    The interval is **inclusive** on both ends: the event covers every frame in
    ``[start_frame, end_frame]``. ``end_frame`` defaults to ``start_frame`` (an
    instantaneous, single-frame event) when not given.

    Participants are optional and each may be a `Track` (a within-video trajectory) or
    an `Identity` (a cross-video animal):

    - ``subject`` -- who the event is *about*. ``None`` means a frame-level event with
      no individual (e.g. a stimulus epoch).
    - ``target`` -- who the event is *directed at*. ``None`` means the event is
      non-directed / individual (``"self"`` in behavior-scoring terms).

    Attributes:
        type: The `EventType` catalog entry for this event. A bare string is
            auto-promoted to ``EventType(name=...)``.
        video: The `Video` the event occurs in.
        start_frame: First frame of the event (inclusive).
        end_frame: Last frame of the event (inclusive). Defaults to ``start_frame``
            (an instantaneous event) when ``None``. Must be ``>= start_frame``.
        subject: Optional `Track` or `Identity` the event is about. ``None`` means a
            frame-level event with no individual.
        target: Optional `Track` or `Identity` the event is directed at. ``None`` means
            a non-directed / individual event (``"self"``).
        name: Optional human-readable name for this specific event instance.
        source: Annotation source identifier.
        metadata: Arbitrary string-keyed, string-valued metadata. Empty by default.

    Notes:
        Events use object-identity equality (two `Event` objects are only equal if they
        are the same object in memory).

        This class is abstract. Use `UserEvent` or `PredictedEvent` instead.
    """

    type: "EventType" = field(
        converter=_as_event_type, validator=instance_of(EventType)
    )
    video: "Video" = field()
    start_frame: int = field(converter=int)
    end_frame: "int | None" = field(default=None)
    subject: "Track | Identity | None" = field(default=None)
    target: "Track | Identity | None" = field(default=None)
    name: str = field(default="", validator=instance_of(str))
    source: str = field(default="", validator=instance_of(str))
    metadata: dict[str, str] = field(factory=dict, validator=instance_of(dict))

    def __attrs_post_init__(self):
        """Guard abstract instantiation, fill ``end_frame``, and validate the span."""
        if type(self) is Event:
            raise TypeError("Event is abstract. Use UserEvent or PredictedEvent.")
        if self.end_frame is None:
            self.end_frame = self.start_frame
        else:
            self.end_frame = int(self.end_frame)
        if self.end_frame < self.start_frame:
            raise ValueError(
                "Expected end_frame >= start_frame, got "
                f"start_frame={self.start_frame}, end_frame={self.end_frame}."
            )

    @property
    def is_predicted(self) -> bool:
        """Whether this event is a prediction."""
        return isinstance(self, PredictedEvent)

    @property
    def is_directed(self) -> bool:
        """Whether this event is directed at a `target` (vs. non-directed / self)."""
        return self.target is not None

    @property
    def is_instantaneous(self) -> bool:
        """Whether this event spans a single frame (``start_frame == end_frame``)."""
        return self.end_frame == self.start_frame

    @property
    def n_frames(self) -> int:
        """Number of frames spanned (inclusive: ``end_frame - start_frame + 1``)."""
        return self.end_frame - self.start_frame + 1

    @property
    def frames(self) -> range:
        """The inclusive range of frame indices covered by this event.

        Returns:
            A ``range(start_frame, end_frame + 1)``. Its length equals `n_frames` and,
            for a `PredictedEvent`, aligns element-wise with a framewise `scores` trace.
            Returned lazily as a ``range`` (not a materialized array) so events spanning
            hundreds of thousands of frames stay cheap.
        """
        return range(self.start_frame, self.end_frame + 1)

    def contains(self, frame_idx: int) -> bool:
        """Whether a frame index falls within this event's inclusive span.

        Args:
            frame_idx: A frame index to test.

        Returns:
            True if ``start_frame <= frame_idx <= end_frame``.
        """
        return self.start_frame <= frame_idx <= self.end_frame

    def overlaps(self, other: "Event") -> bool:
        """Whether this event overlaps another in the same video.

        Two events overlap when they occur in the same `Video` (compared by object
        identity) and their inclusive frame spans intersect. Events in different videos
        never overlap, regardless of their frame indices.

        Args:
            other: Another event to test against.

        Returns:
            True if both events share a video and their spans intersect.
        """
        if self.video is not other.video:
            return False
        return (
            self.start_frame <= other.end_frame and other.start_frame <= self.end_frame
        )

__annotations__ = {'type': "'EventType'", 'video': "'Video'", 'start_frame': 'int', 'end_frame': "'int | None'", 'subject': "'Track | Identity | None'", 'target': "'Track | Identity | None'", 'name': 'str', 'source': 'str', 'metadata': 'dict[str, str]'} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__attrs_own_setattr__ = True class-attribute

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

__attrs_props__ = ClassProps(is_exception=False, is_slotted=True, has_weakref_slot=True, is_frozen=False, kw_only=<KeywordOnly.NO: 'no'>, collected_fields_by_mro=True, added_init=True, added_repr=True, added_eq=False, added_ordering=False, hashability=<Hashability.LEAVE_ALONE: 'leave_alone'>, added_match_args=True, added_str=False, added_pickling=True, on_setattr_hook=<function pipe.<locals>.wrapped_pipe at 0x7f08471ce840>, field_transformer=None) class-attribute

Effective class properties as derived from parameters to attr.s() or define() decorators.

This is the same data structure that attrs uses internally to decide how to construct the final class.

Warning:

This feature is currently **experimental** and is not covered by our
strict backwards-compatibility guarantees.

Attributes:

Name Type Description
is_exception bool

Whether the class is treated as an exception class.

is_slotted bool

Whether the class is slotted <slotted classes>.

has_weakref_slot bool

Whether the class has a slot for weak references.

is_frozen bool

Whether the class is frozen.

kw_only KeywordOnly

Whether / how the class enforces keyword-only arguments on the __init__ method.

collected_fields_by_mro bool

Whether the class fields were collected by method resolution order. That is, correctly but unlike dataclasses.

added_init bool

Whether the class has an attrs-generated __init__ method.

added_repr bool

Whether the class has an attrs-generated __repr__ method.

added_eq bool

Whether the class has attrs-generated equality methods.

added_ordering bool

Whether the class has attrs-generated ordering methods.

hashability Hashability

How hashable <hashing> the class is.

added_match_args bool

Whether the class supports positional match <match> over its fields.

added_str bool

Whether the class has an attrs-generated __str__ method.

added_pickling bool

Whether the class has attrs-generated __getstate__ and __setstate__ methods for pickle.

on_setattr_hook Callable[[Any, Attribute[Any], Any], Any] | None

The class's __setattr__ hook.

field_transformer Callable[[Attribute[Any]], Attribute[Any]] | None

The class's field transformers <transform-fields>.

.. versionadded:: 25.4.0

__doc__ = 'A labeled event spanning a range of frames in a video.\n\nA frame-spanning annotation for anything with a temporal extent: behavior bouts,\nstimulus epochs, physiological events, review flags, etc. Unlike per-frame\nannotations, events live on ``Labels.events`` (not on a single `LabeledFrame`),\nsince an event may cover frames that carry no pose labels.\n\nThe interval is **inclusive** on both ends: the event covers every frame in\n``[start_frame, end_frame]``. ``end_frame`` defaults to ``start_frame`` (an\ninstantaneous, single-frame event) when not given.\n\nParticipants are optional and each may be a `Track` (a within-video trajectory) or\nan `Identity` (a cross-video animal):\n\n- ``subject`` -- who the event is *about*. ``None`` means a frame-level event with\n no individual (e.g. a stimulus epoch).\n- ``target`` -- who the event is *directed at*. ``None`` means the event is\n non-directed / individual (``"self"`` in behavior-scoring terms).\n\nAttributes:\n type: The `EventType` catalog entry for this event. A bare string is\n auto-promoted to ``EventType(name=...)``.\n video: The `Video` the event occurs in.\n start_frame: First frame of the event (inclusive).\n end_frame: Last frame of the event (inclusive). Defaults to ``start_frame``\n (an instantaneous event) when ``None``. Must be ``>= start_frame``.\n subject: Optional `Track` or `Identity` the event is about. ``None`` means a\n frame-level event with no individual.\n target: Optional `Track` or `Identity` the event is directed at. ``None`` means\n a non-directed / individual event (``"self"``).\n name: Optional human-readable name for this specific event instance.\n source: Annotation source identifier.\n metadata: Arbitrary string-keyed, string-valued metadata. Empty by default.\n\nNotes:\n Events use object-identity equality (two `Event` objects are only equal if they\n are the same object in memory).\n\n This class is abstract. Use `UserEvent` or `PredictedEvent` instead.\n' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 135 class-attribute

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('type', 'video', 'start_frame', 'end_frame', 'subject', 'target', 'name', 'source', 'metadata') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'sleap_io.model.event' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__slots__ = ('type', 'video', 'start_frame', 'end_frame', 'subject', 'target', 'name', 'source', 'metadata', '__weakref__') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = ('end_frame',) class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__weakref__ property

list of weak references to the object

frames property

The inclusive range of frame indices covered by this event.

Returns:

Type Description

A range(start_frame, end_frame + 1). Its length equals n_frames and, for a PredictedEvent, aligns element-wise with a framewise scores trace. Returned lazily as a range (not a materialized array) so events spanning hundreds of thousands of frames stay cheap.

is_directed property

Whether this event is directed at a target (vs. non-directed / self).

is_instantaneous property

Whether this event spans a single frame (start_frame == end_frame).

is_predicted property

Whether this event is a prediction.

n_frames property

Number of frames spanned (inclusive: end_frame - start_frame + 1).

__attrs_post_init__()

Guard abstract instantiation, fill end_frame, and validate the span.

Source code in sleap_io/model/event.py
def __attrs_post_init__(self):
    """Guard abstract instantiation, fill ``end_frame``, and validate the span."""
    if type(self) is Event:
        raise TypeError("Event is abstract. Use UserEvent or PredictedEvent.")
    if self.end_frame is None:
        self.end_frame = self.start_frame
    else:
        self.end_frame = int(self.end_frame)
    if self.end_frame < self.start_frame:
        raise ValueError(
            "Expected end_frame >= start_frame, got "
            f"start_frame={self.start_frame}, end_frame={self.end_frame}."
        )

__init__(type, video, start_frame, end_frame=None, subject=None, target=None, name='', source='', metadata=NOTHING)

Method generated by attrs for class Event.

Source code in sleap_io/model/event.py
Frame convention:
    ``start_frame`` and ``end_frame`` are both **inclusive** -- an event covers every
    frame in ``[start_frame, end_frame]`` and spans ``end_frame - start_frame + 1``
    frames. An event with ``end_frame == start_frame`` (or ``end_frame=None``, which is
    filled to ``start_frame``) is *instantaneous* (a single frame).
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import numpy as np
from attrs import define, field
from attrs.validators import instance_of

if TYPE_CHECKING:
    from sleap_io.model.identity import Identity
    from sleap_io.model.instance import Track
    from sleap_io.model.video import Video

__repr__()

Method generated by attrs for class Event.

Source code in sleap_io/model/event.py
"""Data structures for frame-spanning event annotations.

Unlike every other annotation in sleap-io (`Instance`, `Centroid`, `BoundingBox`,
`SegmentationMask`, `LabelImage`, `ROI`), which are strictly per-frame and live on a
single `LabeledFrame`, an `Event` is the first annotation with a *temporal extent*: a
``(video, start_frame, end_frame, type)`` interval. Events model anything with a
duration -- behavior bouts, stimulus epochs, physiological events, feeding bouts,
review flags -- and are stored on ``Labels.events`` rather than on any one frame.

The class hierarchy mirrors the detection-modality pattern:
    - `EventType` -- a catalog / controlled-vocabulary entry (the "ethogram"),
      lightweight and name-matched like `Track` / `Identity`.
    - `Event` -- abstract base carrying the interval, participants, and metadata.
    - `UserEvent` -- a human-annotated event (ground truth).
    - `PredictedEvent` -- a model-predicted event with optional confidence score(s).

__setattr__(name, val)

Method generated by attrs for class Event.

contains(frame_idx)

Whether a frame index falls within this event's inclusive span.

Parameters:

Name Type Description Default
frame_idx int

A frame index to test.

required

Returns:

Type Description
bool

True if start_frame <= frame_idx <= end_frame.

Source code in sleap_io/model/event.py
def contains(self, frame_idx: int) -> bool:
    """Whether a frame index falls within this event's inclusive span.

    Args:
        frame_idx: A frame index to test.

    Returns:
        True if ``start_frame <= frame_idx <= end_frame``.
    """
    return self.start_frame <= frame_idx <= self.end_frame

overlaps(other)

Whether this event overlaps another in the same video.

Two events overlap when they occur in the same Video (compared by object identity) and their inclusive frame spans intersect. Events in different videos never overlap, regardless of their frame indices.

Parameters:

Name Type Description Default
other Event

Another event to test against.

required

Returns:

Type Description
bool

True if both events share a video and their spans intersect.

Source code in sleap_io/model/event.py
def overlaps(self, other: "Event") -> bool:
    """Whether this event overlaps another in the same video.

    Two events overlap when they occur in the same `Video` (compared by object
    identity) and their inclusive frame spans intersect. Events in different videos
    never overlap, regardless of their frame indices.

    Args:
        other: Another event to test against.

    Returns:
        True if both events share a video and their spans intersect.
    """
    if self.video is not other.video:
        return False
    return (
        self.start_frame <= other.end_frame and other.start_frame <= self.end_frame
    )

sleap_io.UserEvent

Bases: sleap_io.model.event.Event

A human-annotated event (ground truth).

Inherits all fields from Event. Has no additional fields.

See Event for attribute documentation.

Methods:

Name Description
__init__

Method generated by attrs for class UserEvent.

__repr__

Method generated by attrs for class UserEvent.

__setattr__

Method generated by attrs for class UserEvent.

Attributes:

Name Type Description
__annotations__

dict() -> new empty dictionary

__attrs_own_setattr__

Returns True when the argument is true, False otherwise.

__attrs_props__

Effective class properties as derived from parameters to attr.s() or

__doc__

str(object='') -> str

__firstlineno__

int([x]) -> integer

__match_args__

Built-in immutable sequence.

__module__

str(object='') -> str

__slots__

Built-in immutable sequence.

__static_attributes__

Built-in immutable sequence.

Source code in sleap_io/model/event.py
@define(eq=False)
class UserEvent(Event):
    """A human-annotated event (ground truth).

    Inherits all fields from `Event`. Has no additional fields.

    See `Event` for attribute documentation.
    """

    pass

__annotations__ = {} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__attrs_own_setattr__ = True class-attribute

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

__attrs_props__ = ClassProps(is_exception=False, is_slotted=True, has_weakref_slot=True, is_frozen=False, kw_only=<KeywordOnly.NO: 'no'>, collected_fields_by_mro=True, added_init=True, added_repr=True, added_eq=False, added_ordering=False, hashability=<Hashability.LEAVE_ALONE: 'leave_alone'>, added_match_args=True, added_str=False, added_pickling=True, on_setattr_hook=<function pipe.<locals>.wrapped_pipe at 0x7f08471ce840>, field_transformer=None) class-attribute

Effective class properties as derived from parameters to attr.s() or define() decorators.

This is the same data structure that attrs uses internally to decide how to construct the final class.

Warning:

This feature is currently **experimental** and is not covered by our
strict backwards-compatibility guarantees.

Attributes:

Name Type Description
is_exception bool

Whether the class is treated as an exception class.

is_slotted bool

Whether the class is slotted <slotted classes>.

has_weakref_slot bool

Whether the class has a slot for weak references.

is_frozen bool

Whether the class is frozen.

kw_only KeywordOnly

Whether / how the class enforces keyword-only arguments on the __init__ method.

collected_fields_by_mro bool

Whether the class fields were collected by method resolution order. That is, correctly but unlike dataclasses.

added_init bool

Whether the class has an attrs-generated __init__ method.

added_repr bool

Whether the class has an attrs-generated __repr__ method.

added_eq bool

Whether the class has attrs-generated equality methods.

added_ordering bool

Whether the class has attrs-generated ordering methods.

hashability Hashability

How hashable <hashing> the class is.

added_match_args bool

Whether the class supports positional match <match> over its fields.

added_str bool

Whether the class has an attrs-generated __str__ method.

added_pickling bool

Whether the class has attrs-generated __getstate__ and __setstate__ methods for pickle.

on_setattr_hook Callable[[Any, Attribute[Any], Any], Any] | None

The class's __setattr__ hook.

field_transformer Callable[[Attribute[Any]], Attribute[Any]] | None

The class's field transformers <transform-fields>.

.. versionadded:: 25.4.0

__doc__ = 'A human-annotated event (ground truth).\n\nInherits all fields from `Event`. Has no additional fields.\n\nSee `Event` for attribute documentation.\n' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 267 class-attribute

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('type', 'video', 'start_frame', 'end_frame', 'subject', 'target', 'name', 'source', 'metadata') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'sleap_io.model.event' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__slots__ = () class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = () class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__init__(type, video, start_frame, end_frame=None, subject=None, target=None, name='', source='', metadata=NOTHING)

Method generated by attrs for class UserEvent.

Source code in sleap_io/model/event.py
Frame convention:
    ``start_frame`` and ``end_frame`` are both **inclusive** -- an event covers every
    frame in ``[start_frame, end_frame]`` and spans ``end_frame - start_frame + 1``
    frames. An event with ``end_frame == start_frame`` (or ``end_frame=None``, which is
    filled to ``start_frame``) is *instantaneous* (a single frame).
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import numpy as np
from attrs import define, field
from attrs.validators import instance_of

if TYPE_CHECKING:
    from sleap_io.model.identity import Identity
    from sleap_io.model.instance import Track
    from sleap_io.model.video import Video

__repr__()

Method generated by attrs for class UserEvent.

Source code in sleap_io/model/event.py
"""Data structures for frame-spanning event annotations.

Unlike every other annotation in sleap-io (`Instance`, `Centroid`, `BoundingBox`,
`SegmentationMask`, `LabelImage`, `ROI`), which are strictly per-frame and live on a
single `LabeledFrame`, an `Event` is the first annotation with a *temporal extent*: a
``(video, start_frame, end_frame, type)`` interval. Events model anything with a
duration -- behavior bouts, stimulus epochs, physiological events, feeding bouts,
review flags -- and are stored on ``Labels.events`` rather than on any one frame.

The class hierarchy mirrors the detection-modality pattern:
    - `EventType` -- a catalog / controlled-vocabulary entry (the "ethogram"),
      lightweight and name-matched like `Track` / `Identity`.
    - `Event` -- abstract base carrying the interval, participants, and metadata.
    - `UserEvent` -- a human-annotated event (ground truth).
    - `PredictedEvent` -- a model-predicted event with optional confidence score(s).

__setattr__(name, val)

Method generated by attrs for class UserEvent.

sleap_io.PredictedEvent

Bases: sleap_io.model.event.Event

A model-predicted event.

Adds two independent, optional confidence fields. A predictor sets whichever it produces (a framewise trace, an event-level scalar, both, or neither); neither is derived from the other.

Attributes:

Name Type Description
scores

Optional framewise confidence trace of shape (n_frames,), aligned element-wise to frames (i.e. [start_frame, end_frame]). Stored as float32. Validated to have length n_frames when set. None if the predictor produced no per-frame trace.

score

Optional scalar event-level confidence. None if unset. Not derived from scores.

See Event for other attribute documentation.

Methods:

Name Description
__attrs_post_init__

Validate the framewise scores length against n_frames.

__init__

Method generated by attrs for class PredictedEvent.

__repr__

Method generated by attrs for class PredictedEvent.

__setattr__

Method generated by attrs for class PredictedEvent.

Source code in sleap_io/model/event.py
@define(eq=False)
class PredictedEvent(Event):
    """A model-predicted event.

    Adds two independent, optional confidence fields. A predictor sets whichever it
    produces (a framewise trace, an event-level scalar, both, or neither); neither is
    derived from the other.

    Attributes:
        scores: Optional framewise confidence trace of shape ``(n_frames,)``, aligned
            element-wise to `frames` (i.e. ``[start_frame, end_frame]``). Stored as
            ``float32``. Validated to have length `n_frames` when set. ``None`` if the
            predictor produced no per-frame trace.
        score: Optional scalar event-level confidence. ``None`` if unset. **Not**
            derived from `scores`.

    See `Event` for other attribute documentation.
    """

    scores: "np.ndarray | None" = field(default=None, converter=_as_scores, repr=False)
    score: "float | None" = field(default=None)

    def __attrs_post_init__(self):
        """Validate the framewise `scores` length against `n_frames`."""
        super().__attrs_post_init__()
        if self.scores is not None and len(self.scores) != self.n_frames:
            raise ValueError(
                "Framewise event scores must have length n_frames "
                f"({self.n_frames}), got {len(self.scores)}."
            )

__annotations__ = {'scores': "'np.ndarray | None'", 'score': "'float | None'"} class-attribute

dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

__attrs_own_setattr__ = True class-attribute

Returns True when the argument is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

__attrs_props__ = ClassProps(is_exception=False, is_slotted=True, has_weakref_slot=True, is_frozen=False, kw_only=<KeywordOnly.NO: 'no'>, collected_fields_by_mro=True, added_init=True, added_repr=True, added_eq=False, added_ordering=False, hashability=<Hashability.LEAVE_ALONE: 'leave_alone'>, added_match_args=True, added_str=False, added_pickling=True, on_setattr_hook=<function pipe.<locals>.wrapped_pipe at 0x7f08471ce840>, field_transformer=None) class-attribute

Effective class properties as derived from parameters to attr.s() or define() decorators.

This is the same data structure that attrs uses internally to decide how to construct the final class.

Warning:

This feature is currently **experimental** and is not covered by our
strict backwards-compatibility guarantees.

Attributes:

Name Type Description
is_exception bool

Whether the class is treated as an exception class.

is_slotted bool

Whether the class is slotted <slotted classes>.

has_weakref_slot bool

Whether the class has a slot for weak references.

is_frozen bool

Whether the class is frozen.

kw_only KeywordOnly

Whether / how the class enforces keyword-only arguments on the __init__ method.

collected_fields_by_mro bool

Whether the class fields were collected by method resolution order. That is, correctly but unlike dataclasses.

added_init bool

Whether the class has an attrs-generated __init__ method.

added_repr bool

Whether the class has an attrs-generated __repr__ method.

added_eq bool

Whether the class has attrs-generated equality methods.

added_ordering bool

Whether the class has attrs-generated ordering methods.

hashability Hashability

How hashable <hashing> the class is.

added_match_args bool

Whether the class supports positional match <match> over its fields.

added_str bool

Whether the class has an attrs-generated __str__ method.

added_pickling bool

Whether the class has attrs-generated __getstate__ and __setstate__ methods for pickle.

on_setattr_hook Callable[[Any, Attribute[Any], Any], Any] | None

The class's __setattr__ hook.

field_transformer Callable[[Attribute[Any]], Attribute[Any]] | None

The class's field transformers <transform-fields>.

.. versionadded:: 25.4.0

__doc__ = 'A model-predicted event.\n\nAdds two independent, optional confidence fields. A predictor sets whichever it\nproduces (a framewise trace, an event-level scalar, both, or neither); neither is\nderived from the other.\n\nAttributes:\n scores: Optional framewise confidence trace of shape ``(n_frames,)``, aligned\n element-wise to `frames` (i.e. ``[start_frame, end_frame]``). Stored as\n ``float32``. Validated to have length `n_frames` when set. ``None`` if the\n predictor produced no per-frame trace.\n score: Optional scalar event-level confidence. ``None`` if unset. **Not**\n derived from `scores`.\n\nSee `Event` for other attribute documentation.\n' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__firstlineno__ = 279 class-attribute

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.int(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral.

int('0b100', base=0) 4

__match_args__ = ('type', 'video', 'start_frame', 'end_frame', 'subject', 'target', 'name', 'source', 'metadata', 'scores', 'score') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__module__ = 'sleap_io.model.event' class-attribute

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.str() (if defined) or repr(object). encoding defaults to 'utf-8'. errors defaults to 'strict'.

__slots__ = ('scores', 'score') class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__static_attributes__ = () class-attribute

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.

If the argument is a tuple, the return value is the same object.

__attrs_post_init__()

Validate the framewise scores length against n_frames.

Source code in sleap_io/model/event.py
def __attrs_post_init__(self):
    """Validate the framewise `scores` length against `n_frames`."""
    super().__attrs_post_init__()
    if self.scores is not None and len(self.scores) != self.n_frames:
        raise ValueError(
            "Framewise event scores must have length n_frames "
            f"({self.n_frames}), got {len(self.scores)}."
        )

__init__(type, video, start_frame, end_frame=None, subject=None, target=None, name='', source='', metadata=NOTHING, scores=None, score=None)

Method generated by attrs for class PredictedEvent.

Source code in sleap_io/model/event.py
Frame convention:
    ``start_frame`` and ``end_frame`` are both **inclusive** -- an event covers every
    frame in ``[start_frame, end_frame]`` and spans ``end_frame - start_frame + 1``
    frames. An event with ``end_frame == start_frame`` (or ``end_frame=None``, which is
    filled to ``start_frame``) is *instantaneous* (a single frame).
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import numpy as np
from attrs import define, field
from attrs.validators import instance_of

if TYPE_CHECKING:
    from sleap_io.model.identity import Identity
    from sleap_io.model.instance import Track
    from sleap_io.model.video import Video

__repr__()

Method generated by attrs for class PredictedEvent.

Source code in sleap_io/model/event.py
"""Data structures for frame-spanning event annotations.

Unlike every other annotation in sleap-io (`Instance`, `Centroid`, `BoundingBox`,
`SegmentationMask`, `LabelImage`, `ROI`), which are strictly per-frame and live on a
single `LabeledFrame`, an `Event` is the first annotation with a *temporal extent*: a
``(video, start_frame, end_frame, type)`` interval. Events model anything with a
duration -- behavior bouts, stimulus epochs, physiological events, feeding bouts,
review flags -- and are stored on ``Labels.events`` rather than on any one frame.

The class hierarchy mirrors the detection-modality pattern:
    - `EventType` -- a catalog / controlled-vocabulary entry (the "ethogram"),
      lightweight and name-matched like `Track` / `Identity`.
    - `Event` -- abstract base carrying the interval, participants, and metadata.
    - `UserEvent` -- a human-annotated event (ground truth).
    - `PredictedEvent` -- a model-predicted event with optional confidence score(s).

__setattr__(name, val)

Method generated by attrs for class PredictedEvent.