
    Ed>                        d dl mZmZ d dlmZ d dlmZmZmZ d dl	m
Z
mZ d dlmZmZ d dlmZ d dlmZ d dlmZmZmZmZmZmZmZ d d	lmZmZ d d
lmZ d dl m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z' ddl(m(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/  G d de%e          Z0 e
j1        ee0fe0           d Z2d Z3d Z4d Z5d Z6d Z7d Z8d Z9d Z:d Z;e;e4e6e:e8e ed           e5e7ee9fZ< e ee0 ee< i                    Z=d  Z>d! Z?e?ed<   d"S )#    )askQ)handlers_dict)BasicsympifyS)mulMul)NumberIntegerDummyadjoint)rm_idunpacktypedflattenexhaustdo_onenew)
ShapeErrorNonInvertibleMatrixError)
MatrixBase)sympy_deprecation_warning   )Inverse)
MatrixExpr)MatPow	transpose)PermutationMatrix)
ZeroMatrixIdentityGenericIdentity	OneMatrixc                        e Zd ZdZdZ e            ZdddddZed             Z	e
d             Zdd	Zd
 Zd Z fdZd Zd Zd Zd Zd Zd ZddZd Z xZS )MatMula  
    A product of matrix expressions

    Examples
    ========

    >>> from sympy import MatMul, MatrixSymbol
    >>> A = MatrixSymbol('A', 5, 4)
    >>> B = MatrixSymbol('B', 4, 3)
    >>> C = MatrixSymbol('C', 3, 6)
    >>> MatMul(A, B, C)
    A*B*C
    TFN)evaluatecheck_sympifyc                    |s j         S t          t           fd|                    }|r"t          t          t          |                    }t          j         g|R  }|                                \  }}|t          ddd           |dv r
t          |  nt          ddd           |s|S |r 
                    |          S |S )Nc                     j         | k    S N)identity)iclss    Alib/python3.11/site-packages/sympy/matrices/expressions/matmul.py<lambda>z MatMul.__new__.<locals>.<lambda>/   s    S\Q%6     zaPassing check to MatMul is deprecated and the check argument will be removed in a future version.z1.11z,remove-check-argument-from-matrix-operations)deprecated_since_versionactive_deprecations_target)TNzgPassing check=False to MatMul is deprecated and the check argument will be removed in a future version.)r/   listfiltermapr   r   __new__as_coeff_matricesr   validate	_evaluate)r1   r)   r*   r+   argsobjfactormatricess   `       r2   r:   zMatMul.__new__)   s!    	 < F6666==>> 	,GT**++DmC'$'''0022 	[%s)/+Y[ [ [ [
 L  	[h%y)/+Y[ [ [ [
  	 M 	&==%%%
r4   c                      t          |          S r.   )canonicalize)r1   exprs     r2   r=   zMatMul._evaluateN   s    D!!!r4   c                 X    d | j         D             }|d         j        |d         j        fS )Nc                      g | ]}|j         	|S  	is_Matrix.0args     r2   
<listcomp>z MatMul.shape.<locals>.<listcomp>T   s    >>>C>C>>>r4   r   )r>   rowscols)selfrA   s     r2   shapezMatMul.shapeR   s0    >>49>>> (2,"344r4   c                 t   ddl m} ddlm |                                 \  }}t          |          dk    r||d         ||f         z  S d gt          |          dz   z  d gt          |          dz
  z  }|d<   |d<   d }	|                    d |	                      t          dt          |                    D ]}t                    |<   t          |d d                   D ]\  }}
|
j
        d         dz
  ||<   fdt          |          D             }t          j        |          }t          fd	|D                       rd
}| ||gt          dd         dgt          |          z  |          R  z  }t          d |D                       sd}|r|                                n|S )Nr   )Sum)ImmutableMatrixr   rN   c               3   @   K   d} 	 t          d| z            V  | dz  } )Nr   Tzi_%ir   )counters    r2   fzMatMul._entry.<locals>.ff   s7      GFW,-----1r4   dummy_generatorc                 d    g | ],\  }}|                     |         |d z                      -S )r   )rY   )_entry)rK   r0   rL   rY   indicess      r2   rM   z!MatMul._entry.<locals>.<listcomp>s   s>    |||^d^_adCJJwqz71Q3<JYY|||r4   c              3   B   K   | ]}|                               V  d S r.   has)rK   vrU   s     r2   	<genexpr>z MatMul._entry.<locals>.<genexpr>u   s/      88!quu_%%888888r4   Tc              3   N   K   | ] }t          |t          t          f          V  !d S r.   )
isinstancer   int)rK   r`   s     r2   ra   z MatMul._entry.<locals>.<genexpr>}   s0      EEQ:a'300EEEEEEr4   F)sympy.concrete.summationsrT   sympy.matrices.immutablerU   r;   lengetrangenext	enumeraterR   r
   fromiteranyzipdoit)rQ   r0   jexpandkwargsrT   coeffrA   
ind_rangesrX   rL   expr_in_sumresultrU   rY   r\   s                @@@r2   r[   zMatMul._entryW   s$   111111<<<<<<0022xx==A 	-8A;q!t,,,&#h--!+,VS]]Q./

	 	 	 !**%6<<q#h--(( 	/ 	/Ao..GAJJ".. 	- 	-FAsIaL1,JqMM|||||hqrzh{h{|||l8,,8888x88888 	FssWQrT]QCJ$7DD    EE*EEEEE 	F &2v{{}}}F2r4   c                     d | j         D             }d | j         D             }t          | }|j        du rt          d          ||fS )Nc                      g | ]}|j         	|S rG   rH   rK   xs     r2   rM   z,MatMul.as_coeff_matrices.<locals>.<listcomp>   s    ;;;q{;1;;;r4   c                      g | ]}|j         	|S rG   rH   ry   s     r2   rM   z,MatMul.as_coeff_matrices.<locals>.<listcomp>   s    888!AK8A888r4   Fz3noncommutative scalars in MatMul are not supported.)r>   r
   is_commutativeNotImplementedError)rQ   scalarsrA   rs   s       r2   r;   zMatMul.as_coeff_matrices   s_    ;;di;;;88ty888W5( 	]%&[\\\hr4   c                 F    |                                  \  }}|t          | fS r.   )r;   r(   rQ   rs   rA   s      r2   as_coeff_mmulzMatMul.as_coeff_mmul   s'    0022xfh'''r4   c                 n     t          t          |           j        di |}|                     |          S )NrG   )superr(   rq   r=   )rQ   rr   expanded	__class__s      r2   rq   zMatMul.expand   s7    -5&&-7777~~h'''r4   c                     |                                  \  }}t          |gd |ddd         D             R                                  S )a  Transposition of matrix multiplication.

        Notes
        =====

        The following rules are applied.

        Transposition for matrix multiplied with another matrix:
        `\left(A B\right)^{T} = B^{T} A^{T}`

        Transposition for matrix multiplied with scalar:
        `\left(c A\right)^{T} = c A^{T}`

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Transpose
        c                 ,    g | ]}t          |          S rG   r    rJ   s     r2   rM   z*MatMul._eval_transpose.<locals>.<listcomp>   s    >>>Ys^^>>>r4   NrN   )r;   r(   ro   r   s      r2   _eval_transposezMatMul._eval_transpose   sa    & 0022x@>>x"~>>>@ @ @@D	Gr4   c                 h    t          d | j        d d d         D                                              S )Nc                 ,    g | ]}t          |          S rG   r   rJ   s     r2   rM   z(MatMul._eval_adjoint.<locals>.<listcomp>   s    @@@@@@r4   rN   )r(   r>   ro   rQ   s    r2   _eval_adjointzMatMul._eval_adjoint   s4    @@	$$B$@@@AFFHHHr4   c                     |                                  \  }}|dk    r&ddlm} | ||                                          z  S t          d          )Nr   )tracezCan't simplify any further)r   r   ro   r}   )rQ   r@   mmulr   s       r2   _eval_tracezMatMul._eval_trace   sb    ))++Q; 	D$$$$$$EE$))++....%&BCCCr4   c           	          ddl m} |                                 \  }}t          | }|| j        z  t          t          t          ||                     z  S )Nr   )Determinant)&sympy.matrices.expressions.determinantr   r;   only_squaresrO   r
   r7   r9   )rQ   r   r@   rA   square_matricess        r2   _eval_determinantzMatMul._eval_determinant   s]    FFFFFF1133&1ty 3So-N-N(O(O#PPPr4   c                     	 t          d | j        d d d         D                                              S # t          $ r t	          |           cY S w xY w)Nc                 j    g | ]0}t          |t                    r|                                n|d z  1S )rN   )rc   r   inverserJ   s     r2   rM   z(MatMul._eval_inverse.<locals>.<listcomp>   sG     0 0 0 ",C!<!<I#r'0 0 0r4   rN   )r(   r>   ro   r   r   r   s    r2   _eval_inversezMatMul._eval_inverse   st    	! 0 0#y20 0 0 1158  	! 	! 	!4==   	!s   25 AAc                                          dd          }|rfd| j        D             }n| j        }t          t          |           }|S )NdeepTc                 *    g | ]} |j         d i S )rG   )ro   )rK   rL   hintss     r2   rM   zMatMul.doit.<locals>.<listcomp>   s+    ;;;#HCH%%u%%;;;r4   )rh   r>   rC   r(   )rQ   r   r   r>   rD   s    `   r2   ro   zMatMul.doit   sZ    yy&& 	;;;;;;;DD9D FDM**r4   c                      d  j         D             }d  j         D             }|rSt          |          }t          |          }|r3|r1t          |          |k    rt          d fd|D             z            ||gS )Nc                      g | ]}|j         	|S rG   r|   ry   s     r2   rM   z#MatMul.args_cnc.<locals>.<listcomp>   s     <<<1+;<1<<<r4   c                      g | ]}|j         	|S rG   r   ry   s     r2   rM   z#MatMul.args_cnc.<locals>.<listcomp>   s     AAA!0@AAAAAr4   z"repeated commutative arguments: %sc                 j    g | ]/}t          j                                      |          d k    -|0S r   )r7   r>   count)rK   cirQ   s     r2   rM   z#MatMul.args_cnc.<locals>.<listcomp>   s;    !X!X!X$ty//:O:OPR:S:SVW:W!X"!X!X!Xr4   )r>   rg   set
ValueError)rQ   csetwarnrr   coeff_ccoeff_ncclens   `      r2   args_cnczMatMul.args_cnc   s    <<di<<<AAtyAAA 	Zw<<D'llG Z ZW!5 Z !E!X!X!X!Xw!X!X!X"Y Z Z Z""r4   c                    ddl m fdt          | j                  D             }g }|D ]}| j        d |         }| j        |dz   d          }|rt                              |          }nt          | j        d                   }|r4t                              fdt          |          D                       }nt          | j        d                   }| j        |         	                              }	|	D ]A}
|

                    |           |
                    |           |                    |
           B|S )Nr   )	Transposec                 D    g | ]\  }}|                               |S rG   r^   )rK   r0   rL   rz   s      r2   rM   z8MatMul._eval_derivative_matrix_lines.<locals>.<listcomp>   s,    IIIFAscggajjIaIIIr4   c                 \    g | ](}|j         r |                                          n|)S rG   )rI   ro   )rK   r0   r   s     r2   rM   z8MatMul._eval_derivative_matrix_lines.<locals>.<listcomp>   s;    +s+s+sZ[1;,UIIaLL,=,=,?,?,?TU+s+s+sr4   r   )r!   r   rk   r>   r(   rl   r$   rR   reversed_eval_derivative_matrix_linesappend_firstappend_secondappend)rQ   rz   
with_x_indlinesind	left_args
right_args	right_matleft_revdr0   r   s    `         @r2   r   z$MatMul._eval_derivative_matrix_lines   sT   ((((((IIIIi	&:&:III
 	  	 C	$3$I3q566*J 4"OOJ77		$TZ]33	 3!??+s+s+s+s_ghq_r_r+s+s+stt#DJqM22	#<<Q??A    x(((	***Q 
 r4   )T)FT)__name__
__module____qualname____doc__	is_MatMulr%   r/   r:   classmethodr=   propertyrR   r[   r;   r   rq   r   r   r   r   r   ro   r   r   __classcell__)r   s   @r2   r(   r(      si         I  H%*$ # # # # #J " " [" 5 5 X5(3 (3 (3 (3T  ( ( (( ( ( ( (G G G.I I ID D DQ Q Q! ! !	 	 		# 	# 	# 	#      r4   r(   c                      t          t          |           dz
            D ]8}| ||dz            \  }}|j        |j        k    rt	          d|d|d          9dS )z, Checks for valid shapes for args of MatMul r      z	Matrices z and z are not alignedN)ri   rg   rP   rO   r   )rA   r0   ABs       r2   r<   r<      s{    3x==?## J J!A#16QV 	J*111aaaHIII	JJ Jr4   c                  R    | d         dk    r
| dd          } t          t          g| R  S )Nr   r   )r   r(   )r>   s    r2   newmulr      s5    Aw!| ABBxvr4   c                     t          d | j        D                       r7d | j        D             }t          |d         j        |d         j                  S | S )Nc              3   @   K   | ]}|j         p|j        o|j        V  d S r.   )is_zerorI   is_ZeroMatrixrJ   s     r2   ra   zany_zeros.<locals>.<genexpr>  sG       , , ;?3=>S-> , , , , , ,r4   c                      g | ]}|j         	|S rG   rH   rJ   s     r2   rM   zany_zeros.<locals>.<listcomp>  s    ===Cs}=C===r4   r   rN   )rm   r>   r#   rO   rP   )r	   rA   s     r2   	any_zerosr     sj    
 , ,"%(, , , , , ?==38===(1+*HRL,=>>>Jr4   c                 j   t          d | j        D                       s| S g }| j        d         }| j        dd         D ]W}t          |t          t          f          r"t          |t          t          f          r||z  }@|                    |           |}X|                    |           t          | S )a   Merge explicit MatrixBase arguments

    >>> from sympy import MatrixSymbol, Matrix, MatMul, pprint
    >>> from sympy.matrices.expressions.matmul import merge_explicit
    >>> A = MatrixSymbol('A', 2, 2)
    >>> B = Matrix([[1, 1], [1, 1]])
    >>> C = Matrix([[1, 2], [3, 4]])
    >>> X = MatMul(A, B, C)
    >>> pprint(X)
      [1  1] [1  2]
    A*[    ]*[    ]
      [1  1] [3  4]
    >>> pprint(merge_explicit(X))
      [4  6]
    A*[    ]
      [4  6]

    >>> X = MatMul(B, A, C)
    >>> pprint(X)
    [1  1]   [1  2]
    [    ]*A*[    ]
    [1  1]   [3  4]
    >>> pprint(merge_explicit(X))
    [1  1]   [1  2]
    [    ]*A*[    ]
    [1  1]   [3  4]
    c              3   @   K   | ]}t          |t                    V  d S r.   )rc   r   rJ   s     r2   ra   z!merge_explicit.<locals>.<genexpr>&  s,      BBsz#z**BBBBBBr4   r   r   N)rm   r>   rc   r   r   r   r(   )matmulnewargslastrL   s       r2   merge_explicitr   
  s    8 BBfkBBBBB G;q>D{122  cJ/00 	ZzSYFZ5[5[ 	#:DDNN4   DDNN47r4   c                      | j                     \  }} t          d           |          }||k    rt          |g|j        R  S | S )z Remove Identities from a MatMul

    This is a modified version of sympy.strategies.rm_id.
    This is necesssary because MatMul may contain both MatrixExprs and Exprs
    as args.

    See Also
    ========

    sympy.strategies.rm_id
    c                     | j         du S )NT)is_Identityrz   s    r2   r3   zremove_ids.<locals>.<lambda>C  s    Q]d2 r4   )r   r   r   r>   )r	   r@   r   rv   s       r2   
remove_idsr   4  s\     %3$&&LFD3U2233D99F~ f+v{++++
r4   c                 P     | j                     \  }}|dk    rt          |g|R  S | S Nr   )r;   r   )r	   r@   rA   s      r2   factor_in_frontr   I  s>    ,s,..FH{ )f(x((((Jr4   c                     | j                     \  }}|d         g}t          dt          |                    D ]}|d         }||         }t          |t                    ryt          |j        t                    r_|j        j        }t          |          }t          |          || d         k    r(|d|          t          |j
        d                   gz   }t          |t                    rt          |j        t                    ru|j        j        }	t          |	          }t          |	          ||||z            k    r<t          |j
        d                   }
|
|d<   t          |||z             D ]}|
||<   E|j        dk    s|j        dk    r|                    |           rt          |t                    r|j        \  }}n|t          j        }}t          |t                    r|j        \  }}n|t          j        }}||k    r.||z   }t          ||                              d          |d<   t          |t"                    s^	 |                                }n# t&          $ r d}Y nw xY w|4||k    r.||z
  }t          ||                              d          |d<   u|                    |           t)          |g|R  S )a  Combine consecutive powers with the same base into one, e.g.
    $$A \times A^2 \Rightarrow A^3$$

    This also cancels out the possible matrix inverses using the
    knowledgebase of :class:`~.Inverse`, e.g.,
    $$ Y \times X \times X^{-1} \Rightarrow Y $$
    r   r   rN   NF)r   )r;   ri   rg   rc   r   rL   r(   r>   r7   r$   rR   	is_squarer   r   r   Onero   r   r   r   r   )r	   r@   r>   new_argsr0   r   r   BargslAargsr/   rp   A_baseA_expB_baseB_expnew_exp
B_base_invs                     r2   combine_powersr   O  s    )3(**LFDQyH1c$ii   0 0RLGa!! 	j&?&? 	EJEE

AE{{hrssm+ #CaRC=HQWQZ,@,@+AAa!! 	j&?&? 	EJEE

AE{{d1QqS5k) #AGAJ//'q!A# ' 'A&DGG;% 	1;%#7 	OOAa   	%FMFEEquEFa   	%FMFEEquEFV 	emG!&'2277U7CCHRLFJ// 	"#^^--

+ " " "!


" &J*> %-%fg66;;;GG&$8$$$$s   I&&I54I5c                    | j         }t          |          }|dk     r| S |d         g}t          d|          D ]}|d         }||         }t          |t                    rEt          |t                    r0|j         d         }|j         d         }t	          ||z            |d<   l|                    |           t          | S )zGRefine products of permutation matrices as the products of cycles.
    r   r   r   rN   )r>   rg   ri   rc   r"   r   r(   )	r	   r>   r   rv   r0   r   r   cycle_1cycle_2s	            r2   combine_permutationsr     s     8DD		A1u 
1gYF1a[[ 	 	2JGa*++ 	q+,,	fQiGfQiG*7W+<==F2JJMM!6?r4   c                     | j                     \  }}|d         g}|dd         D ]}|d         }t          |t                    rt          |t                    s|                    |           J|                                 |                    t          |j        d         |j        d                              ||j        d         z  }t          |g|R  S )zj
    Combine products of OneMatrix

    e.g. OneMatrix(2, 3) * OneMatrix(3, 4) -> 3 * OneMatrix(2, 4)
    r   r   NrN   )r;   rc   r&   r   poprR   r   )r	   r@   r>   r   r   r   s         r2   combine_one_matricesr     s     )3(**LFDQyH!""X  RL!Y'' 	z!Y/G/G 	OOA	!'!*agaj99:::!'!*&$8$$$$r4   c                     | j         t                    dk    rrddlm} d         j        r)d         j        r |fdd         j         D              S d         j        r)d         j        r |fdd         j         D              S | S )zr
    Simplify MatMul expressions but distributing
    rational term to MatMul.

    e.g. 2*(A+B) -> 2*A + 2*B
    r   r   )MatAddr   c                 `    g | ]*}t          |d                                                    +S r   r(   ro   rK   matr>   s     r2   rM   z$distribute_monom.<locals>.<listcomp>  s3    PPPCF3Q005577PPPr4   c                 `    g | ]*}t          d          |                                          +S )r   r   r   s     r2   rM   z$distribute_monom.<locals>.<listcomp>  s3    PPPCF47C005577PPPr4   )r>   rg   mataddr   	is_MatAddis_Rational)r	   r   r>   s     @r2   distribute_monomr    s     8D
4yyA~ R""""""7 	Ra!4 	R6PPPP47<PPPQQ7 	Ra!4 	R6PPPP47<PPPQQJr4   c                     | dk    S r   rG   r   s    r2   r3   r3     s    klpqkq r4   c            	      6   | d         j         | d         j        k    rt          d          g }d}t          |           D ]Y\  }}|j        | |         j         k    r>|                    t          | ||dz                                                        |dz   }Z|S )z'factor matrices only if they are squarer   rN   z!Invalid matrices being multipliedr   )rO   rP   RuntimeErrorrk   r   r(   ro   )rA   outstartr0   Ms        r2   r   r     s    {8B<,, @>???
CE(##  16Xe_)) 	JJvxac	2388::;;;aCEJr4   c                 P   g }g }| j         D ]4}|j        r|                    |           |                    |           5|d         }|dd         D ]}||j        k    r=t	          t          j        |          |          rt          |j        d                   }J||	                                k    r=t	          t          j
        |          |          rt          |j        d                   }|                    |           |}|                    |           t          | S )z
    >>> from sympy import MatrixSymbol, Q, assuming, refine
    >>> X = MatrixSymbol('X', 2, 2)
    >>> expr = X * X.T
    >>> print(expr)
    X*X.T
    >>> with assuming(Q.orthogonal(X)):
    ...     print(refine(expr))
    I
    r   r   N)r>   rI   r   Tr   r   
orthogonalr$   rR   	conjugateunitaryr(   )rD   assumptionsr   exprargsr>   r   rL   s          r2   refine_MatMulr    s,    GH	 ! !> 	!OOD!!!!NN4    A;D|  $&= 	Sc!2!2K@@ 	CIaL))DDDNN$$$ 	QYs^^[)I)I 	CIaL))DDNN4   DDNN47r4   N)@sympy.assumptions.askr   r   sympy.assumptions.refiner   
sympy.corer   r   r   sympy.core.mulr	   r
   sympy.core.numbersr   r   sympy.core.symbolr   sympy.functionsr   sympy.strategiesr   r   r   r   r   r   r   sympy.matrices.commonr   r   sympy.matrices.matricesr   sympy.utilities.exceptionsr   r   r   matexprr   matpowr   r!   permutationr"   specialr#   r$   r%   r&   r(   register_handlerclassr<   r   r   r   r   r   r   r   r   r  rulesrC   r   r  rG   r4   r2   <module>r!     s,   ( ( ( ( ( ( ( ( 2 2 2 2 2 2 ( ( ( ( ( ( ( ( ( ( # # # # # # # # . . . . . . . . # # # # # # # # # # # #                  F F F F F F F F . . . . . . @ @ @ @ @ @                               * * * * * * E E E E E E E E E E E EY Y Y Y YZ Y Y Yv  3- 0 0 0J J J  
  ( ( (T  *  =% =% =%~  ,% % %(  " i-A>SY[`[`aqaq[r[rOW.B	D wuufffen56677
 
 
  D (h   r4   