sc2nachos.gametime

Game time, counted in steps: GameTime, the game's speeds, and TimeSeries, values a bot records against the game time.

 1"""Game time, counted in steps: `GameTime`, the game's speeds, and `TimeSeries`, values a bot records against the
 2game time."""
 3
 4from sc2nachos.gametime._game_speed import (
 5    FASTER_PER_NORMAL_SPEED,
 6    SECONDS_PER_STEP,
 7    STEPS_PER_NORMAL_SECOND,
 8    STEPS_PER_SECOND,
 9)
10from sc2nachos.gametime._game_time import GameTime
11from sc2nachos.gametime._time_series import TimeSeries
12
13__all__ = [
14    "FASTER_PER_NORMAL_SPEED",
15    "SECONDS_PER_STEP",
16    "STEPS_PER_NORMAL_SECOND",
17    "STEPS_PER_SECOND",
18    "GameTime",
19    "TimeSeries",
20]
FASTER_PER_NORMAL_SPEED = 1.4
SECONDS_PER_STEP = 0.044642857142857144
STEPS_PER_NORMAL_SECOND = 16
STEPS_PER_SECOND = 22.4
@dataclass(frozen=True, slots=True, init=False, eq=False, match_args=False)
class GameTime:
 22@dataclass(frozen=True, slots=True, init=False, eq=False, match_args=False)
 23class GameTime:
 24    """A moment of a game, counted from its start, or a length of game time, in steps of the game: 22.4 make a
 25    second at the Faster speed games are played at.
 26
 27    Made from one of `steps`; `seconds` at the Faster speed; or `normal_seconds` at the Normal speed, 16 steps a
 28    second, in which the game gives some times, such as a weapon's cooldown. `GameTime(seconds=120)` is 2688 steps.
 29    Steps are kept as given. Seconds are multiplied out unrounded, exactly where they make a whole number of steps, so
 30    `GameTime(seconds=45) == GameTime(steps=1008)`; normal seconds exactly, 16 being a power of two. Any other
 31    keyword, none, or more than one raises `TypeError`.
 32
 33    A moment is a whole number of steps; a length may be fractional, as a weapon's cooldown is. Two add, subtract and
 34    take `%` to a `GameTime`, and divide, `/` or `//`, to a plain number; one multiplies by a plain number and divides
 35    by one to a `GameTime`. It orders against another `GameTime` alone: compared with a plain number it raises
 36    `TypeError`, and it equals none. Zero is false, and is `GameTime.ZERO`; `GameTime.INFINITE` is later and longer
 37    than any other.
 38    """
 39
 40    # Makes a numpy scalar on the left, `numpy.float64(2) * time`, hand over to `__rmul__` instead of reading the time
 41    # as an array.
 42    __array_ufunc__ = None
 43
 44    ZERO: ClassVar[GameTime]
 45    """No time: the game's start, or a length of none."""
 46
 47    INFINITE: ClassVar[GameTime]
 48    """The time of what never comes, later and longer than any other, as `math.inf` is a number larger than any. It
 49    orders above every finite time and stays infinite when one is added or subtracted, and `seconds` reads
 50    `math.inf`, and `to_string` `"inf"`; `nearest_step` and dividing it by `//` raise `ValueError`. Subtracting it
 51    from itself, multiplying it by zero or taking its remainder gives a time of NaN steps, which equals none."""
 52
 53    steps: float
 54    """The steps of the game it counts."""
 55
 56    @overload
 57    def __init__(self, *, steps: float) -> None: ...
 58
 59    @overload
 60    def __init__(self, *, seconds: float) -> None: ...
 61
 62    @overload
 63    def __init__(self, *, normal_seconds: float) -> None: ...
 64
 65    def __init__(
 66        self, *, steps: float | None = None, seconds: float | None = None, normal_seconds: float | None = None
 67    ) -> None:
 68        if steps is not None:
 69            if seconds is not None or normal_seconds is not None:
 70                raise _not_one_unit_error(steps=steps, seconds=seconds, normal_seconds=normal_seconds)
 71            counted_steps = steps
 72        elif seconds is not None:
 73            if normal_seconds is not None:
 74                raise _not_one_unit_error(steps=steps, seconds=seconds, normal_seconds=normal_seconds)
 75            counted_steps = seconds * _STEPS_PER_FIVE_SECONDS / 5
 76        elif normal_seconds is not None:
 77            counted_steps = normal_seconds * STEPS_PER_NORMAL_SECOND
 78        else:
 79            raise _not_one_unit_error(steps=steps, seconds=seconds, normal_seconds=normal_seconds)
 80        object.__setattr__(self, "steps", counted_steps)
 81
 82    @classmethod
 83    def _from_steps(cls, steps: float) -> GameTime:
 84        """A time of `steps`, made without the constructor's check of its keywords."""
 85        new_time = object.__new__(cls)
 86        object.__setattr__(new_time, "steps", steps)
 87        return new_time
 88
 89    @property
 90    def seconds(self) -> float:
 91        """The seconds it counts at the Faster speed, unrounded."""
 92        return self.steps * SECONDS_PER_STEP
 93
 94    @property
 95    def normal_seconds(self) -> float:
 96        """The seconds it counts at the Normal speed, 16 steps a second. Exact, 16 being a power of two."""
 97        return self.steps / STEPS_PER_NORMAL_SECOND
 98
 99    @property
100    def nearest_step(self) -> int:
101        """The step nearest it, a tie the later, where Python's `round` takes the even one. Raises `ValueError` for
102        `INFINITE`, or any time not finite."""
103        try:
104            return rounded_half_up(self.steps)
105        except (OverflowError, ValueError):
106            raise ValueError(f"{self!r} is not finite, so it has no nearest step") from None
107
108    def is_integer(self) -> bool:
109        """Whether it is a whole number of steps."""
110        return float(self.steps).is_integer()
111
112    def to_string(self, decimals: int = 3) -> str:
113        """Minutes and seconds, the seconds to `decimals` places from 0 to 3, rounded down: `"3:20.000"` at step
114        4480, and `"3:20"` to 0 places. From 2 places up every step reads apart from the next, since a step is 44.6
115        milliseconds. A negative length reads `"-0:04.285"`, and a time not finite as Python writes its steps:
116        `"inf"` for `INFINITE`, `"-inf"`, or `"nan"`. Raises `ValueError` for `decimals` outside 0 to 3."""
117        if (
118            not isinstance(decimals, numbers.Integral)
119            or isinstance(decimals, bool)
120            or not 0 <= decimals <= _MOST_DECIMALS
121        ):
122            raise ValueError(f"decimals is a whole number from 0 to {_MOST_DECIMALS}, not {decimals!r}")
123        if not math.isfinite(self.steps):
124            return str(float(self.steps))
125        parts_per_second = 10**decimals
126        # One division, so a whole part of a second comes out whole and nothing is rounded up past one. From about
127        # 3.6e307 steps, a tenth as many for each decimal place, the product overflows a float, and is counted
128        # exactly in integers instead.
129        try:
130            parts = math.floor(abs(self.steps) * 5 * parts_per_second / _STEPS_PER_FIVE_SECONDS)
131        except OverflowError:
132            parts = math.floor(Fraction(float(abs(self.steps))) * 5 * parts_per_second / _STEPS_PER_FIVE_SECONDS)
133        minutes, parts_in_minute = divmod(parts, 60 * parts_per_second)
134        seconds, parts_in_second = divmod(parts_in_minute, parts_per_second)
135        sign = "-" if self.steps < 0 else ""
136        fraction = f".{parts_in_second:0{decimals}d}" if decimals else ""
137        return f"{sign}{minutes}:{seconds:02d}{fraction}"
138
139    def __eq__(self, other: object) -> bool:
140        if not isinstance(other, GameTime):
141            return NotImplemented
142        return self.steps == other.steps
143
144    def __hash__(self) -> int:
145        return hash(self.steps)
146
147    def __lt__(self, other: GameTime) -> bool:
148        if not isinstance(other, GameTime):
149            return NotImplemented
150        return self.steps < other.steps
151
152    def __le__(self, other: GameTime) -> bool:
153        if not isinstance(other, GameTime):
154            return NotImplemented
155        return self.steps <= other.steps
156
157    def __gt__(self, other: GameTime) -> bool:
158        if not isinstance(other, GameTime):
159            return NotImplemented
160        return self.steps > other.steps
161
162    def __ge__(self, other: GameTime) -> bool:
163        if not isinstance(other, GameTime):
164            return NotImplemented
165        return self.steps >= other.steps
166
167    def __bool__(self) -> bool:
168        return self.steps != 0
169
170    def __add__(self, other: GameTime) -> GameTime:
171        if not isinstance(other, GameTime):
172            return NotImplemented
173        return GameTime._from_steps(self.steps + other.steps)
174
175    def __sub__(self, other: GameTime) -> GameTime:
176        if not isinstance(other, GameTime):
177            return NotImplemented
178        return GameTime._from_steps(self.steps - other.steps)
179
180    def __mul__(self, factor: float) -> GameTime:
181        if not isinstance(factor, _SCALAR_TYPES):
182            return NotImplemented
183        return GameTime._from_steps(self.steps * factor)
184
185    __rmul__ = __mul__
186
187    @overload
188    def __truediv__(self, divisor: GameTime) -> float: ...
189
190    @overload
191    def __truediv__(self, divisor: float) -> GameTime: ...
192
193    def __truediv__(self, divisor: GameTime | float) -> GameTime | float:
194        if isinstance(divisor, GameTime):
195            return self.steps / divisor.steps
196        if not isinstance(divisor, _SCALAR_TYPES):
197            return NotImplemented
198        return GameTime._from_steps(self.steps / divisor)
199
200    def __floordiv__(self, divisor: GameTime) -> int:
201        if not isinstance(divisor, GameTime):
202            return NotImplemented
203        try:
204            return int(self.steps // divisor.steps)
205        except (OverflowError, ValueError):
206            raise ValueError(f"{self!r} // {divisor!r} is not a finite whole number") from None
207
208    def __mod__(self, divisor: GameTime) -> GameTime:
209        if not isinstance(divisor, GameTime):
210            return NotImplemented
211        return GameTime._from_steps(self.steps % divisor.steps)
212
213    def __neg__(self) -> GameTime:
214        return GameTime._from_steps(-self.steps)
215
216    def __abs__(self) -> GameTime:
217        return GameTime._from_steps(abs(self.steps))

A moment of a game, counted from its start, or a length of game time, in steps of the game: 22.4 make a second at the Faster speed games are played at.

Made from one of steps; seconds at the Faster speed; or normal_seconds at the Normal speed, 16 steps a second, in which the game gives some times, such as a weapon's cooldown. GameTime(seconds=120) is 2688 steps. Steps are kept as given. Seconds are multiplied out unrounded, exactly where they make a whole number of steps, so GameTime(seconds=45) == GameTime(steps=1008); normal seconds exactly, 16 being a power of two. Any other keyword, none, or more than one raises TypeError.

A moment is a whole number of steps; a length may be fractional, as a weapon's cooldown is. Two add, subtract and take % to a GameTime, and divide, / or //, to a plain number; one multiplies by a plain number and divides by one to a GameTime. It orders against another GameTime alone: compared with a plain number it raises TypeError, and it equals none. Zero is false, and is GameTime.ZERO; GameTime.INFINITE is later and longer than any other.

GameTime( *, steps: float | None = None, seconds: float | None = None, normal_seconds: float | None = None)
65    def __init__(
66        self, *, steps: float | None = None, seconds: float | None = None, normal_seconds: float | None = None
67    ) -> None:
68        if steps is not None:
69            if seconds is not None or normal_seconds is not None:
70                raise _not_one_unit_error(steps=steps, seconds=seconds, normal_seconds=normal_seconds)
71            counted_steps = steps
72        elif seconds is not None:
73            if normal_seconds is not None:
74                raise _not_one_unit_error(steps=steps, seconds=seconds, normal_seconds=normal_seconds)
75            counted_steps = seconds * _STEPS_PER_FIVE_SECONDS / 5
76        elif normal_seconds is not None:
77            counted_steps = normal_seconds * STEPS_PER_NORMAL_SECOND
78        else:
79            raise _not_one_unit_error(steps=steps, seconds=seconds, normal_seconds=normal_seconds)
80        object.__setattr__(self, "steps", counted_steps)
ZERO: ClassVar[GameTime] = GameTime(steps=0)

No time: the game's start, or a length of none.

INFINITE: ClassVar[GameTime] = GameTime(steps=inf)

The time of what never comes, later and longer than any other, as math.inf is a number larger than any. It orders above every finite time and stays infinite when one is added or subtracted, and seconds reads math.inf, and to_string "inf"; nearest_step and dividing it by // raise ValueError. Subtracting it from itself, multiplying it by zero or taking its remainder gives a time of NaN steps, which equals none.

steps: float

The steps of the game it counts.

seconds: float
89    @property
90    def seconds(self) -> float:
91        """The seconds it counts at the Faster speed, unrounded."""
92        return self.steps * SECONDS_PER_STEP

The seconds it counts at the Faster speed, unrounded.

normal_seconds: float
94    @property
95    def normal_seconds(self) -> float:
96        """The seconds it counts at the Normal speed, 16 steps a second. Exact, 16 being a power of two."""
97        return self.steps / STEPS_PER_NORMAL_SECOND

The seconds it counts at the Normal speed, 16 steps a second. Exact, 16 being a power of two.

nearest_step: int
 99    @property
100    def nearest_step(self) -> int:
101        """The step nearest it, a tie the later, where Python's `round` takes the even one. Raises `ValueError` for
102        `INFINITE`, or any time not finite."""
103        try:
104            return rounded_half_up(self.steps)
105        except (OverflowError, ValueError):
106            raise ValueError(f"{self!r} is not finite, so it has no nearest step") from None

The step nearest it, a tie the later, where Python's round takes the even one. Raises ValueError for INFINITE, or any time not finite.

def is_integer(self) -> bool:
108    def is_integer(self) -> bool:
109        """Whether it is a whole number of steps."""
110        return float(self.steps).is_integer()

Whether it is a whole number of steps.

def to_string(self, decimals: int = 3) -> str:
112    def to_string(self, decimals: int = 3) -> str:
113        """Minutes and seconds, the seconds to `decimals` places from 0 to 3, rounded down: `"3:20.000"` at step
114        4480, and `"3:20"` to 0 places. From 2 places up every step reads apart from the next, since a step is 44.6
115        milliseconds. A negative length reads `"-0:04.285"`, and a time not finite as Python writes its steps:
116        `"inf"` for `INFINITE`, `"-inf"`, or `"nan"`. Raises `ValueError` for `decimals` outside 0 to 3."""
117        if (
118            not isinstance(decimals, numbers.Integral)
119            or isinstance(decimals, bool)
120            or not 0 <= decimals <= _MOST_DECIMALS
121        ):
122            raise ValueError(f"decimals is a whole number from 0 to {_MOST_DECIMALS}, not {decimals!r}")
123        if not math.isfinite(self.steps):
124            return str(float(self.steps))
125        parts_per_second = 10**decimals
126        # One division, so a whole part of a second comes out whole and nothing is rounded up past one. From about
127        # 3.6e307 steps, a tenth as many for each decimal place, the product overflows a float, and is counted
128        # exactly in integers instead.
129        try:
130            parts = math.floor(abs(self.steps) * 5 * parts_per_second / _STEPS_PER_FIVE_SECONDS)
131        except OverflowError:
132            parts = math.floor(Fraction(float(abs(self.steps))) * 5 * parts_per_second / _STEPS_PER_FIVE_SECONDS)
133        minutes, parts_in_minute = divmod(parts, 60 * parts_per_second)
134        seconds, parts_in_second = divmod(parts_in_minute, parts_per_second)
135        sign = "-" if self.steps < 0 else ""
136        fraction = f".{parts_in_second:0{decimals}d}" if decimals else ""
137        return f"{sign}{minutes}:{seconds:02d}{fraction}"

Minutes and seconds, the seconds to decimals places from 0 to 3, rounded down: "3:20.000" at step 4480, and "3:20" to 0 places. From 2 places up every step reads apart from the next, since a step is 44.6 milliseconds. A negative length reads "-0:04.285", and a time not finite as Python writes its steps: "inf" for INFINITE, "-inf", or "nan". Raises ValueError for decimals outside 0 to 3.

@final
class TimeSeries(typing.Generic[T]):
 23@final
 24class TimeSeries[T: float]:
 25    """Values recorded against the game time they were observed at, one a step.
 26
 27    Indexing and slicing are by `GameTime`, not buffer position, so `series[time]` means the same thing for the whole
 28    life of the series. A time between two steps reads the nearest, a tie the later: `series.at(api.time -
 29    GameTime(seconds=1))` reads 22 steps back. A slice is a copy, sharing no memory with the series. Steps are
 30    contiguous: a gap between appends is filled by linear interpolation, rounded to the nearest whole number in an
 31    integer series, a tie up.
 32    """
 33
 34    # Makes a numpy scalar on the left, `numpy.float64(2) * series`, hand over to the reflected operator instead of
 35    # reading the series as an array of its (step, value) pairs.
 36    __array_ufunc__ = None
 37
 38    _buffer: ndarray
 39    _start: int | None
 40    _size: int
 41
 42    def __init__(self, buffer: ndarray, start_time: GameTime | None, size: int) -> None:
 43        """A series over `buffer`, holding the `size` values recorded one a step from `start_time` onward, a whole
 44        number of steps.
 45
 46        `buffer` may be longer than `size`, leaving room to append. An empty series has no start; the first append
 47        sets it. Raises `TypeError` for a `start_time` that is not a `GameTime`, and `ValueError` for one that is not
 48        a whole number of steps.
 49        """
 50        self._set_up(buffer, None if start_time is None else _whole_step_of(start_time, "start_time"), size)
 51
 52    @classmethod
 53    def _from_steps(cls, buffer: ndarray, start: int | None, size: int) -> TimeSeries[T]:
 54        """A series over `buffer` from step `start`, made without a `GameTime`, for the operations that make one."""
 55        series = cls.__new__(cls)
 56        series._set_up(buffer, start, size)
 57        return series
 58
 59    def _set_up(self, buffer: ndarray, start: int | None, size: int) -> None:
 60        """Hold the `size` values of `buffer` from step `start`, once they are checked."""
 61        if not len(buffer):
 62            raise ValueError("buffer must not be empty; a series needs room to record at least one value")
 63        if size < 0:
 64            raise ValueError(f"size must not be negative, got {size}")
 65        if size > len(buffer):
 66            raise ValueError(f"buffer of {len(buffer)} is too small for {size} values")
 67        if size and start is None:
 68            raise ValueError(f"a series of {size} values needs a start time")
 69        self._buffer = buffer
 70        self._start = start if size else None
 71        self._size = size
 72
 73    @classmethod
 74    def empty(cls, dtype: type[T], *, initial_size: int = INITIAL_BUFFER) -> TimeSeries[T]:
 75        """An empty series; the time of the first append becomes its start."""
 76        return cls._from_steps(numpy.zeros(initial_size, dtype=dtype), None, 0)
 77
 78    def _empty_like(self) -> TimeSeries[T]:
 79        """An empty series of the same type, for an operation whose result holds no values."""
 80        return TimeSeries._from_steps(numpy.zeros(INITIAL_BUFFER, dtype=self.dtype), None, 0)
 81
 82    @property
 83    def size(self) -> int:
 84        """The number of recorded steps."""
 85        return self._size
 86
 87    @property
 88    def start_time(self) -> GameTime:
 89        """The time of the first recorded step. An empty series has none, and raises `ValueError`."""
 90        return GameTime(steps=self._first_step)
 91
 92    @property
 93    def last_time(self) -> GameTime:
 94        """The time of the most recently recorded step. An empty series has none, and raises `ValueError`."""
 95        return GameTime(steps=self._last_step)
 96
 97    @property
 98    def _first_step(self) -> int:
 99        """The first recorded step; an empty series has none."""
100        if self._start is None:
101            raise ValueError("an empty series has no start step")
102        return self._start
103
104    @property
105    def _last_step(self) -> int:
106        """The most recently recorded step; an empty series has none."""
107        return self._first_step + self._size - 1
108
109    @property
110    def last_value(self) -> T:
111        """The value at the most recently recorded step; an empty series has none."""
112        if self._start is None:
113            raise ValueError("an empty series has no last value")
114        return self._buffer.item(self._size - 1)
115
116    @property
117    def values(self) -> ndarray:
118        """The recorded values, as a view of the underlying array."""
119        return self._buffer[: self._size]
120
121    @property
122    def dtype(self) -> numpy.dtype:
123        """The type of the recorded values."""
124        return self._buffer.dtype
125
126    def __len__(self) -> int:
127        return self._size
128
129    def __iter__(self) -> Iterator[tuple[GameTime, T]]:
130        """Each recorded step's time and value, in order."""
131        for step, value in enumerate(self.values.tolist(), start=self._start or 0):
132            yield GameTime(steps=step), value
133
134    def append(self, time: GameTime, value: T) -> None:
135        """Record `value` at `time`, interpolating linearly across any gap since the last recorded step. Raises
136        `TypeError` for a `time` that is not a `GameTime`, and `ValueError` for one that is not a whole number of
137        steps, or is not after the last recorded."""
138        step = _whole_step_of(time, "time")
139        if self._size == 0:
140            self._start = step
141            self._buffer[0] = value
142            self._size = 1
143            return
144        if step <= self._last_step:
145            raise ValueError(f"step {step} is not after the last recorded step {self._last_step}")
146
147        index = step - self._first_step
148        if index >= self._buffer.size:
149            grown = numpy.zeros(2 * index, dtype=self._buffer.dtype)
150            grown[: self._size] = self.values
151            self._buffer = grown
152
153        gap = step - self._last_step
154        if gap == 1:
155            self._buffer[index] = value
156        else:
157            interpolated = numpy.linspace(self._buffer[index - gap], value, num=gap + 1)
158            if numpy.issubdtype(self._buffer.dtype, numpy.integer):
159                # A tie up, as `GameTime.nearest_step` has it; `numpy.rint` would send it to the even value.
160                floored = numpy.floor(interpolated)
161                interpolated = floored + (interpolated - floored >= 0.5)
162            self._buffer[index - gap + 1 : index + 1] = interpolated[1:]
163        self._size += gap
164
165    def at(self, time: GameTime) -> T | None:
166        """The value at `time`, taken from the nearest step, a tie the later, or `None` if that step was never
167        recorded. Raises `TypeError` for a `time` that is not a `GameTime`, and `ValueError` for one not finite,
168        such as `GameTime.INFINITE`."""
169        step = _nearest_step_of(time, "time")
170        if self._start is None:
171            return None
172        index = step - self._start
173        if not 0 <= index < self._size:
174            return None
175        return self._buffer.item(index)
176
177    def _index(self, step: int) -> int:
178        """The buffer position of a recorded step."""
179        if self._start is None:
180            raise IndexError(f"step {step} is outside an empty series")
181        index = step - self._start
182        if not 0 <= index < self._size:
183            raise IndexError(f"step {step} outside the recorded range {self._start}-{self._last_step}")
184        return index
185
186    def _slice(self, item: slice) -> tuple[slice, int | None]:
187        """A range of times as a range of buffer positions, none in an empty series, and the step it starts at, or
188        `None` from the start."""
189        if item.step is not None:
190            raise NotImplementedError("TimeSeries does not support strided slicing")
191        start_step = None if item.start is None else _nearest_step_of(item.start, "a slice's start")
192        stop_step = None if item.stop is None else _nearest_step_of(item.stop, "a slice's stop")
193        if self._start is None:
194            return slice(0, 0), start_step
195        start = 0 if start_step is None else start_step - self._start
196        stop = self._size if stop_step is None else stop_step - self._start
197        if start < 0 or stop < 0:
198            raise IndexError(f"steps {start_step}:{stop_step} begin before the first recorded step {self._start}")
199        return slice(start, stop), start_step
200
201    @overload
202    def __getitem__(self, item: GameTime) -> T: ...
203
204    @overload
205    def __getitem__(self, item: slice) -> TimeSeries[T]: ...
206
207    def __getitem__(self, item: GameTime | slice) -> T | TimeSeries[T]:
208        """The value at a time, or a copy of the series over a range of times, each read at the nearest step, a tie
209        the later. Raises `IndexError` for a step not recorded, or a range that begins before the first;
210        `TypeError` for anything but a `GameTime` or a slice of them; and `ValueError` for a time not finite, such as
211        `GameTime.INFINITE`."""
212        if isinstance(item, slice):
213            positions, start_step = self._slice(item)
214            values = self.values[positions]
215            if not len(values):
216                return self._empty_like()
217            start = self._start if start_step is None else start_step
218            return TimeSeries._from_steps(values.copy(), start, len(values))
219        return self._buffer.item(self._index(_nearest_step_of(item, "an index")))
220
221    def __setitem__(self, item: GameTime | slice, value: T | ndarray) -> None:
222        if isinstance(item, slice):
223            self.values[self._slice(item)[0]] = value
224        else:
225            self.values[self._index(_nearest_step_of(item, "an index"))] = value
226
227    def min(self) -> T:
228        """The smallest recorded value."""
229        return self.values.min().item()
230
231    def max(self) -> T:
232        """The largest recorded value."""
233        return self.values.max().item()
234
235    def sum(self) -> T:
236        """The sum of the recorded values."""
237        return self.values.sum().item()
238
239    def mean(self) -> float:
240        """The mean of the recorded values. A float even for an integer series."""
241        return self.values.mean().item()
242
243    def std(self) -> float:
244        """The standard deviation of the recorded values. A float even for an integer series."""
245        return self.values.std().item()
246
247    def derivative_at(self, time: GameTime, *, window: GameTime = GameTime(steps=100)) -> float | None:
248        """The rate of change per second over the `window` ending at `time`, each rounded to the nearest whole step, a
249        tie up.
250
251        `None` if the series does not cover the whole range. Raises `TypeError` for a `time` or a `window` that is not
252        a `GameTime`, and `ValueError` for a window under one step once rounded, or either not finite.
253        """
254        step = _nearest_step_of(time, "time")
255        check_game_time(window, "window")
256        window_steps = window.nearest_step
257        if window_steps <= 0:
258            raise ValueError(f"a window is at least one step, not {window!r}")
259        if self._start is None:
260            return None
261        start = step - window_steps
262        if not (self._start <= start and step <= self._last_step):
263            return None
264        low = self._buffer.item(start - self._start)
265        high = self._buffer.item(step - self._start)
266        return (high - low) / GameTime(steps=window_steps).seconds
267
268    def gaussian_filter(self, *, sigma: GameTime, mode: str = "nearest") -> TimeSeries[float]:
269        """A copy with a Gaussian filter of standard deviation `sigma` applied along the series. Raises `TypeError` for
270        a `sigma` that is not a `GameTime`."""
271        check_game_time(sigma, "sigma")
272        if not self._size:
273            return TimeSeries.empty(float)
274        filtered = scipy.ndimage.gaussian_filter1d(self.values.astype(float), sigma=sigma.steps, mode=mode)
275        return TimeSeries._from_steps(filtered, self._start, self._size)
276
277    def uniform_filter(self, *, size: GameTime, mode: str = "nearest") -> TimeSeries[float]:
278        """A copy with a moving average over `size` applied along the series. Raises `TypeError` for a `size` that is
279        not a `GameTime`, and `ValueError` for one that is not a whole number of steps, at least 1."""
280        check_game_time(size, "size")
281        if not size.is_integer() or size.steps < 1:
282            raise ValueError(f"a moving average is over a whole number of steps, at least 1, not {size!r}")
283        if not self._size:
284            return TimeSeries.empty(float)
285        filtered = scipy.ndimage.uniform_filter(self.values.astype(float), size=int(size.steps), mode=mode)
286        return TimeSeries._from_steps(filtered, self._start, self._size)
287
288    def copy(self) -> TimeSeries[T]:
289        """An independent copy, sharing no memory with this series."""
290        if not self._size:
291            return self._empty_like()
292        return TimeSeries._from_steps(self.values.copy(), self._start, self._size)
293
294    def _combine(self, other: TimeSeries[T] | T, op: Callable[[ndarray, ndarray | T], ndarray]) -> TimeSeries[T]:
295        """`op` applied with a scalar, or with another series over the steps both record."""
296        if not isinstance(other, TimeSeries):
297            if self._start is None:
298                return self._empty_like()
299            return TimeSeries._from_steps(op(self.values, other), self._start, self._size)
300        if self._start is None or other._start is None:
301            return self._empty_like()
302        start = max(self._start, other._start)
303        size = min(self._last_step, other._last_step) - start + 1
304        if size <= 0:
305            return self._empty_like()
306        mine = self._buffer[start - self._start : start - self._start + size]
307        theirs = other._buffer[start - other._start : start - other._start + size]
308        return TimeSeries._from_steps(op(mine, theirs), start, size)
309
310    def __add__(self, other: TimeSeries[T] | T) -> TimeSeries[T]:
311        if not isinstance(other, OPERAND_TYPES):
312            return NotImplemented
313        return self._combine(other, numpy.add)
314
315    def __sub__(self, other: TimeSeries[T] | T) -> TimeSeries[T]:
316        if not isinstance(other, OPERAND_TYPES):
317            return NotImplemented
318        return self._combine(other, numpy.subtract)
319
320    def __mul__(self, other: TimeSeries[T] | T) -> TimeSeries[T]:
321        if not isinstance(other, OPERAND_TYPES):
322            return NotImplemented
323        return self._combine(other, numpy.multiply)
324
325    __radd__ = __add__
326    __rmul__ = __mul__
327
328    def __rsub__(self, other: T) -> TimeSeries[T]:
329        if not isinstance(other, SCALAR_TYPES):
330            return NotImplemented
331        return self._combine(other, lambda values, scalar: numpy.subtract(scalar, values))
332
333    def __repr__(self) -> str:
334        if self._size == 0:
335            return f"{type(self).__name__}(empty, dtype={self.dtype})"
336        return f"{type(self).__name__}(steps {self._start}-{self._last_step}, dtype={self.dtype})"

Values recorded against the game time they were observed at, one a step.

Indexing and slicing are by GameTime, not buffer position, so series[time] means the same thing for the whole life of the series. A time between two steps reads the nearest, a tie the later: series.at(api.time - GameTime(seconds=1)) reads 22 steps back. A slice is a copy, sharing no memory with the series. Steps are contiguous: a gap between appends is filled by linear interpolation, rounded to the nearest whole number in an integer series, a tie up.

TimeSeries( buffer: numpy.ndarray, start_time: GameTime | None, size: int)
42    def __init__(self, buffer: ndarray, start_time: GameTime | None, size: int) -> None:
43        """A series over `buffer`, holding the `size` values recorded one a step from `start_time` onward, a whole
44        number of steps.
45
46        `buffer` may be longer than `size`, leaving room to append. An empty series has no start; the first append
47        sets it. Raises `TypeError` for a `start_time` that is not a `GameTime`, and `ValueError` for one that is not
48        a whole number of steps.
49        """
50        self._set_up(buffer, None if start_time is None else _whole_step_of(start_time, "start_time"), size)

A series over buffer, holding the size values recorded one a step from start_time onward, a whole number of steps.

buffer may be longer than size, leaving room to append. An empty series has no start; the first append sets it. Raises TypeError for a start_time that is not a GameTime, and ValueError for one that is not a whole number of steps.

@classmethod
def empty(cls, dtype: 'type[T]', *, initial_size: int = 128) -> 'TimeSeries[T]':
73    @classmethod
74    def empty(cls, dtype: type[T], *, initial_size: int = INITIAL_BUFFER) -> TimeSeries[T]:
75        """An empty series; the time of the first append becomes its start."""
76        return cls._from_steps(numpy.zeros(initial_size, dtype=dtype), None, 0)

An empty series; the time of the first append becomes its start.

size: int
82    @property
83    def size(self) -> int:
84        """The number of recorded steps."""
85        return self._size

The number of recorded steps.

start_time: GameTime
87    @property
88    def start_time(self) -> GameTime:
89        """The time of the first recorded step. An empty series has none, and raises `ValueError`."""
90        return GameTime(steps=self._first_step)

The time of the first recorded step. An empty series has none, and raises ValueError.

last_time: GameTime
92    @property
93    def last_time(self) -> GameTime:
94        """The time of the most recently recorded step. An empty series has none, and raises `ValueError`."""
95        return GameTime(steps=self._last_step)

The time of the most recently recorded step. An empty series has none, and raises ValueError.

last_value: 'T'
109    @property
110    def last_value(self) -> T:
111        """The value at the most recently recorded step; an empty series has none."""
112        if self._start is None:
113            raise ValueError("an empty series has no last value")
114        return self._buffer.item(self._size - 1)

The value at the most recently recorded step; an empty series has none.

values: numpy.ndarray
116    @property
117    def values(self) -> ndarray:
118        """The recorded values, as a view of the underlying array."""
119        return self._buffer[: self._size]

The recorded values, as a view of the underlying array.

dtype: numpy.dtype
121    @property
122    def dtype(self) -> numpy.dtype:
123        """The type of the recorded values."""
124        return self._buffer.dtype

The type of the recorded values.

def append(self, time: GameTime, value: 'T') -> None:
134    def append(self, time: GameTime, value: T) -> None:
135        """Record `value` at `time`, interpolating linearly across any gap since the last recorded step. Raises
136        `TypeError` for a `time` that is not a `GameTime`, and `ValueError` for one that is not a whole number of
137        steps, or is not after the last recorded."""
138        step = _whole_step_of(time, "time")
139        if self._size == 0:
140            self._start = step
141            self._buffer[0] = value
142            self._size = 1
143            return
144        if step <= self._last_step:
145            raise ValueError(f"step {step} is not after the last recorded step {self._last_step}")
146
147        index = step - self._first_step
148        if index >= self._buffer.size:
149            grown = numpy.zeros(2 * index, dtype=self._buffer.dtype)
150            grown[: self._size] = self.values
151            self._buffer = grown
152
153        gap = step - self._last_step
154        if gap == 1:
155            self._buffer[index] = value
156        else:
157            interpolated = numpy.linspace(self._buffer[index - gap], value, num=gap + 1)
158            if numpy.issubdtype(self._buffer.dtype, numpy.integer):
159                # A tie up, as `GameTime.nearest_step` has it; `numpy.rint` would send it to the even value.
160                floored = numpy.floor(interpolated)
161                interpolated = floored + (interpolated - floored >= 0.5)
162            self._buffer[index - gap + 1 : index + 1] = interpolated[1:]
163        self._size += gap

Record value at time, interpolating linearly across any gap since the last recorded step. Raises TypeError for a time that is not a GameTime, and ValueError for one that is not a whole number of steps, or is not after the last recorded.

def at(self, time: GameTime) -> 'T | None':
165    def at(self, time: GameTime) -> T | None:
166        """The value at `time`, taken from the nearest step, a tie the later, or `None` if that step was never
167        recorded. Raises `TypeError` for a `time` that is not a `GameTime`, and `ValueError` for one not finite,
168        such as `GameTime.INFINITE`."""
169        step = _nearest_step_of(time, "time")
170        if self._start is None:
171            return None
172        index = step - self._start
173        if not 0 <= index < self._size:
174            return None
175        return self._buffer.item(index)

The value at time, taken from the nearest step, a tie the later, or None if that step was never recorded. Raises TypeError for a time that is not a GameTime, and ValueError for one not finite, such as GameTime.INFINITE.

def min(self) -> 'T':
227    def min(self) -> T:
228        """The smallest recorded value."""
229        return self.values.min().item()

The smallest recorded value.

def max(self) -> 'T':
231    def max(self) -> T:
232        """The largest recorded value."""
233        return self.values.max().item()

The largest recorded value.

def sum(self) -> 'T':
235    def sum(self) -> T:
236        """The sum of the recorded values."""
237        return self.values.sum().item()

The sum of the recorded values.

def mean(self) -> float:
239    def mean(self) -> float:
240        """The mean of the recorded values. A float even for an integer series."""
241        return self.values.mean().item()

The mean of the recorded values. A float even for an integer series.

def std(self) -> float:
243    def std(self) -> float:
244        """The standard deviation of the recorded values. A float even for an integer series."""
245        return self.values.std().item()

The standard deviation of the recorded values. A float even for an integer series.

def derivative_at( self, time: GameTime, *, window: GameTime = GameTime(steps=100)) -> float | None:
247    def derivative_at(self, time: GameTime, *, window: GameTime = GameTime(steps=100)) -> float | None:
248        """The rate of change per second over the `window` ending at `time`, each rounded to the nearest whole step, a
249        tie up.
250
251        `None` if the series does not cover the whole range. Raises `TypeError` for a `time` or a `window` that is not
252        a `GameTime`, and `ValueError` for a window under one step once rounded, or either not finite.
253        """
254        step = _nearest_step_of(time, "time")
255        check_game_time(window, "window")
256        window_steps = window.nearest_step
257        if window_steps <= 0:
258            raise ValueError(f"a window is at least one step, not {window!r}")
259        if self._start is None:
260            return None
261        start = step - window_steps
262        if not (self._start <= start and step <= self._last_step):
263            return None
264        low = self._buffer.item(start - self._start)
265        high = self._buffer.item(step - self._start)
266        return (high - low) / GameTime(steps=window_steps).seconds

The rate of change per second over the window ending at time, each rounded to the nearest whole step, a tie up.

None if the series does not cover the whole range. Raises TypeError for a time or a window that is not a GameTime, and ValueError for a window under one step once rounded, or either not finite.

def gaussian_filter( self, *, sigma: GameTime, mode: str = 'nearest') -> TimeSeries[float]:
268    def gaussian_filter(self, *, sigma: GameTime, mode: str = "nearest") -> TimeSeries[float]:
269        """A copy with a Gaussian filter of standard deviation `sigma` applied along the series. Raises `TypeError` for
270        a `sigma` that is not a `GameTime`."""
271        check_game_time(sigma, "sigma")
272        if not self._size:
273            return TimeSeries.empty(float)
274        filtered = scipy.ndimage.gaussian_filter1d(self.values.astype(float), sigma=sigma.steps, mode=mode)
275        return TimeSeries._from_steps(filtered, self._start, self._size)

A copy with a Gaussian filter of standard deviation sigma applied along the series. Raises TypeError for a sigma that is not a GameTime.

def uniform_filter( self, *, size: GameTime, mode: str = 'nearest') -> TimeSeries[float]:
277    def uniform_filter(self, *, size: GameTime, mode: str = "nearest") -> TimeSeries[float]:
278        """A copy with a moving average over `size` applied along the series. Raises `TypeError` for a `size` that is
279        not a `GameTime`, and `ValueError` for one that is not a whole number of steps, at least 1."""
280        check_game_time(size, "size")
281        if not size.is_integer() or size.steps < 1:
282            raise ValueError(f"a moving average is over a whole number of steps, at least 1, not {size!r}")
283        if not self._size:
284            return TimeSeries.empty(float)
285        filtered = scipy.ndimage.uniform_filter(self.values.astype(float), size=int(size.steps), mode=mode)
286        return TimeSeries._from_steps(filtered, self._start, self._size)

A copy with a moving average over size applied along the series. Raises TypeError for a size that is not a GameTime, and ValueError for one that is not a whole number of steps, at least 1.

def copy(self) -> 'TimeSeries[T]':
288    def copy(self) -> TimeSeries[T]:
289        """An independent copy, sharing no memory with this series."""
290        if not self._size:
291            return self._empty_like()
292        return TimeSeries._from_steps(self.values.copy(), self._start, self._size)

An independent copy, sharing no memory with this series.