
    lj[N                    6   d Z ddlmZ g dZddlZddlmZmZm	Z	 ddl
mZmZ ddlZddlmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlT ddlmZmZ d'dZd(dZ G d dee          Z G d de          Z  G d de          Z! G d de          Z"	 	 	 d)d*d&Z#dS )+ax  Mobjects representing matrices.

Examples
--------

.. manim:: MatrixExamples
    :save_last_frame:

    class MatrixExamples(Scene):
        def construct(self):
            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=r"\{",
                right_bracket=r"\}")
            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)
    )annotations)MatrixDecimalMatrixIntegerMatrixMobjectMatrixmatrix_to_tex_stringmatrix_to_mobjectget_det_textN)CallableIterableSequence)AnySelf)Mobject)ConvertToOpenGL)DecimalNumberInteger)MathTexTex   )*)VGroupVMobjectmatrix
np.ndarrayreturnstrc                   t          j        |                               d          } | j        dk    r|                     | j        df          } | j        \  }}dd|z  z  }d}d | D             }|d                    |          z   |z   S )Nr      z\left[ \begin{array}{%s}cz\end{array} \right]c                8    g | ]}d                      |          S )z & )join.0rows     O/home/agentuser/manim-venv/lib/python3.11/site-packages/manim/mobject/matrix.py
<listcomp>z(matrix_to_tex_string.<locals>.<listcomp>C   s"    ...EJJsOO...    z \\ )nparrayastypendimreshapesizeshaper"   )r   n_rowsn_colsprefixsuffixrowss         r&   r   r   <   s    Xf$$U++F{aa 011\NFF)S6\:F$F..v...DHMM$'''&00r(   r   c                :    t          t          |                     S N)r   r   )r   s    r&   r	   r	   G   s    '//000r(   c                       e Zd ZdZddeeddei edddi fd3 fdZd4d#Zd5d%Z	d6d7d(Z
d8d*Zd9d,Zd8d-Zd9d.Zd:d/Zd;d0Zd8d1Zd8d2Z xZS )<r   a  A mobject that displays a matrix on the screen.

    Parameters
    ----------
    matrix
        A numpy 2d array or list of lists.
    v_buff
        Vertical distance between elements, by default 0.8.
    h_buff
        Horizontal distance between elements, by default 1.3.
    bracket_h_buff
        Distance of the brackets from the matrix, by default ``MED_SMALL_BUFF``.
    bracket_v_buff
        Height of the brackets, by default ``MED_SMALL_BUFF``.
    add_background_rectangles_to_entries
        ``True`` if should add backgraound rectangles to entries, by default ``False``.
    include_background_rectangle
        ``True`` if should include background rectangle, by default ``False``.
    element_to_mobject
        The mobject class used to construct the elements, by default :class:`~.MathTex`.
    element_to_mobject_config
        Additional arguments to be passed to the constructor in ``element_to_mobject``,
        by default ``{}``.
    element_alignment_corner
        The corner to which elements are aligned, by default ``DR``.
    left_bracket
        The left bracket type, by default ``"["``.
    right_bracket
        The right bracket type, by default ``"]"``.
    stretch_brackets
        ``True`` if should stretch the brackets to fit the height of matrix contents, by default ``True``.
    bracket_config
        Additional arguments to be passed to :class:`~.MathTex` when constructing
        the brackets.

    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, r"\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=r"\{",
                    right_bracket=r"\}")
                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=r"\langle",
                    right_bracket=r"\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)
    g?g?F[]Tr   r   v_bufffloath_buffbracket_h_buffbracket_v_buff$add_background_rectangles_to_entriesboolinclude_background_rectangleelement_to_mobject&type[Mobject] | Callable[..., Mobject]element_to_mobject_configdictelement_alignment_cornerSequence[float]left_bracketr   right_bracketstretch_bracketsbracket_configkwargsr   c                   || _         || _        || _        || _        || _        || _        || _        |	| _        |
| _        || _	        || _
        || _         t                      j        di | |                     |          }|                     |           t!          t#          j        |  | _        |                     | j                    | j        | j	        | j
        fi | |                                  || _        | j        r| j        D ]}|                                 | j        r|                                  d S d S )N )r:   r<   r=   r>   r?   rA   rB   rD   rF   rH   rI   rJ   super__init___matrix_to_mob_matrix_organize_mob_matrixr   itchainelementsadd_add_bracketscenter
mob_matrixadd_background_rectangle)selfr   r:   r<   r=   r>   r?   rA   rB   rD   rF   rH   rI   rJ   rK   rL   rY   mob	__class__s                     r&   rP   zMatrix.__init__   sc   $ ,,4X1,H)"4)B&(@%(* 0""6"""//77
!!*---* 564,d.@SSNSSS$4 	/} / /,,...., 	,))+++++	, 	,r(   r   r   list[list[Mobject]]c                       fd|D             S )Nc                ,    g | ]}fd |D             S )c                6    g | ]} j         |fi j        S rN   rB   rD   )r$   itemr[   s     r&   r'   z;Matrix._matrix_to_mob_matrix.<locals>.<listcomp>.<listcomp>   sA        ('OO0NOO  r(   rN   )r$   r%   r[   s     r&   r'   z0Matrix._matrix_to_mob_matrix.<locals>.<listcomp>   sL     
 
 

 	     
 
 
r(   rN   )r[   r   s   ` r&   rQ   zMatrix._matrix_to_mob_matrix   s0    
 
 
 

 
 
 
 	
r(   r   c                    t          |          D ]f\  }}t          |          D ]Q\  }}||         |         }|                    || j        z  t          z  || j        z  t
          z  z   | j                   Rg| S r6   )	enumeratemove_tor:   DOWNr<   RIGHTrF   )r[   r   ir%   j_r\   s          r&   rR   zMatrix._organize_mob_matrix   s    '' 	 	FAs!#  1QilOd*Q_u-DD1    r(   leftrightc                P   d}t          | j        |z            dz   }d                    dg|dgz  d          }d                    d|z   |dg          }d                    d	|d
|z   g          }t          |fi |}	t          |fi |}
t	          |	|
          }| j        r%|                    | j        d| j        z  z              |	                    | t          | j
                   |
                    | t          | j
                   || _        |                     |	|
           | S )al  Adds the brackets to the Matrix mobject.

        See Latex document for various bracket types.

        Parameters
        ----------
        left
            the left bracket, by default "["
        right
            the right bracket, by default "]"

        Returns
        -------
        :class:`Matrix`
            The current matrix object (self).
        g6[ ?r    z\begin{array}{c}z\quad \\z\end{array}z\leftz\right.z\left.z\rightr   )intheightr"   r   r   rJ   stretch_to_fit_heightr>   next_toLEFTr=   rh   bracketsrV   )r[   rl   rm   rL   BRACKET_HEIGHTnempty_tex_arraytex_left	tex_right	l_bracket	r_bracketbracket_pairs               r&   rW   zMatrix._add_brackets   se   $  .//!3''#k]" 
 
 774
 
 GGE!
 
	 H////	I0000	i33  	V..t{QAT=T/TUUU$d&9:::$t':;;;$I&&&r(   r   c           	     x     t           fdt          t           j        d                             D              S )a  Return columns of the matrix as VGroups.

        Returns
        --------
        :class:`~.VGroup`
            The VGroup contains a nested VGroup for each column of the matrix.

        Examples
        --------

        .. manim:: GetColumnsExample
            :save_last_frame:

            class GetColumnsExample(Scene):
                def construct(self):
                    m0 = Matrix([[r"\pi", 3], [1, 5]])
                    m0.add(SurroundingRectangle(m0.get_columns()[1]))
                    self.add(m0)
        c              3  N   K   | ]t          fd j        D              V  dS )c              3  (   K   | ]}|         V  d S r6   rN   )r$   r%   ri   s     r&   	<genexpr>z/Matrix.get_columns.<locals>.<genexpr>.<genexpr>0  s'      ;;CQ;;;;;;r(   Nr   rY   )r$   ri   r[   s    @r&   r   z%Matrix.get_columns.<locals>.<genexpr>/  sT         ;;;;4?;;;<     r(   r   )r   rangelenrY   r[   s   `r&   get_columnszMatrix.get_columns  sO    (    s4?1#56677  
 	
r(   colorsc                    |                                  }t          ||d          D ]\  }}|                    |           | S )a  Set individual colors for each columns of the matrix.

        Parameters
        ----------
        colors
            The list of colors; each color specified corresponds to a column.

        Returns
        -------
        :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)
        Fstrict)r   zip	set_color)r[   r   columnscolorcolumns        r&   set_column_colorszMatrix.set_column_colors5  sS    2 ""$$ ??? 	$ 	$ME6U####r(   c                2    t          d | j        D              S )a  Return rows of the matrix as VGroups.

        Returns
        --------
        :class:`~.VGroup`
            The VGroup contains a nested VGroup for each 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)
        c              3  (   K   | ]}t          | V  d S r6   )r   r#   s     r&   r   z"Matrix.get_rows.<locals>.<genexpr>g  s&      @@@@@@@@r(   r   r   s    r&   get_rowszMatrix.get_rowsS  s     ( @@@@@AAr(   c                    |                                  }t          ||d          D ]\  }}|                    |           | S )ap  Set individual colors for each row of the matrix.

        Parameters
        ----------
        colors
            The list of colors; each color specified corresponds to a row.

        Returns
        -------
        :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)
        Fr   )r   r   r   )r[   r   r4   r   r%   s        r&   set_row_colorszMatrix.set_row_colorsi  sM    2 }}fd5999 	! 	!JE3MM%    r(   c                \    |                                  D ]}|                                 | S )zAdd a black background rectangle to the matrix,
        see above for an example.

        Returns
        -------
        :class:`Matrix`
            The current matrix object (self).
        )get_entriesrZ   )r[   r\   s     r&   add_background_to_entriesz Matrix.add_background_to_entries  s9     ##%% 	+ 	+C((****r(   c                    | j         S )zReturn the underlying mob matrix mobjects.

        Returns
        --------
        List[:class:`~.VGroup`]
            Each VGroup contains a row of the matrix.
        )rY   r   s    r&   get_mob_matrixzMatrix.get_mob_matrix  s     r(   c                    | j         S )az  Return the individual entries of the matrix.

        Returns
        --------
        :class:`~.VGroup`
            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)
        )rU   r   s    r&   r   zMatrix.get_entries      . }r(   c                    | j         S )al  Return the bracket mobjects.

        Returns
        --------
        :class:`~.VGroup`
            A VGroup containing the left and right 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)
        )ru   r   s    r&   get_bracketszMatrix.get_brackets  r   r(   )r   r   r:   r;   r<   r;   r=   r;   r>   r;   r?   r@   rA   r@   rB   rC   rD   rE   rF   rG   rH   r   rI   r   rJ   r@   rK   rE   rL   r   )r   r   r   r^   )r   r^   r   r   )r8   r9   )rl   r   rm   r   rL   r   r   r   )r   r   )r   r   r   r   )r   r   )r   r^   )__name__
__module____qualname____doc__MED_SMALL_BUFFr   DRrP   rQ   rR   rW   r   r   r   r   r   r   r   r   __classcell__r]   s   @r&   r   r   K   s_       W Wx  . .5:-2EL*,46 !%!*, *, *, *, *, *, *,X
 
 
 
   4 4 4 4 4l
 
 
 
6   <B B B B,   <         2       r(   r   )	metaclassc                  .     e Zd ZdZeddifd fdZ xZS )r   a   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)
    num_decimal_placesr   r   r   rB   type[Mobject]rD   dict[str, Any]rL   r   c                B     t                      j        |f||d| dS )a{  
        Will round/truncate the decimal places as per the provided config.

        Parameters
        ----------
        matrix
            A numpy 2d array or list of lists
        element_to_mobject
            Mobject to use, by default DecimalNumber
        element_to_mobject_config
            Config for the desired mobject, by default {"num_decimal_places": 1}
        rb   NrO   rP   )r[   r   rB   rD   rL   r]   s        r&   rP   zDecimalMatrix.__init__  sG    & 		
1&?	
 	
 		
 	
 	
 	
 	
r(   )r   r   rB   r   rD   r   rL   r   )r   r   r   r   r   rP   r   r   s   @r&   r   r     sY         * -:5I14M	
 
 
 
 
 
 
 
 
 
 
r(   r   c                  (     e Zd ZdZefd	 fdZ xZS )
r   a  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)
    r   r   rB   r   rL   r   c                @     t                      j        |fd|i| dS )z
        Will round if there are decimal entries in the matrix.

        Parameters
        ----------
        matrix
            A numpy 2d array or list of lists
        element_to_mobject
            Mobject to use, by default Integer
        rB   Nr   r[   r   rB   rL   r]   s       r&   rP   zIntegerMatrix.__init__  s0      	QQ4FQ&QQQQQr(   )r   r   rB   r   rL   r   )r   r   r   r   r   rP   r   r   s   @r&   r   r     s\         ( -4R R R R R R R R R R Rr(   r   c                  *     e Zd ZdZd fd
 fd	Z xZS )r   a  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)
    c                    | S r6   rN   )ms    r&   <lambda>zMobjectMatrix.<lambda>:  s    q r(   r   r   rB   rC   rL   r   c                @     t                      j        |fd|i| d S )NrB   r   r   s       r&   rP   zMobjectMatrix.__init__7  s0     	QQ4FQ&QQQQQr(   )r   r   rB   rC   rL   r   )r   r   r   r   rP   r   r   s   @r&   r   r   $  s`         * FQ[R R R R R R R R R R Rr(   r   Fdeterminantint | str | Nonebackground_rectr@   initial_scale_factorr;   r   c                   t          dd          }|                    |           |                    | j                   |                                \  }}|                    | t          d           |                    | t          d           t          d          }|                    |           |                    |t          d           |r|	                                 t          |||          }|{t          d          }	|	                    |t          d           t          t          |                    }
|
                    |	t          d           |                    |	|
           |S )	a  Helper function to create determinant.

    Parameters
    ----------
    matrix
        The matrix whose determinant is to be created

    determinant
        The value of the determinant of the matrix

    background_rect
        The background rectangle

    initial_scale_factor
        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)
    ()g?)buffdetN=g?)r   scalerr   rq   splitrs   rt   rh   r   rZ   r   r   rV   )r   r   r   r   parensl_parenr_parenr   det_texteqresults              r&   r
   r
   @  sO   b S#F
LL%&&&
  ///||~~GWOOFDsO+++OOFEO,,,
e**CII"###KKCK((( '$$&&&c7G,,HS\\


7E
,,,[))**r5s+++R   Or(   )r   r   r   r   )r   r   r   r   )NFr   )
r   r   r   r   r   r@   r   r;   r   r   )$r   
__future__r   __all__	itertoolsrS   collections.abcr   r   r   typingr   r   numpyr)   manim.mobject.mobjectr   )manim.mobject.opengl.opengl_compatibilityr   manim.mobject.text.numbersr   r   manim.mobject.text.tex_mobjectr   r   	constants mobject.types.vectorized_mobjectr   r   r   r	   r   r   r   r   r
   rN   r(   r&   <module>r      s$   8 # " " " " "       8 8 8 8 8 8 8 8 8 8             ) ) ) ) ) ) E E E E E E = = = = = = = = 7 7 7 7 7 7 7 7     ? ? ? ? ? ? ? ?1 1 1 11 1 1 1C C C C CX C C C CL+
 +
 +
 +
 +
F +
 +
 +
\"R "R "R "R "RF "R "R "RJR R R R RF R R R< %)!"#	C C C C C C Cr(   