Coverage for src/manimgx/mobjects/numbers.py: 99%

165 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-10-26 05:52 +0000

1# SPDX-FileCopyrightText: 2026 Academa, Inc. 

2# SPDX-FileCopyrightText: 2024 the Manim Community Developers 

3# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC 

4# SPDX-License-Identifier: MIT 

5 

6"""Ported from Manim CE 0.21 (MIT).""" 

7 

8from __future__ import annotations 

9 

10__all__ = ["DecimalNumber", "Integer", "Variable", "index_labels"] 

11from typing import ClassVar, Self, Unpack 

12 

13import numpy as np 

14 

15from manimgx.caches import Memo 

16from manimgx.constants import DEFAULT_FONT_SIZE, DOWN, LEFT, ORIGIN, RIGHT, UP 

17from manimgx.drawing.geometry import Blend 

18from manimgx.drawing.paint import BLACK, Paint, Style, _Style 

19from manimgx.mobject import Mobject, ValueTracker, VGroup, VMobject, copied, prototype 

20from manimgx.mobjects.text import MathTex, SingleStringMathTex, Text 

21from manimgx.typing import ManimTextLabel, Vector3DLike 

22 

23# a string's glyphs laid out (CE's procedure, run once per string and layout): what laying out 

24# sets on the number, copied in by every later layout of the same string 

25_ROWS: Memo[tuple[object, ...], dict[str, object]] = Memo(1 << 12) 

26_ROW = ("submobjects", "initial_height", "background_rectangle") 

27 

28 

29class _NumberStyle(_Style, total=False): 

30 """NumberStyle's keys, open, for the keywords that add to them.""" 

31 

32 mob_class: type[ManimTextLabel] 

33 """The class each character is typeset with (default [MathTex][manimgx.MathTex]).""" 

34 include_sign: bool 

35 """Whether a number that is not negative is written with a plus sign (default 

36 False).""" 

37 group_with_commas: bool 

38 """Whether the digits before the decimal point are grouped in threes by commas, 

39 12,345 (default True).""" 

40 digit_buff_per_font_unit: float 

41 """The gap between characters, per unit of font size: 0.001, the default, is 0.048 

42 scene units at font size 48.""" 

43 show_ellipsis: bool 

44 """Whether "…" follows the number, for a value that goes on (default False).""" 

45 unit: str | None 

46 r"""A unit after the number, in LaTeX math: `"^\circ"` for degrees, `r"\text{ m}"`; 

47 one that starts with "^" is raised to the number's top (default None).""" 

48 unit_buff_per_font_unit: float 

49 """The gap before the unit, beyond the gap between characters, per unit of font 

50 size (default 0).""" 

51 include_background_rectangle: bool 

52 """Whether a background rectangle is behind the number (default False).""" 

53 edge_to_fix: Vector3DLike 

54 """The edge, as a direction, that stays where it is when a new value changes the 

55 number's width (default LEFT: it grows to the right).""" 

56 font_size: float 

57 """The characters' font size, as `mob_class` measures it (default 48).""" 

58 

59 

60class NumberStyle(_NumberStyle, total=False, closed=True): 

61 """How a number is written: [DecimalNumber][manimgx.DecimalNumber]'s keywords but 

62 its number of decimal places, for the classes that pass them on. 

63 

64 Beyond these, they take the [style keywords][manimgx.drawing.paint.Style]. 

65 """ 

66 

67 

68class DecimalNumberOptions(_NumberStyle, total=False, closed=True): 

69 """[DecimalNumber][manimgx.DecimalNumber]'s keywords, for the classes that pass them 

70 on: a number line's labels. 

71 

72 Beyond these, they take the 

73 [number keywords][manimgx.mobjects.numbers.NumberStyle]. 

74 """ 

75 

76 num_decimal_places: int 

77 """How many digits follow the decimal point (default 2).""" 

78 

79 

80class DecimalNumber[V: (float, complex) = float](VMobject): 

81 r"""A number, written with a fixed number of decimal places: white and filled 

82 unless styled. 

83 

84 Its parts are its characters, in order, each typeset by `mob_class`: the sign, the 

85 digits, the commas and the decimal point; then "…" and the unit, if any (and a 

86 background rectangle before them all, if asked for). The number shown is rounded (a 

87 negative one that rounds to zero loses its sign, in either component of a complex 

88 number), and a complex one is written `a+bi`. 

89 [set_value][manimgx.DecimalNumber.set_value] shows another 

90 number, keeping the font size, the color and the edge `edge_to_fix` where they are: 

91 driven by a [value tracker][manimgx.ValueTracker], or by 

92 [ChangeDecimalToValue][manimgx.ChangeDecimalToValue], the number counts on screen. 

93 

94 A type checker follows the initial value's kind: real by default, complex for a 

95 complex initial value. Use `DecimalNumber[complex](0)` to start real and later 

96 accept complex values. 

97 

98 Args: 

99 number: The number to show; a complex one too. 

100 num_decimal_places: How many digits follow the decimal point. 

101 mob_class: The class each character is typeset with. 

102 include_sign: Whether a number that is not negative is written with a plus 

103 sign. 

104 group_with_commas: Whether the digits before the decimal point are grouped in 

105 threes by commas. 

106 digit_buff_per_font_unit: The gap between characters, per unit of font size 

107 (0.001: 0.048 scene units at 48). 

108 show_ellipsis: Whether "…" follows the number. 

109 unit: A unit after the number, in LaTeX math (`"^\circ"`, `r"\text{ m}"`); one 

110 that starts with "^" is raised to the number's top. 

111 unit_buff_per_font_unit: The gap before the unit, beyond the gap between 

112 characters, per unit of font size. 

113 include_background_rectangle: Whether a background rectangle is behind the 

114 number. 

115 edge_to_fix: The edge, as a direction, that stays where it is when a new value 

116 changes the number's width. 

117 font_size: The characters' font size, as `mob_class` measures it. 

118 

119 Examples: 

120 ```python 

121 import manimgx as m 

122 

123 

124 class DecimalNumberExample(m.Scene): 

125 def construct(self) -> None: 

126 numbers = m.VGroup( 

127 m.DecimalNumber(3.14159), 

128 m.DecimalNumber(1234567.891, num_decimal_places=1), 

129 m.DecimalNumber(42, include_sign=True, color=m.YELLOW), 

130 m.DecimalNumber(90, num_decimal_places=0, unit=r"^\circ"), 

131 m.DecimalNumber(3.14159, num_decimal_places=4, show_ellipsis=True), 

132 ) 

133 self.add(numbers.arrange(m.DOWN, buff=0.4).scale(1.5)) 

134 ``` 

135 """ 

136 

137 defaults: ClassVar[Style] = {"stroke_width": 0, "fill_opacity": 1.0} 

138 

139 @prototype 

140 def __init__( 

141 self, 

142 number: V = 0, 

143 num_decimal_places: int = 2, 

144 mob_class: type[ManimTextLabel] = MathTex, 

145 include_sign: bool = False, 

146 group_with_commas: bool = True, 

147 digit_buff_per_font_unit: float = 0.001, 

148 show_ellipsis: bool = False, 

149 unit: str | None = None, 

150 unit_buff_per_font_unit: float = 0, 

151 include_background_rectangle: bool = False, 

152 edge_to_fix: Vector3DLike = LEFT, 

153 font_size: float = DEFAULT_FONT_SIZE, 

154 **kwargs: Unpack[Style], 

155 ): 

156 if font_size <= 0: 

157 raise ValueError("font_size must be greater than 0.") 

158 super().__init__(**kwargs) 

159 self.number = number 

160 self.num_decimal_places = num_decimal_places 

161 self.include_sign = include_sign 

162 self.mob_class = mob_class 

163 self.group_with_commas = group_with_commas 

164 self.digit_buff_per_font_unit = digit_buff_per_font_unit 

165 self.show_ellipsis = show_ellipsis 

166 self.unit = unit 

167 self.unit_buff_per_font_unit = unit_buff_per_font_unit 

168 self.include_background_rectangle = include_background_rectangle 

169 self.edge_to_fix = edge_to_fix 

170 self._font_size = font_size 

171 self._set_submobjects_from_number(number) 

172 self.init_colors() 

173 

174 @property 

175 def font_size(self) -> float: 

176 """The number's font size: the one it was made with, times how much it has been 

177 scaled since. Set it, to a positive size, to scale the number to it.""" 

178 return_value: float = self.height / self.initial_height * self._font_size 

179 return return_value 

180 

181 @font_size.setter 

182 def font_size(self, font_val: float) -> None: 

183 if font_val <= 0: 

184 raise ValueError("font_size must be greater than 0.") 

185 elif self.height > 0: 

186 self.scale(font_val / self.font_size) 

187 

188 def _row_key(self, shown: str) -> tuple[object, ...]: 

189 """The displayed row, before placement and final repaint.""" 

190 return ( 

191 type(self), 

192 shown, 

193 self.mob_class, 

194 self._font_size, 

195 self.digit_buff_per_font_unit, 

196 self.unit, 

197 self.unit_buff_per_font_unit, 

198 self.include_background_rectangle, 

199 self.show_ellipsis, 

200 ) 

201 

202 def _set_submobjects_from_number(self, number: V) -> tuple[object, ...]: 

203 """The glyphs of `number` about the origin at the constructed font size: laid out once per 

204 string and layout, then copied.""" 

205 self.number = number 

206 shown = self._get_num_string(number) 

207 key = self._row_key(shown) 

208 # The layout is independent of paint; the cached ellipsis starts in its ink. 

209 cache_key = (*key, str(self.get_color()) if self.show_ellipsis else None) 

210 if not self.include_background_rectangle: 

211 self.__dict__.pop("background_rectangle", None) 

212 row = _ROWS.get(cache_key) 

213 if row is None: 

214 self._lay_out(shown) 

215 _ROWS.keep( 

216 cache_key, 

217 copied( 

218 { 

219 name: self.__dict__[name] 

220 for name in _ROW 

221 if name in self.__dict__ 

222 } 

223 ), 

224 ) 

225 else: 

226 self.__dict__.update(copied(row)) 

227 return key 

228 

229 def _lay_out(self, num_string: str) -> None: 

230 self.submobjects = [] 

231 # Size the constructed labels: constructing at that size rounds their points 

232 # differently, enough to move a number line's coordinates in rendered frames. 

233 self.add( 

234 *( 

235 self.mob_class(char).set(font_size=self._font_size) 

236 for char in num_string 

237 ) 

238 ) 

239 if self.show_ellipsis: 

240 self.add( 

241 SingleStringMathTex("\\dots", color=self.get_color()).set( 

242 font_size=self._font_size 

243 ) 

244 ) 

245 self.arrange( 

246 buff=self.digit_buff_per_font_unit * self._font_size, aligned_edge=DOWN 

247 ) 

248 unit_sign = None 

249 if self.unit is not None: 

250 unit_sign = SingleStringMathTex(self.unit).set(font_size=self._font_size) 

251 self.add( 

252 unit_sign.next_to( 

253 self, 

254 direction=RIGHT, 

255 buff=(self.unit_buff_per_font_unit + self.digit_buff_per_font_unit) 

256 * self._font_size, 

257 aligned_edge=DOWN, 

258 ) 

259 ) 

260 self.move_to(ORIGIN) 

261 for i, c in enumerate(num_string): 

262 if c == "-" and len(num_string) > i + 1: 

263 self[i].align_to(self[i + 1], UP) 

264 self[i].shift(self[i + 1].height * DOWN / 2) 

265 elif c == ",": 

266 self[i].shift(self[i].height * DOWN / 2) 

267 if unit_sign is not None and self.unit and self.unit.startswith("^"): 

268 unit_sign.align_to(self, UP) 

269 self.initial_height: float = self.height 

270 if self.include_background_rectangle: 

271 self.add_background_rectangle() 

272 

273 def _get_num_string(self, number: float | complex) -> str: 

274 if isinstance(number, complex | np.complexfloating): # a+bi, not Python's a+bj 

275 return ( 

276 self._get_formatter("0.real") 

277 + self._get_formatter("0.imag", include_sign=True) 

278 + "i" 

279 ).format(number) 

280 return self._get_formatter().format(number) 

281 

282 def _get_formatter( 

283 self, field_name: str = "", include_sign: bool | None = None 

284 ) -> str: 

285 sign = self.include_sign if include_sign is None else include_sign 

286 commas = "," if self.group_with_commas else "" 

287 return f"{{{field_name}:{'+' if sign else ''}z{commas}.{self.num_decimal_places}f}}" 

288 

289 _shown: ( 

290 tuple[tuple[object, ...], tuple[tuple[Mobject, Blend, Paint], ...]] | None 

291 ) = None 

292 

293 def get_value(self) -> V: 

294 """The number shown, as it was given: not rounded.""" 

295 return self.number 

296 

297 def increment_value(self, delta_t: V = 1) -> Self: 

298 """Show the number plus `delta_t`. 

299 

300 Args: 

301 delta_t: What to add. 

302 """ 

303 return self.set_value(self.get_value() + delta_t) 

304 

305 def set_value(self, number: V) -> Self: 

306 """Show another number, keeping the look: the font size, the edge `edge_to_fix` 

307 where it is, and the color — every character takes the number's own, so a color 

308 given to single characters is not kept. 

309 

310 Args: 

311 number: The number to show. 

312 

313 Examples: 

314 ```python 

315 import manimgx as m 

316 

317 

318 class DecimalNumberSetValueExample(m.Scene): 

319 def construct(self) -> None: 

320 tracker = m.ValueTracker(0) 

321 number = m.DecimalNumber(0, font_size=144).shift(2 * m.LEFT) 

322 number.add_updater(lambda n: n.set_value(tracker.get_value())) 

323 self.add(number) 

324 self.play(tracker.animate.set_value(100), run_time=3) 

325 ``` 

326 """ 

327 # every glyph takes the number's own color, as CE's `init_colors` repaints them. 

328 # A number still as it was left showing the same string is left alone: its 

329 # members' geometry and paint are values, so "as it was left" is the same objects 

330 shown = self._get_num_string(number) 

331 key = self._row_key(shown) 

332 last = self._shown 

333 if last is not None and last[0] == key: 

334 family = self.get_family() 

335 if len(family) == len(last[1]) and all( 

336 m is was and m._geometry is g and m.paint is p 

337 for m, (was, g, p) in zip(family, last[1], strict=True) 

338 ): 

339 self.number = number 

340 return self 

341 old_font_size = self.font_size 

342 move_to_point = self.get_critical_point(self.edge_to_fix) 

343 key = self._set_submobjects_from_number(number) 

344 self.font_size = old_font_size 

345 self.move_to(move_to_point, self.edge_to_fix) 

346 self.init_colors() 

347 self._shown = ( 

348 key, 

349 tuple((m, m._geometry, m.paint) for m in self.get_family()), 

350 ) 

351 return self 

352 

353 

354class Integer(DecimalNumber): 

355 """An integer: a [DecimalNumber][manimgx.DecimalNumber] with no decimal places, 

356 white and filled unless styled. 

357 

358 A number with a fractional part is shown rounded, and 

359 [get_value][manimgx.Integer.get_value] rounds it too. 

360 

361 Args: 

362 number: The number to show. 

363 num_decimal_places: How many digits follow the decimal point: none unless 

364 given. 

365 

366 Examples: 

367 ```python 

368 import manimgx as m 

369 

370 

371 class IntegerExample(m.Scene): 

372 def construct(self) -> None: 

373 count = m.Integer(0, font_size=144).shift(1.5 * m.LEFT) 

374 self.add(count) 

375 self.play(m.ChangeDecimalToValue(count, 1000), run_time=3) 

376 ``` 

377 """ 

378 

379 def __init__( 

380 self, 

381 number: float = 0, 

382 num_decimal_places: int = 0, 

383 **kwargs: Unpack[NumberStyle], 

384 ) -> None: 

385 super().__init__(number=number, num_decimal_places=num_decimal_places, **kwargs) 

386 

387 def get_value(self) -> int: 

388 """The number shown: the number given, rounded to an integer.""" 

389 return int(np.round(super().get_value())) 

390 

391 

392class Variable(VMobject): 

393 """A named value: a label, "=", and a number that shows a value tracker's value. 

394 

395 Its parts are its [label][manimgx.Variable.label], followed by "=", and its 

396 [value][manimgx.Variable.value], a [DecimalNumber][manimgx.DecimalNumber] or an 

397 [Integer][manimgx.Integer] that shows its [tracker][manimgx.Variable.tracker]'s 

398 value at every frame: animate the tracker, and the number counts. 

399 

400 Args: 

401 var: The value it starts with. 

402 label: The label: a string, typeset as math ([MathTex][manimgx.MathTex]), or a 

403 text or math mobject. 

404 var_type: The number's class: DecimalNumber or a subclass, such as Integer. 

405 num_decimal_places: How many digits follow the decimal point. Integer classes 

406 use their own precision defaults instead. 

407 **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the group itself; its 

408 parts keep their own (color them through `label` and `value`). 

409 

410 Examples: 

411 ```python 

412 import manimgx as m 

413 

414 

415 class VariableExample(m.Scene): 

416 def construct(self) -> None: 

417 x = m.Variable(2.0, "x", num_decimal_places=3) 

418 y = m.Variable(4.0, "x^2", num_decimal_places=3) 

419 self.add(m.VGroup(x, y).arrange(m.DOWN, buff=0.5).scale(2)) 

420 t = x.tracker 

421 y.add_updater(lambda v: v.tracker.set_value(t.get_value() ** 2)) 

422 self.play(t.animate.set_value(5), run_time=3, rate_func=m.linear) 

423 ``` 

424 """ 

425 

426 def __init__( 

427 self, 

428 var: float, 

429 label: str | MathTex | Text | SingleStringMathTex, 

430 var_type: type[DecimalNumber] = DecimalNumber, 

431 num_decimal_places: int = 2, 

432 **kwargs: Unpack[Style], 

433 ): 

434 self.label = MathTex(label) if isinstance(label, str) else label 

435 """The label, followed by "=", one of its submobjects.""" 

436 equals = MathTex("=").next_to(self.label, RIGHT) 

437 self.label.add(equals) 

438 self.tracker = ValueTracker(var) 

439 """The value tracker the number shows: set or animate it to change the 

440 number.""" 

441 self.value = ( 

442 var_type(self.tracker.get_value()) 

443 if issubclass(var_type, Integer) 

444 else var_type( 

445 self.tracker.get_value(), num_decimal_places=num_decimal_places 

446 ) 

447 ) 

448 """The number, which shows the tracker's value at every frame.""" 

449 self.value.add_updater(self._update_value).next_to(self.label, RIGHT) 

450 super().__init__(**kwargs) 

451 self.add(self.label, self.value) 

452 

453 def _update_value(self, value: DecimalNumber) -> None: 

454 value.set_value(self.tracker.get_value()) 

455 

456 

457def index_labels( 

458 mobject: Mobject, label_height: float = 0.15, **kwargs: Unpack[NumberStyle] 

459) -> VGroup: 

460 r"""Number the submobjects of a mobject: an [Integer][manimgx.Integer] at the center 

461 of each, on a dark outline, to find a part's index. 

462 

463 A debugging help: add the labels to the scene to see them; they don't follow the 

464 mobject. 

465 

466 Args: 

467 mobject: The mobject whose submobjects are numbered, from 0. 

468 label_height: Each label's height, in scene units. 

469 **kwargs: [Number keywords][manimgx.mobjects.numbers.NumberStyle] (a black 

470 background stroke 5 wide unless given). 

471 

472 Returns: 

473 A new group of the labels, in order. 

474 

475 Examples: 

476 ```python 

477 import manimgx as m 

478 

479 

480 class IndexLabelsExample(m.Scene): 

481 def construct(self) -> None: 

482 formula = m.MathTex(r"\binom{2n}{n+2}", font_size=144) 

483 formula[0][1:3].set_color(m.YELLOW) 

484 formula[0][3:6].set_color(m.RED) 

485 self.add(formula, m.index_labels(formula[0], label_height=0.3)) 

486 ``` 

487 """ 

488 kwargs.setdefault("background_stroke_width", 5) 

489 kwargs.setdefault("background_stroke_color", BLACK) 

490 labels = VGroup() 

491 for n, submob in enumerate(mobject): 

492 label = Integer(n, **kwargs) 

493 label.height = label_height 

494 labels.add(label.move_to(submob)) 

495 return labels