Coverage for src/python/ensembl/vep/runner/run/progress.py: 100%
67 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Interactive variant progress reporting."""
16from __future__ import annotations
18import sys
19from time import monotonic
20from typing import TextIO
22from attrs import define, field
24__all__ = ["VariantProgress"]
27def _format_duration(seconds: int) -> str:
28 """Format a duration as hours, minutes, and seconds."""
29 hours, remainder = divmod(seconds, 3600)
30 minutes, remaining_seconds = divmod(remainder, 60)
31 return f"{hours:02d}:{minutes:02d}:{remaining_seconds:02d}"
34@define(kw_only=True, auto_attribs=True)
35class VariantProgress:
36 """Progress renderer for completed input variants.
38 Attributes:
39 total (int | None): Number of input variant records, or None when the input declares no
40 count. Without one there is nothing to measure against, so the line shows what has
41 been annotated so far and leaves out the bar, the percentage and the ETA.
42 enabled (bool): Whether updates should be rendered.
43 stream (TextIO): Interactive output stream.
44 width (int): Character width of the progress bar.
45 """
47 total: int | None
48 enabled: bool = True
49 stream: TextIO = field(factory=lambda: sys.stderr)
50 width: int = 24
51 _completed: int = field(default=0, init=False)
52 _started_at: float = field(init=False)
53 _rendered_width: int = field(default=0, init=False)
55 def __attrs_post_init__(self) -> None:
56 if self.total is not None and self.total < 0:
57 raise ValueError("progress total must not be negative")
58 if self.width < 1:
59 raise ValueError("progress width must be positive")
60 self._started_at = monotonic()
62 def __enter__(self) -> VariantProgress:
63 if self.enabled:
64 self._render()
65 return self
67 def __exit__(self, *_error: object) -> None:
68 if self.enabled:
69 self.stream.write("\n")
70 self.stream.flush()
72 def advance(self, variants: int) -> None:
73 """Advance by a non-negative number of completed variants."""
74 if variants < 0:
75 raise ValueError("progress increment must not be negative")
76 completed = self._completed + variants
77 self._completed = completed if self.total is None else min(self.total, completed)
78 if self.enabled:
79 self._render()
81 def _render(self) -> None:
82 """Redraw the current variant count."""
83 elapsed_seconds = max(0.0, monotonic() - self._started_at)
84 rate = self._completed / elapsed_seconds if elapsed_seconds > 0 else 0.0
86 if self.total is None:
87 line = self._unsized_line(rate, elapsed_seconds)
88 else:
89 line = self._sized_line(self.total, rate, elapsed_seconds)
91 padding = " " * max(0, self._rendered_width - len(line))
92 self.stream.write(f"\r{line}{padding}")
93 self.stream.flush()
94 self._rendered_width = len(line)
96 def _sized_line(self, total: int, rate: float, elapsed_seconds: float) -> str:
97 """Return the progress line for an input whose record count is known."""
98 percentage = 100 if total == 0 else int(100 * self._completed / total)
99 filled = self.width if total == 0 else int(self.width * self._completed / total + 0.5)
100 progress_bar = "█" * filled + "░" * (self.width - filled)
102 if total in (0, self._completed):
103 eta = "00:00:00"
104 elapsed = "00:00:00"
105 elif rate == 0:
106 eta = "--:--:--"
107 elapsed = "--:--:--"
108 else:
109 remaining_seconds = int((total - self._completed) / rate + 0.5)
110 eta = _format_duration(remaining_seconds)
111 elapsed = _format_duration(int(elapsed_seconds + 0.5))
113 return (
114 f"Annotating variants: [{progress_bar}] {percentage}% | "
115 f"{self._completed:,}/{total:,} | {int(rate + 0.5):,} variants/s | {elapsed}>{eta}"
116 )
118 def _unsized_line(self, rate: float, elapsed_seconds: float) -> str:
119 """Return the progress line for an input that declares no record count.
121 No total means no fraction of it, so the bar, the percentage and the ETA are all left
122 out rather than drawn against a guess.
123 """
124 elapsed = _format_duration(int(elapsed_seconds + 0.5))
126 return f"Annotating variants: {self._completed:,} | {int(rate + 0.5):,} variants/s | {elapsed}"