A community-maintained Python framework for creating mathematical animations.
Fixed bugs and added examples to methods and classes in matrix.py (#1636)
Olivera6f246738871
diff --git a/manim/mobject/matrix.py b/manim/mobject/matrix.pyindex f6b32567a..b4562794e 100644--- a/manim/mobject/matrix.py+++ b/manim/mobject/matrix.py@@ -8,20 +8,22 @@ Examplesclass MatrixExamples(Scene):def construct(self):- m0 = Matrix([[2, 0], [-1, 1]])- m1 = Matrix([[1, 0], [0, 1]],- left_bracket="\\big(",- right_bracket="\\big)")+ m0 = Matrix([["\\pi", 0], [-1, 1]])+ m1 = IntegerMatrix([[1.5, 0.], [12, -1.3]],+ left_bracket="(",+ right_bracket=")")m2 = DecimalMatrix([[3.456, 2.122], [33.2244, 12.33]],element_to_mobject_config={"num_decimal_places": 2},left_bracket="\\{",right_bracket="\\}")-- self.add(m0.shift(LEFT - (3, 0, 0)))- self.add(m1)- self.add(m2.shift(RIGHT + (3, 0, 0)))-+ m3 = MobjectMatrix(+ [[Circle().scale(0.3), Square().scale(0.3)],+ [MathTex("\\pi").scale(2), Star().scale(0.3)]],+ left_bracket="\\langle",+ right_bracket="\\rangle")+ g = Group(m0, m1, m2, m3).arrange_in_grid(buff=2)+ self.add(g)"""__all__ = [@@ -35,6 +37,8 @@ __all__ = []+import itertools as it+import numpy as npfrom ..constants import *@@ -44,6 +48,9 @@ from ..mobject.svg.tex_mobject import MathTex, Texfrom ..mobject.types.vectorized_mobject import VGroup, VMobjectfrom ..utils.color import WHITE+# TO DO : The following two functions are not used in this file.+# Not sure if we should keep it or not.+def matrix_to_tex_string(matrix):matrix = np.array(matrix).astype("str")@@ -61,7 +68,61 @@ def matrix_to_mobject(matrix):class Matrix(VMobject):- """A mobject that displays a matrix on the screen."""+ """A mobject that displays a matrix on the screen.++ Examples+ --------+ The first example shows a variety of uses of this module while the second example+ exlpains the use of the options `add_background_rectangles_to_entries` and+ `include_background_rectangle`.++ .. manim:: MatrixExamples+ :save_last_frame:++ class MatrixExamples(Scene):+ def construct(self):+ m0 = Matrix([[2, "\\pi"], [-1, 1]])+ m1 = Matrix([[2, 0, 4], [-1, 1, 5]],+ v_buff=1.3,+ h_buff=0.8,+ bracket_h_buff=SMALL_BUFF,+ bracket_v_buff=SMALL_BUFF,+ left_bracket="\\{",+ right_bracket="\\}")+ m1.add(SurroundingRectangle(m1.get_columns()[1]))+ m2 = Matrix([[2, 1], [-1, 3]],+ element_alignment_corner=UL,+ left_bracket="(",+ right_bracket=")")+ m3 = Matrix([[2, 1], [-1, 3]],+ left_bracket="\\\\langle",+ right_bracket="\\\\rangle")+ m4 = Matrix([[2, 1], [-1, 3]],+ ).set_column_colors(RED, GREEN)+ m5 = Matrix([[2, 1], [-1, 3]],+ ).set_row_colors(RED, GREEN)+ g = Group(+ m0,m1,m2,m3,m4,m5+ ).arrange_in_grid(buff=2)+ self.add(g)++ .. manim:: BackgroundRectanglesExample+ :save_last_frame:++ class BackgroundRectanglesExample(Scene):+ def construct(self):+ background= Rectangle().scale(3.2)+ background.set_fill(opacity=.5)+ background.set_color([TEAL, RED, YELLOW])+ self.add(background)+ m0 = Matrix([[12, -30], [-1, 15]],+ add_background_rectangles_to_entries=True)+ m1 = Matrix([[2, 0], [-1, 1]],+ include_background_rectangle=True)+ m2 = Matrix([[12, -30], [-1, 15]])+ g = Group(m0, m1, m2).arrange(buff=2)+ self.add(g)+ """def __init__(self,@@ -75,8 +136,8 @@ class Matrix(VMobject):element_to_mobject=MathTex,element_to_mobject_config={},element_alignment_corner=DR,- left_bracket="\\big[",- right_bracket="\\big]",+ left_bracket="[",+ right_bracket="]",**kwargs,):"""@@ -104,9 +165,9 @@ class Matrix(VMobject):element_alignment_corner : :class:`np.ndarray`, optionalthe element alignment corner, by default DRleft_bracket : :class:`str`, optional- the left bracket type, by default "\\\\big["+ the left bracket type, by default "["right_bracket : :class:`str`, optional- the right bracket type, by default "\\\\big]"+ the right bracket type, by default "]""""@@ -122,14 +183,9 @@ class Matrix(VMobject):self.left_bracket = left_bracketself.right_bracket = right_bracketVMobject.__init__(self, **kwargs)- matrix = np.array(matrix)- if len(matrix.shape) < 2:- raise ValueError(- f"{self.__str__()} class requires a two-dimensional array!"- )mob_matrix = self.matrix_to_mob_matrix(matrix)self.organize_mob_matrix(mob_matrix)- self.elements = VGroup(*mob_matrix.flatten())+ self.elements = VGroup(*it.chain(*mob_matrix))self.add(self.elements)self.add_brackets(self.left_bracket, self.right_bracket)self.center()@@ -141,11 +197,17 @@ class Matrix(VMobject):self.add_background_rectangle()def matrix_to_mob_matrix(self, matrix):- return np.vectorize(self.element_to_mobject)(- matrix, **self.element_to_mobject_config- )+ """Used internally."""+ return [+ [+ self.element_to_mobject(item, **self.element_to_mobject_config)+ for item in row+ ]+ for row in matrix+ ]def organize_mob_matrix(self, matrix):+ """Used internally."""for i, row in enumerate(matrix):for j, _ in enumerate(row):mob = matrix[i][j]@@ -155,17 +217,17 @@ class Matrix(VMobject):)return self- def add_brackets(self, left="\\big[", right="\\big]"):- """Add the brackets to the Matrix mobject+ def add_brackets(self, left="[", right="]"):+ """Used internally. Adds the brackets to the Matrix mobject.See Latex document for various bracket types.Parameters----------left : :class:`str`, optional- the left bracket, by default "\\\\big["+ the left bracket, by default "["right : :class:`str`, optional- the right bracket, by default "\\\\big]"+ the right bracket, by default "]"Returns-------@@ -184,19 +246,35 @@ class Matrix(VMobject):return selfdef get_columns(self):- """Return columns of the matrix as VGroups+ """Return columns of the matrix as VGroups.Returns--------List[:class:`~.VGroup`]Each VGroup contains a column of the matrix.++ Examples+ --------++ .. manim:: GetColumnsExample+ :save_last_frame:++ class GetColumnsExample(Scene):+ def construct(self):+ m0 = Matrix([["\\pi", 3], [1, 5]])+ m0.add(SurroundingRectangle(m0.get_columns()[1]))+ self.add(m0)"""+return VGroup(- *[VGroup(*self.mob_matrix[:, i]) for i in range(self.mob_matrix.shape[1])]+ *[+ VGroup(*[row[i] for row in self.mob_matrix])+ for i in range(len(self.mob_matrix[0]))+ ])def set_column_colors(self, *colors):- """Set individual colors for each columns of the matrix+ """Set individual colors for each columns of the matrix.Parameters----------@@ -207,6 +285,18 @@ class Matrix(VMobject):-------:class:`Matrix`The current matrix object (self).++ Examples+ --------++ .. manim:: SetColumnColorsExample+ :save_last_frame:++ class SetColumnColorsExample(Scene):+ def construct(self):+ m0 = Matrix([["\\pi", 1], [-1, 3]],+ ).set_column_colors([RED,BLUE], GREEN)+ self.add(m0)"""columns = self.get_columns()for color, column in zip(colors, columns):@@ -214,19 +304,29 @@ class Matrix(VMobject):return selfdef get_rows(self):- """Return rows of the matrix as VGroups+ """Return rows of the matrix as VGroups.Returns--------List[:class:`~.VGroup`]Each VGroup contains a row of the matrix.++ Examples+ --------++ .. manim:: GetRowsExample+ :save_last_frame:++ class GetRowsExample(Scene):+ def construct(self):+ m0 = Matrix([["\\pi", 3], [1, 5]])+ m0.add(SurroundingRectangle(m0.get_rows()[1]))+ self.add(m0)"""- return VGroup(- *[VGroup(*self.mob_matrix[i, :]) for i in range(self.mob_matrix.shape[0])]- )+ return VGroup(*[VGroup(*row) for row in self.mob_matrix])def set_row_colors(self, *colors):- """Set individual colors for each row of the matrix+ """Set individual colors for each row of the matrix.Parameters----------@@ -237,6 +337,18 @@ class Matrix(VMobject):-------:class:`Matrix`The current matrix object (self).++ Examples+ --------++ .. manim:: SetRowColorsExample+ :save_last_frame:++ class SetRowColorsExample(Scene):+ def construct(self):+ m0 = Matrix([["\\pi", 1], [-1, 3]],+ ).set_row_colors([RED,BLUE], GREEN)+ self.add(m0)"""rows = self.get_rows()for color, row in zip(colors, rows):@@ -244,12 +356,20 @@ class Matrix(VMobject):return selfdef add_background_to_entries(self):+ """Add a black background rectangle to the matrix,+ see above for an example.++ Returns+ -------+ :class:`Matrix`+ The current matrix object (self).+ """for mob in self.get_entries():mob.add_background_rectangle()return selfdef get_mob_matrix(self):- """Return the underlying mob matrix mobjects+ """Return the underlying mob matrix mobjects.Returns--------@@ -259,28 +379,74 @@ class Matrix(VMobject):return self.mob_matrixdef get_entries(self):- """Return the individual entries of the matrix+ """Return the individual entries of the matrix.Returns--------:class:`~.VGroup`- VGroup containing entries of the matrix+ VGroup containing entries of the matrix.++ Examples+ --------++ .. manim:: GetEntriesExample+ :save_last_frame:++ class GetEntriesExample(Scene):+ def construct(self):+ m0 = Matrix([[2, 3], [1, 5]])+ ent = m0.get_entries()+ colors = [BLUE, GREEN, YELLOW, RED]+ for k in range(len(colors)):+ ent[k].set_color(colors[k])+ self.add(m0)"""- return VGroup(*self.get_mob_matrix().flatten())+ return self.elementsdef get_brackets(self):- """Return the bracket mobjects+ """Return the bracket mobjects.Returns--------List[:class:`~.VGroup`]Each VGroup contains a bracket++ Examples+ --------++ .. manim:: GetBracketsExample+ :save_last_frame:++ class GetBracketsExample(Scene):+ def construct(self):+ m0 = Matrix([["\\pi", 3], [1, 5]])+ bra = m0.get_brackets()+ colors = [BLUE, GREEN]+ for k in range(len(colors)):+ bra[k].set_color(colors[k])+ self.add(m0)"""return self.bracketsclass DecimalMatrix(Matrix):- """A mobject that displays a matrix with decimal entries on the screen."""+ """A mobject that displays a matrix with decimal entries on the screen.++ Examples+ --------++ .. manim:: DecimalMatrixExample+ :save_last_frame:++ class DecimalMatrixExample(Scene):+ def construct(self):+ m0 = DecimalMatrix(+ [[3.456, 2.122], [33.2244, 12]],+ element_to_mobject_config={"num_decimal_places": 2},+ left_bracket="\\{",+ right_bracket="\\}")+ self.add(m0)+ """def __init__(self,@@ -311,11 +477,26 @@ class DecimalMatrix(Matrix):class IntegerMatrix(Matrix):- """A mobject that displays a matrix with integer entries on the screen."""+ """A mobject that displays a matrix with integer entries on the screen.++ Examples+ --------++ .. manim:: IntegerMatrixExample+ :save_last_frame:++ class IntegerMatrixExample(Scene):+ def construct(self):+ m0 = IntegerMatrix(+ [[3.7, 2], [42.2, 12]],+ left_bracket="(",+ right_bracket=")")+ self.add(m0)+ """def __init__(self, matrix, element_to_mobject=Integer, **kwargs):"""- Note- Will round if there are decimal entries in the matrix.+ Will round if there are decimal entries in the matrix.Parameters----------@@ -328,7 +509,23 @@ class IntegerMatrix(Matrix):class MobjectMatrix(Matrix):- """A mobject that displays a matrix of mobject entries on the screen."""+ """A mobject that displays a matrix of mobject entries on the screen.++ Examples+ --------++ .. manim:: MobjectMatrixExample+ :save_last_frame:++ class MobjectMatrixExample(Scene):+ def construct(self):+ a = Circle().scale(0.3)+ b = Square().scale(0.3)+ c = MathTex("\\pi").scale(2)+ d = Star().scale(0.3)+ m0 = MobjectMatrix([[a, b], [c, d]])+ self.add(m0)+ """def __init__(self, matrix, element_to_mobject=lambda m: m, **kwargs):Matrix.__init__(self, matrix, element_to_mobject=element_to_mobject, **kwargs)@@ -337,7 +534,7 @@ class MobjectMatrix(Matrix):def get_det_text(matrix, determinant=None, background_rect=False, initial_scale_factor=2):- r"""Helper function to create determinant+ r"""Helper function to create determinant.Parameters----------@@ -379,7 +576,6 @@ def get_det_text(# must add the matrixself.add(matrix)self.add(det)-"""parens = MathTex("(", ")")parens.scale(initial_scale_factor)