Coverage for src/manimgx/mobjects/grid.py: 97%
279 statements
« prev ^ index » next coverage.py v7.16.1, created at 2026-10-26 05:52 +0000
« 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
6"Rows and columns of entries: matrices place them between brackets; tables fit cells and rules."
8from __future__ import annotations
10import itertools as it
11from collections.abc import Callable, Iterable, Mapping, Sequence
12from typing import ClassVar, Self, Unpack
14import numpy as np
16from manimgx.animation.motion import Create, FadeIn, Write
17from manimgx.animation.timeline import Animation, AnimationGroup, AnimationOptions
18from manimgx.constants import DOWN, DR, LEFT, MED_SMALL_BUFF, RIGHT, UP
19from manimgx.drawing.paint import (
20 BLACK,
21 PURE_YELLOW,
22 Colors,
23 ManimColor,
24 ParsableManimColor,
25 Style,
26 _Style,
27)
28from manimgx.mobject import (
29 GridArrangement,
30 Mobject,
31 VGroup,
32 VMobject,
33 _family,
34 _family_box,
35)
36from manimgx.mobjects.annotations import BackgroundRectangle, FrameOptions
37from manimgx.mobjects.numbers import DecimalNumber, Integer
38from manimgx.mobjects.shapes import Line, LineOptions, Polygon
39from manimgx.mobjects.text import MathTex, MathTexOptions, Paragraph
40from manimgx.typing import Vector2DLike, Vector3DLike
42__all__ = [
43 "DecimalMatrix",
44 "DecimalTable",
45 "IntegerMatrix",
46 "IntegerTable",
47 "MathTable",
48 "Matrix",
49 "MobjectMatrix",
50 "MobjectTable",
51 "Table",
52]
54type Entries = Iterable[Iterable[object]] | Iterable[Vector2DLike]
55"""A matrix's entries, row by row: each row an iterable of entries, as its
56`element_to_mobject` takes them."""
57type ElementFactory = Callable[..., Mobject]
58"""What makes the mobject of a matrix's or a table's entry: called with the entry, and
59with the keywords of `element_to_mobject_config` (a class, as
60[MathTex][manimgx.MathTex], or any function)."""
63class MatrixOptions(_Style, total=False, closed=True):
64 """A [Matrix][manimgx.Matrix]'s keywords but its entries, for the methods that pass
65 them on (a [vector's coordinate label][manimgx.Vector.coordinate_label]): its
66 entries' kind, with its layout, brackets and style."""
68 v_buff: float
69 """The distance between rows, in scene units, from one row's entries' alignment
70 corners to the next's (default 0.8)."""
71 h_buff: float
72 """The distance between columns, in scene units, likewise (default 1.3)."""
73 bracket_h_buff: float
74 """The gap between the entries and each bracket, in scene units (default 0.25)."""
75 bracket_v_buff: float
76 """How far the brackets reach above and below the entries, in scene units, when
77 stretched (default 0.25)."""
78 add_background_rectangles_to_entries: bool
79 """Whether each entry gets a background rectangle (default False)."""
80 include_background_rectangle: bool
81 """Whether the matrix gets a background rectangle (default False)."""
82 element_alignment_corner: Vector3DLike
83 """The corner of each entry put on the grid, named by a direction: DR aligns the
84 entries of a column on their right, UL on their left (default DR)."""
85 left_bracket: str
86 r"""The left bracket, as a LaTeX delimiter: `"["`, `"("`, `"\{"`, `"\langle"`,
87 `"|"`, … (default `"["`)."""
88 right_bracket: str
89 """The right bracket, as a LaTeX delimiter (default `"]"`)."""
90 stretch_brackets: bool
91 """Whether the brackets are stretched to the entries' height, and `bracket_v_buff`
92 beyond (default True)."""
93 bracket_config: MathTexOptions | None
94 """[Math keywords][manimgx.MathTex] for the
95 brackets: their `color`, … (default None: none)."""
97 element_to_mobject: ElementFactory
98 """The function that makes each entry's mobject, called with the entry and the
99 keywords of `element_to_mobject_config` (default: the matrix class's own,
100 [MathTex][manimgx.MathTex] for a [Matrix][manimgx.Matrix])."""
101 element_to_mobject_config: Mapping[str, object] | None
102 """Keywords for `element_to_mobject` (default None: the matrix class's own, none
103 for a [Matrix][manimgx.Matrix])."""
106def _same(entry: Mobject) -> Mobject:
107 return entry
110class _Grid:
111 """Entries in rows and columns (`cells`), each made from its item by the class's `entry` with
112 its `entry_config`, unless the constructor is given others."""
114 entry: ClassVar[ElementFactory] = MathTex
115 """The function that makes each entry's mobject when the constructor is given no
116 `element_to_mobject`: a class, as [MathTex][manimgx.MathTex], or any function. A
117 subclass sets its own ([IntegerMatrix][manimgx.IntegerMatrix]'s is
118 [Integer][manimgx.Integer])."""
119 entry_config: ClassVar[Mapping[str, object]] = {}
120 """The keywords `entry` is called with when the constructor is given no
121 `element_to_mobject_config` (none, unless a subclass sets them)."""
122 cells: list[list[Mobject]]
123 """The entries' mobjects, as a list of rows from the top down, each a list of its
124 mobjects from left to right (a table's labels included)."""
126 def _make_cells(
127 self,
128 data: Iterable[Iterable[object]],
129 factory: ElementFactory | None,
130 config: Mapping[str, object] | None,
131 ) -> list[list[Mobject]]:
132 make = factory or type(self).entry
133 options = type(self).entry_config if config is None else config
134 return [[make(item, **options) for item in row] for row in data]
136 def get_rows(self) -> VGroup:
137 """The rows, from the top down, each a group of its entries from left to right
138 (a table's labels included).
140 Returns:
141 A new group of the rows.
143 Examples:
144 ```python
145 import manimgx as m
148 class MatrixGetRowsExample(m.Scene):
149 def construct(self) -> None:
150 matrix = m.Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).scale(1.5)
151 row = m.SurroundingRectangle(matrix.get_rows()[1])
152 self.add(matrix)
153 self.play(m.Create(row))
154 ```
155 """
156 return VGroup(*(VGroup(*row) for row in self.cells))
158 def get_columns(self) -> VGroup:
159 """The columns, from left to right, each a group of its entries from the top
160 down (a table's labels included).
162 Returns:
163 A new group of the columns.
165 Examples:
166 ```python
167 import manimgx as m
170 class TableGetColumnsExample(m.Scene):
171 def construct(self) -> None:
172 table = m.Table(
173 [["First", "Second"], ["Third", "Fourth"]],
174 row_labels=[m.Text("R1"), m.Text("R2")],
175 col_labels=[m.Text("C1"), m.Text("C2")],
176 )
177 column = m.SurroundingRectangle(table.get_columns()[1])
178 self.add(table)
179 self.play(m.Create(column))
180 ```
181 """
182 return VGroup(*(VGroup(*column) for column in zip(*self.cells, strict=False)))
184 def set_row_colors(self, *colors: Colors) -> Self:
185 """Color the rows, from the top down: each one color, or several for a gradient
186 (as [set_color][manimgx.Mobject.set_color] makes one); rows past the last
187 color keep theirs.
189 Args:
190 *colors: The rows' colors, in order: a color each, or a list of colors.
192 Examples:
193 ```python
194 import manimgx as m
197 class MatrixSetRowColorsExample(m.Scene):
198 def construct(self) -> None:
199 matrix = m.Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).scale(1.5)
200 self.add(matrix.set_row_colors(m.RED, [m.YELLOW, m.GREEN]))
201 ```
202 """
203 for color, row in zip(colors, self.get_rows(), strict=False):
204 row.set_color(color)
205 return self
207 def set_column_colors(self, *colors: Colors) -> Self:
208 """Color the columns, from left to right: each one color, or several for a
209 gradient (as [set_color][manimgx.Mobject.set_color] makes one); columns past
210 the last color keep theirs.
212 Args:
213 *colors: The columns' colors, in order: a color each, or a list of colors.
215 Examples:
216 ```python
217 import manimgx as m
220 class TableSetColumnColorsExample(m.Scene):
221 def construct(self) -> None:
222 table = m.Table(
223 [["First", "Second"], ["Third", "Fourth"]],
224 row_labels=[m.Text("R1"), m.Text("R2")],
225 col_labels=[m.Text("C1"), m.Text("C2")],
226 )
227 self.add(table.set_column_colors(m.YELLOW, m.BLUE, m.GREEN))
228 ```
229 """
230 for color, column in zip(colors, self.get_columns(), strict=False):
231 column.set_color(color)
232 return self
235class Matrix(_Grid, VMobject):
236 r"""A matrix: entries in rows and columns between brackets; white unless styled.
238 Each entry is made into a mobject by `element_to_mobject` — by default typeset as
239 math, with [MathTex][manimgx.MathTex] — and put on a grid, rows `v_buff` apart and
240 columns `h_buff` apart, by its bottom right corner (`element_alignment_corner`): the
241 entries of a column are aligned on their right. Brackets, typeset as LaTeX
242 delimiters, stand on either side, stretched to the entries' height; the matrix is
243 centered on the scene's origin. Its [entries][manimgx.Matrix.get_entries] and
244 [brackets][manimgx.Matrix.get_brackets] can be reached, colored and animated, and
245 so can its rows and columns: `get_rows()` and `get_columns()` give them as groups,
246 `set_row_colors(...)` and `set_column_colors(...)` color them.
248 Layout and bracket options are used during construction; the resulting cells and
249 brackets hold the matrix's state.
251 Args:
252 matrix: The entries, row by row: numbers, strings of math or mobjects, as
253 `element_to_mobject` takes them.
254 v_buff: The distance between rows, in scene units, from one row's entries'
255 alignment corners to the next's.
256 h_buff: The distance between columns, in scene units, likewise.
257 bracket_h_buff: The gap between the entries and each bracket, in scene units.
258 bracket_v_buff: How far the brackets reach above and below the entries, in
259 scene units, when stretched.
260 add_background_rectangles_to_entries: Whether each entry gets a background
261 rectangle, in the scene's background color (see
262 [add_background_rectangle][manimgx.Mobject.add_background_rectangle]).
263 include_background_rectangle: Whether the matrix gets a background rectangle
264 (see [add_background_rectangle][manimgx.Mobject.add_background_rectangle]).
265 element_to_mobject: The function that makes each entry's mobject, called with
266 the entry and the keywords of `element_to_mobject_config`: a class, as
267 [DecimalNumber][manimgx.DecimalNumber], or any function; None for the
268 class's own (MathTex, for a Matrix).
269 element_to_mobject_config: Keywords for `element_to_mobject`; None for the
270 class's own (none, for a Matrix).
271 element_alignment_corner: The corner of each entry put on the grid, named by a
272 direction: DR aligns the entries of a column on their right, UL on their
273 left.
274 left_bracket: The left bracket, as a LaTeX delimiter: `"["`, `"("`, `"\{"`,
275 `"\langle"`, `"|"`, ….
276 right_bracket: The right bracket, as a LaTeX delimiter.
277 stretch_brackets: Whether the brackets are stretched to the entries' height,
278 and `bracket_v_buff` beyond.
279 bracket_config: [Math keywords][manimgx.MathTex]
280 for the brackets: their `color`, …; None for none.
281 **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the matrix itself: as it
282 has no points, they do not restyle its entries or its brackets.
284 Examples:
285 ```python
286 import manimgx as m
289 class MatrixExample(m.Scene):
290 def construct(self) -> None:
291 matrices = m.VGroup(
292 m.Matrix([[2, 0], [-1, 1]]),
293 m.Matrix(
294 [[r"\cos t", r"-\sin t"], [r"\sin t", r"\cos t"]],
295 h_buff=2,
296 left_bracket="(",
297 right_bracket=")",
298 ),
299 m.Matrix(
300 [[10, 2, 300], [4, 50, 6]],
301 element_alignment_corner=m.UL,
302 bracket_config={"color": m.BLUE},
303 ),
304 ).arrange(buff=1)
305 self.add(matrices)
306 ```
307 """
309 def __init__(
310 self,
311 matrix: Entries,
312 v_buff: float = 0.8,
313 h_buff: float = 1.3,
314 bracket_h_buff: float = MED_SMALL_BUFF,
315 bracket_v_buff: float = MED_SMALL_BUFF,
316 add_background_rectangles_to_entries: bool = False,
317 include_background_rectangle: bool = False,
318 element_to_mobject: ElementFactory | None = None,
319 element_to_mobject_config: Mapping[str, object] | None = None,
320 element_alignment_corner: Vector3DLike = DR,
321 left_bracket: str = "[",
322 right_bracket: str = "]",
323 stretch_brackets: bool = True,
324 bracket_config: MathTexOptions | None = None,
325 **kwargs: Unpack[Style],
326 ):
327 if bracket_config is None:
328 bracket_config = {}
329 super().__init__(**kwargs)
330 self.cells = self._make_cells(
331 matrix, element_to_mobject, element_to_mobject_config
332 )
333 cells = self.cells
334 for i, row in enumerate(cells):
335 for j, _ in enumerate(row):
336 mob = cells[i][j]
337 mob.move_to(
338 i * v_buff * DOWN + j * h_buff * RIGHT,
339 element_alignment_corner,
340 )
341 self.elements = VGroup(*it.chain(*self.cells))
342 """The entries, row by row: a group, added to the matrix."""
343 self.add(self.elements)
344 bracket_config = {**bracket_config}
345 BRACKET_HEIGHT = 0.5977
346 n = int(self.height / BRACKET_HEIGHT) + 1
347 empty_tex_array = "".join(
348 ["\\begin{array}{c}", *n * ["\\quad \\\\"], "\\end{array}"]
349 )
350 tex_left = "".join(["\\left" + left_bracket, empty_tex_array, "\\right."])
351 tex_right = "".join(["\\left.", empty_tex_array, "\\right" + right_bracket])
352 l_bracket = MathTex(tex_left, **bracket_config)
353 r_bracket = MathTex(tex_right, **bracket_config)
354 bracket_pair = VGroup(l_bracket, r_bracket)
355 if stretch_brackets:
356 bracket_pair.stretch_to_fit_height(self.height + 2 * bracket_v_buff)
357 l_bracket.next_to(self, LEFT, bracket_h_buff)
358 r_bracket.next_to(self, RIGHT, bracket_h_buff)
359 self.brackets = bracket_pair
360 self.add(l_bracket, r_bracket)
361 self.center()
362 if add_background_rectangles_to_entries:
363 for mob in self.elements:
364 mob.add_background_rectangle()
365 if include_background_rectangle:
366 self.add_background_rectangle()
368 def get_entries(self) -> VGroup:
369 """The matrix's entries, row by row.
371 Returns:
372 The group of the entries; `get_entries()[1]` is the second entry of the
373 first row.
375 Examples:
376 ```python
377 import manimgx as m
380 class MatrixGetEntriesExample(m.Scene):
381 def construct(self) -> None:
382 matrix = m.Matrix([[2, 3], [1, 5]]).scale(1.5)
383 entries = matrix.get_entries()
384 self.add(matrix)
385 self.play(entries[0].animate.set_color(m.YELLOW))
386 self.play(m.Swap(entries[1], entries[2]))
387 ```
388 """
389 return self.elements
391 def get_brackets(self) -> VGroup:
392 r"""The matrix's brackets, the left one first.
394 Returns:
395 The group of the two brackets.
397 Examples:
398 ```python
399 import manimgx as m
402 class MatrixGetBracketsExample(m.Scene):
403 def construct(self) -> None:
404 matrix = m.Matrix([[r"\pi", 3], [1, 5]]).scale(1.5)
405 left, right = matrix.get_brackets()
406 self.add(matrix)
407 self.play(
408 left.animate.set_color(m.BLUE), right.animate.set_color(m.GREEN)
409 )
410 ```
411 """
412 return self.brackets
415class DecimalMatrix(Matrix):
416 r"""A matrix of decimal numbers: each entry written as a
417 [DecimalNumber][manimgx.DecimalNumber], with one decimal place unless configured.
419 It takes a [Matrix][manimgx.Matrix]'s arguments; its entries are numbers, and its
420 `element_to_mobject_config` gives the numbers'
421 [keywords][manimgx.DecimalNumber], in place of
422 `{"num_decimal_places": 1}`.
424 Examples:
425 ```python
426 import manimgx as m
429 class DecimalMatrixExample(m.Scene):
430 def construct(self) -> None:
431 matrix = m.DecimalMatrix(
432 [[3.456, 2.122], [33.2244, 12]],
433 h_buff=2,
434 element_to_mobject_config={"num_decimal_places": 2},
435 left_bracket=r"\{",
436 right_bracket=r"\}",
437 )
438 self.add(matrix.scale(1.5))
439 ```
440 """
442 entry = DecimalNumber
443 entry_config: ClassVar[Mapping[str, object]] = {"num_decimal_places": 1}
446class IntegerMatrix(Matrix):
447 """A matrix of integers: each entry written as an [Integer][manimgx.Integer], its
448 number rounded to a whole number.
450 It takes a [Matrix][manimgx.Matrix]'s arguments; its entries are numbers, and its
451 `element_to_mobject_config` gives the numbers'
452 [keywords][manimgx.DecimalNumber].
454 Examples:
455 ```python
456 import manimgx as m
459 class IntegerMatrixExample(m.Scene):
460 def construct(self) -> None:
461 matrix = m.IntegerMatrix(
462 [[3.7, 2], [42.2, 12]], left_bracket="(", right_bracket=")"
463 )
464 self.add(matrix.scale(1.5))
465 ```
466 """
468 entry = Integer
471class MobjectMatrix(Matrix):
472 r"""A matrix of mobjects: each entry a mobject, placed as it is.
474 It takes a [Matrix][manimgx.Matrix]'s arguments; its entries are mobjects, used
475 themselves (not copied).
477 Examples:
478 ```python
479 import manimgx as m
482 class MobjectMatrixExample(m.Scene):
483 def construct(self) -> None:
484 circle = m.Circle(radius=0.3, color=m.BLUE)
485 triangle = m.Triangle(radius=0.35, color=m.GREEN)
486 matrix = m.MobjectMatrix(
487 [[circle, m.Square(0.6)], [triangle, m.Star(outer_radius=0.35)]],
488 left_bracket=r"\langle",
489 right_bracket=r"\rangle",
490 )
491 self.add(matrix.scale(1.5))
492 ```
493 """
495 entry = staticmethod(_same)
498class Table(_Grid, VGroup):
499 """A table: entries in rows and columns, with lines between them, and labels for
500 the rows and the columns if given; white unless styled.
502 Each entry is made into a mobject by `element_to_mobject` — by default a
503 [Paragraph][manimgx.Paragraph] of its text — and the cells are laid out in a grid,
504 each entry centered in its cell (see
505 [arrange_in_grid][manimgx.Mobject.arrange_in_grid]); the table is centered on the
506 scene's origin. Row labels make a first column, column labels a first row, and
507 `top_left_entry` fills the corner between them. The lines run through the middle of
508 the gaps between rows and between columns, and half a gap beyond the entries. Its
509 rows and columns can be reached as groups, `get_rows()` and `get_columns()`, and
510 colored, `set_row_colors(...)` and `set_column_colors(...)`, labels included.
512 A cell is addressed by its position, `(row, column)`, counted from 1 at the top
513 left, labels included: in a table with row and column labels, (1, 1) is the corner
514 and the first entry is at (2, 2).
516 Grid, line and background options are consumed during construction; cells, labels,
517 line groups and gaps hold the table's state.
519 Args:
520 table: The entries, row by row, every row as long: strings, for the default
521 [Paragraph][manimgx.Paragraph]; numbers or mobjects, as another
522 `element_to_mobject` takes them.
523 row_labels: A label for each row, left of it; None for none.
524 col_labels: A label for each column, above it; None for none.
525 top_left_entry: A mobject for the corner above the row labels and left of the
526 column labels, when there are both; None to leave it empty.
527 v_buff: The gap between rows, in scene units.
528 h_buff: The gap between columns, in scene units.
529 include_outer_lines: Whether lines frame the table.
530 include_inner_lines: Whether lines separate its rows and its columns.
531 add_background_rectangles_to_entries: Whether each entry, labels included,
532 gets a background rectangle (see
533 [add_background_to_entries][manimgx.Table.add_background_to_entries]).
534 entries_background_color: The color of the entries' background rectangles.
535 include_background_rectangle: Whether the table gets a background rectangle
536 (see [add_background_rectangle][manimgx.Mobject.add_background_rectangle]).
537 background_rectangle_color: The color of the table's background rectangle.
538 element_to_mobject: The function that makes each entry's mobject, called with
539 the entry and the keywords of `element_to_mobject_config`: a class, as
540 [MathTex][manimgx.MathTex], or any function; None for the class's own
541 (Paragraph, for a Table).
542 element_to_mobject_config: Keywords for `element_to_mobject`; None for the
543 class's own (none, for a Table).
544 arrange_in_grid_config: [Grid keywords][manimgx.Mobject.arrange_in_grid]
545 for laying out the cells, over the table's own rows, columns and gaps:
546 `cell_alignment`, `col_alignments`, …; None for none.
547 line_config: [Line keywords][manimgx.Line] for the
548 lines: their `color`, `stroke_width`, …; None for none.
549 **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the table itself: as it
550 has no points, they do not restyle its entries or its lines.
552 Examples:
553 ```python
554 import manimgx as m
557 class TableExample(m.Scene):
558 def construct(self) -> None:
559 table = m.Table(
560 [["1", "2", "3"], ["2", "4", "6"], ["3", "6", "9"]],
561 row_labels=[m.Text("1"), m.Text("2"), m.Text("3")],
562 col_labels=[m.Text("1"), m.Text("2"), m.Text("3")],
563 top_left_entry=m.Text("×"),
564 include_outer_lines=True,
565 line_config={"color": m.BLUE},
566 )
567 self.add(table)
568 ```
569 """
571 entry = Paragraph
573 def __init__(
574 self,
575 table: Iterable[Iterable[float | str | Mobject]],
576 row_labels: Iterable[Mobject] | None = None,
577 col_labels: Iterable[Mobject] | None = None,
578 top_left_entry: Mobject | None = None,
579 v_buff: float = 0.8,
580 h_buff: float = 1.3,
581 include_outer_lines: bool = False,
582 include_inner_lines: bool = True,
583 add_background_rectangles_to_entries: bool = False,
584 entries_background_color: ParsableManimColor = BLACK,
585 include_background_rectangle: bool = False,
586 background_rectangle_color: ParsableManimColor = BLACK,
587 element_to_mobject: ElementFactory | None = None,
588 element_to_mobject_config: Mapping[str, object] | None = None,
589 arrange_in_grid_config: GridArrangement | None = None,
590 line_config: LineOptions | None = None,
591 **kwargs: Unpack[Style],
592 ):
593 if line_config is None:
594 line_config = {}
595 if arrange_in_grid_config is None:
596 arrange_in_grid_config = {}
597 table_data = [list(row) for row in table]
598 row_label_data = list(row_labels) if row_labels is not None else []
599 col_label_data = list(col_labels) if col_labels is not None else []
600 self.row_labels = row_label_data or None
601 """The row labels, top to bottom; None if there are none."""
602 self.col_labels = col_label_data or None
603 """The column labels, left to right; None if there are none."""
604 self.top_left_entry = top_left_entry
605 """The mobject in the corner between the labels; None if there is none."""
606 self.row_dim = len(table_data)
607 """How many rows of entries the table has, labels not counted."""
608 self.col_dim = len(table_data[0])
609 """How many columns of entries the table has, labels not counted."""
610 self.v_buff = v_buff
611 """The gap between rows, in scene units, as the table was made: scaling the
612 table leaves it as it is."""
613 self.h_buff = h_buff
614 """The gap between columns, in scene units, as the table was made: scaling the
615 table leaves it as it is."""
616 entries_background_color = ManimColor(entries_background_color)
617 background_rectangle_color = ManimColor(background_rectangle_color)
618 if any(len(row) != len(table_data[0]) for row in table_data):
619 raise ValueError("Not all rows in table have the same length.")
620 super().__init__(**kwargs)
621 cells = self._make_cells(
622 table_data, element_to_mobject, element_to_mobject_config
623 )
624 self.elements_without_labels = VGroup(*it.chain(*cells))
625 """The entries but the labels, row by row."""
626 empty_corner = None
627 if self.row_labels is not None:
628 for k in range(len(self.row_labels)):
629 cells[k] = [self.row_labels[k]] + cells[k]
630 if self.col_labels is not None:
631 if self.row_labels is not None:
632 if self.top_left_entry is not None:
633 col_labels = [self.top_left_entry] + self.col_labels
634 cells.insert(0, col_labels)
635 else:
636 empty_corner = VMobject()
637 col_labels = [empty_corner] + self.col_labels
638 cells.insert(0, col_labels)
639 else:
640 cells.insert(0, self.col_labels)
641 self.cells = cells
642 self.elements = VGroup(*it.chain(*self.cells))
643 """Every entry of the table, labels included, row by row: a group, added to the
644 table."""
645 layout = GridArrangement(
646 rows=len(self.cells), cols=len(self.cells[0]), buff=(h_buff, v_buff)
647 )
648 self.elements.arrange_in_grid(**(layout | arrange_in_grid_config))
649 if empty_corner is not None:
650 self.elements.remove(empty_corner)
651 self.add(self.elements)
652 self.center()
653 for axis in (0, 1):
654 divisions = self.get_rows() if axis == 0 else self.get_columns()
655 along, across = (RIGHT, UP) if axis == 0 else (DOWN, LEFT)
656 near = [float(part.get_corner(across) @ across) for part in divisions]
657 far = [float(part.get_corner(-across) @ across) for part in divisions]
658 gap = (self.v_buff, self.h_buff)[axis] / 2
659 pad = (self.h_buff, self.v_buff)[axis] / 2
660 start = float(self.elements.get_corner(-along) @ along) - pad
661 end = float(self.elements.get_corner(along) @ along) + pad
662 anchors: list[tuple[float, bool]] = []
663 if include_outer_lines:
664 anchors.extend(((near[0] + gap, False), (far[-1] - gap, False)))
665 if include_inner_lines:
666 anchors.extend(
667 (b + 0.5 * (a - b), axis == 1) for a, b in zip(far[:-1], near[1:])
668 )
669 lines = VGroup()
670 parts: list[Line] = []
671 for anchor, reverse in anchors:
672 offset = anchor * across
673 ends = (start * along + offset, end * along + offset)
674 parts.append(Line(*(ends[::-1] if reverse else ends), **line_config))
675 lines.add(*parts)
676 self.add(*lines)
677 if axis == 0:
678 self.horizontal_lines = lines
679 else:
680 self.vertical_lines = lines
681 if add_background_rectangles_to_entries:
682 self.add_background_to_entries(color=entries_background_color)
683 if include_background_rectangle:
684 self.add_background_rectangle(color=background_rectangle_color)
686 def get_horizontal_lines(self) -> VGroup:
687 """The table's horizontal lines: the outer ones first, top then bottom, if it
688 has them, then those between its rows, from the top down.
690 Returns:
691 The group of the lines.
693 Examples:
694 ```python
695 import manimgx as m
698 class TableGetHorizontalLinesExample(m.Scene):
699 def construct(self) -> None:
700 table = m.Table(
701 [["First", "Second"], ["Third", "Fourth"]],
702 row_labels=[m.Text("R1"), m.Text("R2")],
703 col_labels=[m.Text("C1"), m.Text("C2")],
704 include_outer_lines=True,
705 )
706 self.add(table)
707 self.play(table.get_horizontal_lines().animate.set_color(m.RED))
708 ```
709 """
710 return self.horizontal_lines
712 def get_vertical_lines(self) -> VGroup:
713 """The table's vertical lines: the outer ones first, left then right, if it has
714 them, then those between its columns, from left to right.
716 Returns:
717 The group of the lines.
718 """
719 return self.vertical_lines
721 def get_entries(self, pos: Sequence[int] | None = None) -> Mobject:
722 """The table's entries, labels included, or the one at a position.
724 Args:
725 pos: The position, `(row, column)`, counted from 1 at the top left, labels
726 included; None for every entry.
728 Returns:
729 The entry; or every entry, row by row, in a group.
730 The absent corner between row and column labels is an empty mobject,
731 omitted from the group.
733 Examples:
734 ```python
735 import manimgx as m
738 class TableGetEntriesExample(m.Scene):
739 def construct(self) -> None:
740 table = m.Table(
741 [["First", "Second"], ["Third", "Fourth"]],
742 row_labels=[m.Text("R1"), m.Text("R2")],
743 col_labels=[m.Text("C1"), m.Text("C2")],
744 )
745 self.add(table)
746 self.play(table.get_entries((2, 3)).animate.set_color(m.YELLOW))
747 self.play(m.Rotate(table.get_entries((3, 2)), m.PI))
748 ```
749 """
750 if pos is not None:
751 return self.cells[pos[0] - 1][pos[1] - 1]
752 return self.elements
754 def get_entries_without_labels(self, pos: Sequence[int] | None = None) -> Mobject:
755 """The table's entries but its labels, or the one at a position among them.
757 Args:
758 pos: The position, `(row, column)`, counted from 1 at the top left entry
759 that is not a label; None for every such entry.
761 Returns:
762 The entry; or every entry but the labels, row by row, in a group.
764 Examples:
765 ```python
766 import manimgx as m
769 class TableGetEntriesWithoutLabelsExample(m.Scene):
770 def construct(self) -> None:
771 table = m.Table(
772 [["First", "Second"], ["Third", "Fourth"]],
773 row_labels=[m.Text("R1"), m.Text("R2")],
774 col_labels=[m.Text("C1"), m.Text("C2")],
775 )
776 entries = table.get_entries_without_labels()
777 colors = [m.BLUE, m.GREEN, m.YELLOW, m.RED]
778 for entry, color in zip(entries, colors):
779 entry.set_color(color)
780 self.add(table)
781 ```
782 """
783 if pos is not None:
784 row = pos[0] - 1 + (self.col_labels is not None)
785 column = pos[1] - 1 + (self.row_labels is not None)
786 return self.cells[row][column]
787 return self.elements_without_labels
789 def get_row_labels(self) -> VGroup:
790 """The table's row labels, from the top down.
792 Returns:
793 A new group of the labels; empty if there are none.
794 """
795 if self.row_labels is not None:
796 return VGroup(*self.row_labels)
797 return VGroup()
799 def get_col_labels(self) -> VGroup:
800 """The table's column labels, from left to right.
802 Returns:
803 A new group of the labels; empty if there are none.
804 """
805 if self.col_labels is not None:
806 return VGroup(*self.col_labels)
807 return VGroup()
809 def get_labels(self) -> VGroup:
810 """The table's labels: its top left entry, if it has one, then its column
811 labels, then its row labels.
813 Returns:
814 A new group of the labels; empty if there are none.
816 Examples:
817 ```python
818 import manimgx as m
821 class TableGetLabelsExample(m.Scene):
822 def construct(self) -> None:
823 table = m.Table(
824 [["First", "Second"], ["Third", "Fourth"]],
825 row_labels=[m.Text("R1"), m.Text("R2")],
826 col_labels=[m.Text("C1"), m.Text("C2")],
827 )
828 self.add(table)
829 self.play(table.get_labels().animate.set_color(m.YELLOW))
830 ```
831 """
832 label_group = VGroup()
833 if self.top_left_entry is not None:
834 label_group.add(self.top_left_entry)
835 for label in (self.col_labels, self.row_labels):
836 if label is not None:
837 label_group.add(*label)
838 return label_group
840 def add_background_to_entries(self, color: ParsableManimColor = BLACK) -> Self:
841 """Put a background rectangle behind each entry, labels included (see
842 [add_background_rectangle][manimgx.Mobject.add_background_rectangle]).
844 The rectangles are the entries' `background_rectangle`s:
845 [create][manimgx.Table.create] fades in those of the entries but the labels.
847 Args:
848 color: The rectangles' color.
849 """
850 for mob in self.get_entries():
851 mob.add_background_rectangle(color=ManimColor(color))
852 return self
854 def get_cell(self, pos: Sequence[int] = (1, 1), **kwargs: Unpack[Style]) -> Polygon:
855 """Make the rectangle of a cell: its row's height and its column's width,
856 reaching half a gap beyond them on every side, so that it meets the lines;
857 blue unless styled.
859 The gaps are `v_buff` and `h_buff`, as the table was made: on a table scaled
860 since, the rectangle reaches as far beyond the entries as before.
862 Args:
863 pos: The cell's position, `(row, column)`, counted from 1 at the top left,
864 labels included.
865 **kwargs: [Style keywords][manimgx.drawing.paint.Style].
867 Returns:
868 A new [Polygon][manimgx.Polygon], not added to the table.
870 Examples:
871 ```python
872 import manimgx as m
875 class TableGetCellExample(m.Scene):
876 def construct(self) -> None:
877 table = m.Table(
878 [["First", "Second"], ["Third", "Fourth"]],
879 row_labels=[m.Text("R1"), m.Text("R2")],
880 col_labels=[m.Text("C1"), m.Text("C2")],
881 )
882 self.add(table)
883 self.play(m.Create(table.get_cell((2, 2), color=m.RED)))
884 ```
885 """
886 row = list(self.cells[pos[0] - 1])
887 col = [row[pos[1] - 1] for row in self.cells]
888 across = _family_box(_family(col)) # (the column's box: the cell's sides)
889 down = _family_box(_family(row)) # (the row's box: its top and bottom)
890 if across is None:
891 across = np.zeros((2, 3))
892 if down is None:
893 down = np.zeros((2, 3))
894 left = across[0, 0] - self.h_buff / 2
895 right = across[1, 0] + self.h_buff / 2
896 bottom = down[0, 1] - self.v_buff / 2
897 top = down[1, 1] + self.v_buff / 2
898 return Polygon(
899 [left, top, 0],
900 [right, top, 0],
901 [right, bottom, 0],
902 [left, bottom, 0],
903 **kwargs,
904 )
906 def get_highlighted_cell(
907 self,
908 pos: Sequence[int] = (1, 1),
909 **kwargs: Unpack[FrameOptions],
910 ) -> BackgroundRectangle:
911 """Make a highlight for a cell: a
912 [BackgroundRectangle][manimgx.BackgroundRectangle] over the
913 [cell's rectangle][manimgx.Table.get_cell], bright yellow (`PURE_YELLOW`) unless
914 given a color.
916 It is not added to the table: put it behind the entries, as
917 [add_highlighted_cell][manimgx.Table.add_highlighted_cell] does.
919 Args:
920 pos: The cell's position, `(row, column)`, counted from 1 at the top left,
921 labels included.
922 **kwargs: [Frame keywords][manimgx.mobjects.annotations.FrameOptions]:
923 its `color`, `buff`, `fill_opacity`, ….
925 Returns:
926 A new background rectangle.
927 """
928 if kwargs.get("color") is None: # not given, None too
929 kwargs["color"] = PURE_YELLOW
930 bg_cell = BackgroundRectangle(self.get_cell(pos), **kwargs)
931 return bg_cell
933 def add_highlighted_cell(
934 self,
935 pos: Sequence[int] = (1, 1),
936 **kwargs: Unpack[FrameOptions],
937 ) -> Self:
938 """Highlight a cell: put a [highlight][manimgx.Table.get_highlighted_cell]
939 behind everything in the table.
941 The highlight is the `background_rectangle` of the entry at `pos`:
942 [create][manimgx.Table.create] fades it in, unless the entry is a label.
944 Args:
945 pos: The cell's position, `(row, column)`, counted from 1 at the top left,
946 labels included.
947 **kwargs: [Frame keywords][manimgx.mobjects.annotations.FrameOptions]:
948 its `color`, `buff`, `fill_opacity`, ….
950 Examples:
951 ```python
952 import manimgx as m
955 class TableAddHighlightedCellExample(m.Scene):
956 def construct(self) -> None:
957 table = m.Table(
958 [["First", "Second"], ["Third", "Fourth"]],
959 row_labels=[m.Text("R1"), m.Text("R2")],
960 col_labels=[m.Text("C1"), m.Text("C2")],
961 )
962 table.add_highlighted_cell((2, 2), color=m.GREEN)
963 self.add(table)
964 ```
965 """
966 bg_cell = self.get_highlighted_cell(pos, **kwargs)
967 self.add_to_back(bg_cell)
968 entry = self.get_entries(pos)
969 entry.background_rectangle = bg_cell
970 return self
972 def create(
973 self,
974 line_animation: Callable[..., Animation] = Create,
975 label_animation: Callable[..., Animation] = Write,
976 element_animation: Callable[..., Animation] = Create,
977 entry_animation: Callable[..., Animation] = FadeIn,
978 **kwargs: Unpack[AnimationOptions],
979 ) -> AnimationGroup:
980 """Make an animation that builds the table: its lines, then its entries, then
981 its labels, then each entry's background rectangle, one after another.
983 Each part is its own animation, made with the options given; the parts follow
984 one another by `lag_ratio`, 1 unless given. The entries but the labels are
985 moved to a z-index of 2, over backgrounds and highlights.
987 Args:
988 line_animation: The animation that draws the lines.
989 label_animation: The animation that draws the labels.
990 element_animation: The animation that draws the entries but the labels.
991 entry_animation: The animation that brings in each entry's background
992 rectangle (the highlights of
993 [add_highlighted_cell][manimgx.Table.add_highlighted_cell]).
994 **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions]
995 for each part (`run_time` is each part's), and `lag_ratio` for the
996 whole: 1 plays the parts one after another, 0 all at once.
998 Returns:
999 A new animation group.
1001 Examples:
1002 ```python
1003 import manimgx as m
1006 class TableCreateExample(m.Scene):
1007 def construct(self) -> None:
1008 table = m.Table(
1009 [["First", "Second"], ["Third", "Fourth"]],
1010 row_labels=[m.Text("R1"), m.Text("R2")],
1011 col_labels=[m.Text("C1"), m.Text("C2")],
1012 include_outer_lines=True,
1013 )
1014 table.add_highlighted_cell((2, 2), color=m.GREEN)
1015 self.play(table.create())
1016 ```
1017 """
1018 # the parts: lines, entries, labels (if any), then the entries' backgrounds;
1019 # the other options go to each part
1020 lag_ratio = kwargs.pop("lag_ratio", 1)
1021 animations: list[Animation] = [
1022 line_animation(
1023 VGroup(self.vertical_lines, self.horizontal_lines), **kwargs
1024 ),
1025 element_animation(self.elements_without_labels.set_z_index(2), **kwargs),
1026 ]
1027 if self.get_labels():
1028 animations += [label_animation(self.get_labels(), **kwargs)]
1029 if self.get_entries():
1030 for entry in self.elements_without_labels:
1031 if entry.background_rectangle is not None:
1032 animations.append(
1033 entry_animation(entry.background_rectangle, **kwargs)
1034 )
1035 return AnimationGroup(*animations, lag_ratio=lag_ratio)
1038class MathTable(Table):
1039 """A table of math: each entry typeset as math, with [MathTex][manimgx.MathTex].
1041 It takes a [Table][manimgx.Table]'s arguments; its entries are strings of math, or
1042 numbers, and its `element_to_mobject_config` gives their
1043 [math keywords][manimgx.MathTex].
1045 Examples:
1046 ```python
1047 import manimgx as m
1050 class MathTableExample(m.Scene):
1051 def construct(self) -> None:
1052 table = m.MathTable(
1053 [["+", 0, 5, 10], [0, 0, 5, 10], [2, 2, 7, 12], [4, 4, 9, 14]],
1054 include_outer_lines=True,
1055 )
1056 self.add(table)
1057 ```
1058 """
1060 entry = MathTex
1063class MobjectTable(Table):
1064 """A table of mobjects: each entry a mobject, placed as it is.
1066 It takes a [Table][manimgx.Table]'s arguments; its entries are mobjects, used
1067 themselves (not copied).
1069 Examples:
1070 ```python
1071 import manimgx as m
1074 class MobjectTableExample(m.Scene):
1075 def construct(self) -> None:
1076 def o() -> m.Circle:
1077 return m.Circle(radius=0.45, color=m.RED)
1079 def x() -> m.VGroup:
1080 cross = m.VGroup(m.Line(m.UL, m.DR), m.Line(m.UR, m.DL))
1081 return cross.scale(0.45).set_color(m.BLUE)
1083 table = m.MobjectTable(
1084 [[o(), x(), o()], [x(), o(), o()], [o(), x(), x()]]
1085 )
1086 self.add(table)
1087 ```
1088 """
1090 entry = staticmethod(_same)
1093class IntegerTable(Table):
1094 r"""A table of integers: each entry written as an [Integer][manimgx.Integer], its
1095 number rounded to a whole number.
1097 It takes a [Table][manimgx.Table]'s arguments; its entries are numbers, and its
1098 `element_to_mobject_config` gives their
1099 [number keywords][manimgx.DecimalNumber].
1101 Examples:
1102 ```python
1103 import manimgx as m
1106 class IntegerTableExample(m.Scene):
1107 def construct(self) -> None:
1108 table = m.IntegerTable(
1109 [[0, 30, 45, 60, 90], [90, 60, 45, 30, 0]],
1110 row_labels=[m.MathTex(r"\alpha"), m.MathTex(r"90^\circ - \alpha")],
1111 h_buff=1,
1112 element_to_mobject_config={"unit": r"^\circ"},
1113 )
1114 self.add(table)
1115 ```
1116 """
1118 entry = Integer
1121class DecimalTable(Table):
1122 """A table of decimal numbers: each entry written as a
1123 [DecimalNumber][manimgx.DecimalNumber], with one decimal place unless configured.
1125 It takes a [Table][manimgx.Table]'s arguments; its entries are numbers, and its
1126 `element_to_mobject_config` gives their
1127 [number keywords][manimgx.DecimalNumber], in place of
1128 `{"num_decimal_places": 1}`.
1130 Examples:
1131 ```python
1132 import numpy as np
1134 import manimgx as m
1137 class DecimalTableExample(m.Scene):
1138 def construct(self) -> None:
1139 xs = [-2, -1, 0, 1, 2]
1140 table = m.DecimalTable(
1141 [xs, np.exp(xs)],
1142 row_labels=[m.MathTex("x"), m.MathTex("e^x")],
1143 h_buff=1,
1144 element_to_mobject_config={"num_decimal_places": 2},
1145 )
1146 self.add(table)
1147 ```
1148 """
1150 entry = DecimalNumber
1151 entry_config: ClassVar[Mapping[str, object]] = {"num_decimal_places": 1}