A community-maintained Python framework for creating mathematical animations.
add api docs and examples for Matrix mobjects (#1047)
Kapil Sachdeva7bfabe3919df
diff --git a/manim/mobject/matrix.py b/manim/mobject/matrix.pyindex 420ac9f1d..e80e4cc9c 100644--- a/manim/mobject/matrix.py+++ b/manim/mobject/matrix.py@@ -1,4 +1,28 @@-"""Mobjects representing matrices."""+r"""Mobjects representing matrices.++Examples+--------++.. manim:: MatrixExamples+ :save_last_frame:++ class MatrixExamples(Scene):+ def construct(self):+ m0 = Matrix([[2, 0], [-1, 1]])+ m1 = Matrix([[1, 0], [0, 1]],+ left_bracket="\\big(",+ right_bracket="\\big)")+ 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)))++"""__all__ = ["Matrix",@@ -64,6 +88,8 @@ def vector_coordinate_label(vector_mob, integer_labels=True, n_dim=2, color=WHITclass Matrix(VMobject):+ """A mobject that displays a matrix on the screen."""+def __init__(self,matrix,@@ -81,9 +107,36 @@ class Matrix(VMobject):**kwargs,):"""- Matrix can either either include numbers, tex_strings,- or mobjects++ Parameters+ ----------+ matrix : :class:`typing.Iterable`+ A numpy 2d array or list of lists+ v_buff : :class:`float`, optional+ vertical buffer, by default 0.8+ h_buff : :class:`float`, optional+ horizontal buffer, by default 1.3+ bracket_h_buff : :class:`float`, optional+ bracket horizonal buffer, by default MED_SMALL_BUFF+ bracket_v_buff : :class:`float`, optional+ bracket veritical buffer, by default MED_SMALL_BUFF+ add_background_rectangles_to_entries : :class:`bool`, optional+ `True` if should add backgraound rectangles to entries, by default False+ include_background_rectangle : :class:`bool`, optional+ `True` if should include background rectangle, by default False+ element_to_mobject : :class:`~.Mobject`, optional+ element to mobject, by default MathTex+ element_to_mobject_config : Dict[:class:`str`, :class:`~.Mobject`], optional+ element to mobject config, by default {}+ element_alignment_corner : :class:`np.ndarray`, optional+ the element alignment corner, by default DR+ left_bracket : :class:`str`, optional+ the left bracket type, by default "\\\\big["+ right_bracket : :class:`str`, optional+ the right bracket type, by default "\\\\big]"+"""+self.v_buff = v_buffself.h_buff = h_buffself.bracket_h_buff = bracket_h_buff@@ -121,7 +174,7 @@ class Matrix(VMobject):def organize_mob_matrix(self, matrix):for i, row in enumerate(matrix):- for j, elem in enumerate(row):+ for j, _ in enumerate(row):mob = matrix[i][j]mob.move_to(i * self.v_buff * DOWN + j * self.h_buff * RIGHT,@@ -130,6 +183,23 @@ class Matrix(VMobject):return selfdef add_brackets(self, left="\\big[", right="\\big]"):+ """Add the brackets to the Matrix mobject++ See Latex document for various bracket types.++ Parameters+ ----------+ left : :class:`str`, optional+ the left bracket, by default "\\\\big["+ right : :class:`str`, optional+ the right bracket, by default "\\\\big]"++ Returns+ -------+ :class:`Matrix`+ The current matrix object (self).+ """+bracket_pair = MathTex(left, right)bracket_pair.scale(2)bracket_pair.stretch_to_fit_height(self.height + 2 * self.bracket_v_buff)@@ -141,11 +211,30 @@ class Matrix(VMobject):return selfdef get_columns(self):+ """Return columns of the matrix as VGroups++ Returns+ --------+ List[:class:`~.VGroup`]+ Each VGroup contains a column of the matrix.+ """return VGroup(*[VGroup(*self.mob_matrix[:, i]) for i in range(self.mob_matrix.shape[1])])def set_column_colors(self, *colors):+ """Set individual colors for each columns of the matrix++ Parameters+ ----------+ colors : :class:`str`+ The list of colors; each color specified corresponds to a column.++ Returns+ -------+ :class:`Matrix`+ The current matrix object (self).+ """columns = self.get_columns()for color, column in zip(colors, columns):column.set_color(color)@@ -187,16 +276,39 @@ class Matrix(VMobject):return selfdef get_mob_matrix(self):+ """Return the underlying mob matrix mobjects++ Returns+ --------+ List[:class:`~.VGroup`]+ Each VGroup contains a row of the matrix.+ """return self.mob_matrixdef get_entries(self):+ """Return the individual entries of the matrix++ Returns+ --------+ :class:`~.VGroup`+ VGroup containing entries of the matrix+ """return VGroup(*self.get_mob_matrix().flatten())def get_brackets(self):+ """Return the bracket mobjects++ Returns+ --------+ List[:class:`~.VGroup`]+ Each VGroup contains a bracket+ """return self.bracketsclass DecimalMatrix(Matrix):+ """A mobject that displays a matrix with decimal entries on the screen."""+def __init__(self,matrix,@@ -204,6 +316,18 @@ class DecimalMatrix(Matrix):element_to_mobject_config={"num_decimal_places": 1},**kwargs,):+ """+ Will round/truncate the decimal places as per the provided config.++ Parameters+ ----------+ matrix : :class:`typing.Iterable`+ A numpy 2d array or list of lists+ element_to_mobject : :class:`~.Mobject`, optional+ Mobject to use, by default DecimalNumber+ element_to_mobject_config : Dict[:class:`str`, :class:`~.Mobject`], optional+ Config for the desired mobject, by default {"num_decimal_places": 1}+ """Matrix.__init__(self,matrix,@@ -214,11 +338,25 @@ class DecimalMatrix(Matrix):class IntegerMatrix(Matrix):+ """A mobject that displays a matrix with integer entries on the screen."""+def __init__(self, matrix, element_to_mobject=Integer, **kwargs):+ """+ Note- Will round if there are decimal entries in the matrix.++ Parameters+ ----------+ matrix : :class:`typing.Iterable`+ A numpy 2d array or list of lists+ element_to_mobject : :class:`~.Mobject`, optional+ Mobject to use, by default Integer+ """Matrix.__init__(self, matrix, element_to_mobject=element_to_mobject, **kwargs)class MobjectMatrix(Matrix):+ """A mobject that displays a matrix of mobject entries on the screen."""+def __init__(self, matrix, element_to_mobject=lambda m: m, **kwargs):Matrix.__init__(self, matrix, element_to_mobject=element_to_mobject, **kwargs)@@ -226,6 +364,50 @@ class MobjectMatrix(Matrix):def get_det_text(matrix, determinant=None, background_rect=False, initial_scale_factor=2):+ r"""Helper function to create determinant++ Parameters+ ----------+ matrix : :class:`~.Matrix`+ The matrix whose determinant is to be created++ determinant : :class:`int|str`+ The value of the determinant of the matrix++ background_rect : :class:`bool`+ The background rectangle++ initial_scale_factor : :class:`float`+ The scale of the text `det` w.r.t the matrix++ Returns+ --------+ :class:`~.VGroup`+ A VGroup containing the determinant++ Examples+ --------++ .. manim:: DeterminantOfAMatrix+ :save_last_frame:++ class DeterminantOfAMatrix(Scene):+ def construct(self):+ matrix = Matrix([+ [2, 0],+ [-1, 1]+ ])++ # scaling down the `det` string+ det = get_det_text(matrix,+ determinant=3,+ initial_scale_factor=1)++ # must add the matrix+ self.add(matrix)+ self.add(det)++ """parens = MathTex("(", ")")parens.scale(initial_scale_factor)parens.stretch_to_fit_height(matrix.height)