File size: 9,319 Bytes
9e18664
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
from __future__ import annotations

from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, overload

import numpy as np
import pyarrow as pa

import rerun_bindings as bindings

if TYPE_CHECKING:
    from rerun.recording_stream import RecordingStream

# --- Time ---


# These overloads ensure that mypy can catch errors that would otherwise not be caught until runtime.
@overload
def set_time(timeline: str, *, recording: RecordingStream | None = None, sequence: int) -> None: ...


@overload
def set_time(
    timeline: str,
    *,
    recording: RecordingStream | None = None,
    duration: int | float | timedelta | np.timedelta64,
) -> None: ...


@overload
def set_time(
    timeline: str,
    *,
    recording: RecordingStream | None = None,
    timestamp: int | float | datetime | np.datetime64,
) -> None: ...


def set_time(
    timeline: str,
    *,
    recording: RecordingStream | None = None,
    sequence: int | None = None,
    duration: int | float | timedelta | np.timedelta64 | None = None,
    timestamp: int | float | datetime | np.datetime64 | pa.TimestampScalar | None = None,
) -> None:
    """
    Set the current time of a timeline for this thread.

    Used for all subsequent logging on the same thread, until the next call to
    [`rerun.set_time`][], [`rerun.reset_time`][] or [`rerun.disable_timeline`][].

    For example: `set_time("frame_nr", sequence=frame_nr)`.

    There is no requirement of monotonicity. You can move the time backwards if you like.

    You are expected to set exactly ONE of the arguments `sequence`, `duration`, or `timestamp`.
    You may NOT change the type of a timeline, so if you use `duration` for a specific timeline,
    you must only use `duration` for that timeline going forward.

    The columnar equivalent to this function is [`rerun.TimeColumn`][].

    Parameters
    ----------
    timeline:
        The name of the timeline to set the time for.
    recording:
        Specifies the [`rerun.RecordingStream`][] to use.
        If left unspecified, defaults to the current active data recording (if there is one).
        See also: [`rerun.init`][], [`rerun.set_global_data_recording`][].
    sequence:
        Used for sequential indices, like `frame_nr`.
        Must be an integer.
    duration:
        Used for relative times, like `time_since_start`.
        Must either be in seconds, a [`datetime.timedelta`][], or [`numpy.timedelta64`][].
        For nanosecond precision, use `numpy.timedelta64(nanoseconds, 'ns')`.
    timestamp:
        Used for absolute time indices, like `capture_time`.
        Must either be in seconds since Unix epoch, a [`datetime.datetime`][], or [`numpy.datetime64`][].
        For nanosecond precision, use `numpy.datetime64(nanoseconds, 'ns')`.

    """
    if sum(x is not None for x in (sequence, duration, timestamp)) != 1:
        raise ValueError(
            f"set_time: Exactly one of `sequence`, `duration`, and `timestamp` must be set (timeline='{timeline}')",
        )

    if sequence is not None:
        bindings.set_time_sequence(
            timeline,
            sequence,
            recording=recording.to_native() if recording is not None else None,
        )
    elif duration is not None:
        nanos = to_nanos(duration)
        bindings.set_time_duration_nanos(
            timeline,
            nanos,
            recording=recording.to_native() if recording is not None else None,
        )
    elif timestamp is not None:
        nanos = to_nanos_since_epoch(timestamp)
        bindings.set_time_timestamp_nanos_since_epoch(
            timeline,
            nanos,
            recording=recording.to_native() if recording is not None else None,
        )


def to_nanos(duration: int | np.integer | float | np.float64 | timedelta | np.timedelta64) -> int:
    if isinstance(duration, np.timedelta64):
        return duration.astype("timedelta64[ns]").astype("int64")  # type: ignore[no-any-return]
    elif isinstance(duration, timedelta):
        return round(1e9 * duration.total_seconds())
    elif isinstance(duration, (int, np.integer)):
        return 1_000_000_000 * int(duration)  # Interpret as seconds and convert to nanos
    elif isinstance(
        duration,
        (float, np.floating),
    ):
        return round(1e9 * float(duration))  # Interpret as seconds and convert to nanos
    else:
        raise TypeError(
            f"set_time: duration must be an int, float, timedelta, or numpy.timedelta64 object, got {type(duration)}",
        )


def to_nanos_since_epoch(
    timestamp: int | np.integer | float | np.float64 | datetime | np.datetime64 | pa.TimestampScalar,
) -> int:
    # Only allowing f64 since anything less has way too little precision for measuring time since 1970
    if isinstance(timestamp, (int, np.integer, float, np.float64)):
        if timestamp > 1e11:
            raise ValueError("set_time: Expected seconds since unix epoch, but it looks like this is in milliseconds")
        return int(np.round(1e9 * timestamp))  # Interpret as seconds and convert to nanos
    elif isinstance(timestamp, datetime):
        # Special case pandas to avoid loss of precision
        if (to_datetime64 := getattr(timestamp, "to_datetime64", None)) is not None:
            datetime64: np.datetime64 = to_datetime64()
            return int(datetime64.astype("datetime64[ns]").astype("int64"))

        if timestamp.tzinfo is None:
            timestamp = timestamp.replace(tzinfo=UTC)
        else:
            timestamp = timestamp.astimezone(UTC)
        epoch = datetime(1970, 1, 1, tzinfo=UTC)

        return int(np.round(1e9 * (timestamp - epoch).total_seconds()))
    elif isinstance(timestamp, np.datetime64):
        return int(timestamp.astype("datetime64[ns]").astype("int64"))
    elif isinstance(timestamp, pa.TimestampScalar):
        return int(timestamp.value)
    else:
        raise TypeError(
            f"set_time: timestamp must be an int, float, datetime, numpy.datetime64, or pyarrow.TimestampScalar object, got {type(timestamp)}",
        )


# TODO(emilk): rename to something with the word `index`, and maybe unify with `reset_time`?
def disable_timeline(timeline: str, recording: RecordingStream | None = None) -> None:
    """
    Clear time information for the specified timeline on this thread.

    Parameters
    ----------
    timeline:
        The name of the timeline to clear the time for.
    recording:
        Specifies the [`rerun.RecordingStream`][] to use.
        If left unspecified, defaults to the current active data recording, if there is one.
        See also: [`rerun.init`][], [`rerun.set_global_data_recording`][].

    """

    bindings.disable_timeline(
        timeline,
        recording=recording.to_native() if recording is not None else None,
    )


# TODO(emilk): rename to something with the word `index`, and maybe unify with `disable_timeline`?
def reset_time(recording: RecordingStream | None = None) -> None:
    """
    Clear all timeline information on this thread.

    This is the same as calling `disable_timeline` for all of the active timelines.

    Used for all subsequent logging on the same thread,
    until the next call to [`rerun.set_time`][].

    Parameters
    ----------
    recording:
        Specifies the [`rerun.RecordingStream`][] to use.
        If left unspecified, defaults to the current active data recording, if there is one.
        See also: [`rerun.init`][], [`rerun.set_global_data_recording`][].

    """

    bindings.reset_time(
        recording=recording.to_native() if recording is not None else None,
    )


def set_log_tick_enabled(enabled: bool, recording: RecordingStream | None = None) -> None:
    """
    Enable or disable automatic injection of the `log_tick` timeline into logged data.

    `log_tick` is a per-recording counter that increments on every logging call.
    It is **disabled** by default (it can also be controlled via the `RERUN_LOG_TICK` environment variable).

    Parameters
    ----------
    enabled:
        Whether to inject the `log_tick` timeline.
    recording:
        Specifies the [`rerun.RecordingStream`][] to use.
        If left unspecified, defaults to the current active data recording, if there is one.
        See also: [`rerun.init`][], [`rerun.set_global_data_recording`][].

    """

    bindings.set_log_tick_enabled(
        enabled,
        recording=recording.to_native() if recording is not None else None,
    )


def set_log_time_enabled(enabled: bool, recording: RecordingStream | None = None) -> None:
    """
    Enable or disable automatic injection of the `log_time` timeline into logged data.

    `log_time` is the wall-clock time at which data was logged.
    It is **enabled** by default (it can also be controlled via the `RERUN_LOG_TIME` environment variable).

    Parameters
    ----------
    enabled:
        Whether to inject the `log_time` timeline.
    recording:
        Specifies the [`rerun.RecordingStream`][] to use.
        If left unspecified, defaults to the current active data recording, if there is one.
        See also: [`rerun.init`][], [`rerun.set_global_data_recording`][].

    """

    bindings.set_log_time_enabled(
        enabled,
        recording=recording.to_native() if recording is not None else None,
    )