|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import bisect |
| 4 | +from math import ceil |
| 5 | +from time import monotonic |
| 6 | + |
| 7 | +import rich.repr |
| 8 | + |
| 9 | + |
| 10 | +@rich.repr.auto(angular=True) |
| 11 | +class ETA: |
| 12 | + """Calculate speed and estimate time to arrival.""" |
| 13 | + |
| 14 | + def __init__( |
| 15 | + self, estimation_period: float = 60, extrapolate_period: float = 30 |
| 16 | + ) -> None: |
| 17 | + """Create an ETA. |
| 18 | +
|
| 19 | + Args: |
| 20 | + estimation_period: Period in seconds, used to calculate speed. |
| 21 | + extrapolate_period: Maximum number of seconds used to estimate progress after last sample. |
| 22 | + """ |
| 23 | + self.estimation_period = estimation_period |
| 24 | + self.max_extrapolate = extrapolate_period |
| 25 | + self._samples: list[tuple[float, float]] = [(0.0, 0.0)] |
| 26 | + self._add_count = 0 |
| 27 | + |
| 28 | + def __rich_repr__(self) -> rich.repr.Result: |
| 29 | + yield "speed", self.speed |
| 30 | + yield "eta", self.get_eta(monotonic()) |
| 31 | + |
| 32 | + @property |
| 33 | + def first_sample(self) -> tuple[float, float]: |
| 34 | + """First sample.""" |
| 35 | + assert self._samples, "Assumes samples not empty" |
| 36 | + return self._samples[0] |
| 37 | + |
| 38 | + @property |
| 39 | + def last_sample(self) -> tuple[float, float]: |
| 40 | + """Last sample.""" |
| 41 | + assert self._samples, "Assumes samples not empty" |
| 42 | + return self._samples[-1] |
| 43 | + |
| 44 | + def reset(self) -> None: |
| 45 | + """Start ETA calculations from current time.""" |
| 46 | + del self._samples[:] |
| 47 | + |
| 48 | + def add_sample(self, time: float, progress: float) -> None: |
| 49 | + """Add a new sample. |
| 50 | +
|
| 51 | + Args: |
| 52 | + time: Time when sample occurred. |
| 53 | + progress: Progress ratio (0 is start, 1 is complete). |
| 54 | + """ |
| 55 | + if self._samples and self.last_sample[1] > progress: |
| 56 | + # If progress goes backwards, we need to reset calculations |
| 57 | + self.reset() |
| 58 | + self._samples.append((time, progress)) |
| 59 | + self._add_count += 1 |
| 60 | + if self._add_count % 100 == 0: |
| 61 | + # Prune periodically so we don't accumulate vast amounts of samples |
| 62 | + self._prune() |
| 63 | + |
| 64 | + def _prune(self) -> None: |
| 65 | + """Prune old samples.""" |
| 66 | + if len(self._samples) <= 10: |
| 67 | + # Keep at least 10 samples |
| 68 | + return |
| 69 | + prune_time = self._samples[-1][0] - self.estimation_period |
| 70 | + index = bisect.bisect_left(self._samples, (prune_time, 0)) |
| 71 | + del self._samples[:index] |
| 72 | + |
| 73 | + def _get_progress_at(self, time: float) -> tuple[float, float]: |
| 74 | + """Get the progress at a specific time.""" |
| 75 | + |
| 76 | + index = bisect.bisect_left(self._samples, (time, 0)) |
| 77 | + if index >= len(self._samples): |
| 78 | + return self.last_sample |
| 79 | + if index == 0: |
| 80 | + return self.first_sample |
| 81 | + # Linearly interpolate progress between two samples |
| 82 | + time1, progress1 = self._samples[index - 1] |
| 83 | + time2, progress2 = self._samples[index] |
| 84 | + factor = (time - time1) / (time2 - time1) |
| 85 | + intermediate_progress = progress1 + (progress2 - progress1) * factor |
| 86 | + return time, intermediate_progress |
| 87 | + |
| 88 | + @property |
| 89 | + def speed(self) -> float | None: |
| 90 | + """The current speed, or `None` if it couldn't be calculated.""" |
| 91 | + |
| 92 | + if len(self._samples) < 2: |
| 93 | + # Need at least 2 samples to calculate speed |
| 94 | + return None |
| 95 | + |
| 96 | + recent_sample_time, progress2 = self.last_sample |
| 97 | + progress_start_time, progress1 = self._get_progress_at( |
| 98 | + recent_sample_time - self.estimation_period |
| 99 | + ) |
| 100 | + time_delta = recent_sample_time - progress_start_time |
| 101 | + distance = progress2 - progress1 |
| 102 | + speed = distance / time_delta if time_delta else 0 |
| 103 | + return speed |
| 104 | + |
| 105 | + def get_eta(self, time: float) -> int | None: |
| 106 | + """Estimated seconds until completion, or `None` if no estimate can be made. |
| 107 | +
|
| 108 | + Args: |
| 109 | + time: Current time. |
| 110 | + """ |
| 111 | + speed = self.speed |
| 112 | + if not speed: |
| 113 | + # Not enough samples to guess |
| 114 | + return None |
| 115 | + recent_time, recent_progress = self.last_sample |
| 116 | + remaining = 1.0 - recent_progress |
| 117 | + if remaining <= 0: |
| 118 | + # Complete |
| 119 | + return 0 |
| 120 | + # The bar is not complete, so we will extrapolate progress |
| 121 | + # This will give us a countdown, even with no samples |
| 122 | + time_since_sample = min(self.max_extrapolate, time - recent_time) |
| 123 | + extrapolate_progress = speed * time_since_sample |
| 124 | + # We don't want to extrapolate all the way to 0, as that would erroneously suggest it is finished |
| 125 | + eta = max(1.0, (remaining - extrapolate_progress) / speed) |
| 126 | + return ceil(eta) |
0 commit comments