
    CdW                       d dl mZ d dlZd dlZd dlmZ d dlmZ d dlZ	d dl
Zd dlmZmZmZmZ d dlmZ d dlmZmZ d dl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%m&Z& d Z'd Z(d Z)d Z*d*dZ+d+dZ,d,dZ-	 	 	 	 	 d-dZ.	 	 	 	 	 	 d.dZ/d Z0d/dZ1d Z2d Z3d0d Z4d1d"Z5d# Z6d$ Z7d0d%Z8d& Z9d' Z:d( Z; e&e	j<                  d2d)            Z=dS )3    )annotationsN)partial)Number)Arrayconcatenatedotmanyfrom_delayed)eye)RandomStatedefault_rng)
array_safemeta_from_arraysolve_triangular_safesvd_flip)tokenizewait)	blockwise)delayed)HighLevelGraph)applyderived_fromc              #  2   K   d}| D ]}|}||z  }||fV  d S )Nr    )ittotalxtotal_previouss       1lib/python3.11/site-packages/dask/array/linalg.py_cumsum_blocksr      sF      E & &
u%%%%%& &    c                (    | d         | d         |z   fS N   r   )lastnews     r   _cumsum_partr&   #   s    GT!Ws]##r    c                    t          | |g          }t          j        |          r| n|}t          j        |          r|n|S N)minnpisnan)mnk_0k_1s       r   _nanminr0   '   s>    
q!f++Cx{{
!!!C(3--(33S(r    c                    | j         d         dk    r9t          j        | d          t          j        | d| j         d         f          fS t          j                            |           S )z
    A wrapper for np.linalg.qr that handles arrays with 0 rows

    Notes: Created for tsqr so as to manage cases with uncertain
    array dimensions. In particular, the case where arrays have
    (uncertain) chunks with 0 rows.
    r   )r   r   shaper#   )r3   r*   
zeros_likelinalgqras    r   _wrapped_qrr9   -   sY     	wqzQ}Qf---r}Qq!'RS*o/V/V/VVVy||Ar    Fc                $   ]^_`abcdefgh t           j        d                   t           j        d                   }}t           j        d                    j        d         d         }} j        dk    r|dk    s-t	          d                     j         j                            dt           |          z   } j        \  }]|df}	t          j
                            t          j        d j                            \  }
}                                 j                                        }                                 j                                        }d|z   et%          t&          ed	 j        d	 j        |	i
          }||e<   t+                                                     |e<   d|z   dz   bbefdt/          |	d                   D             }||b<   eh|b<   d|z   dz   feffdt/          |	d                   D             }||f<   eh|f<   ||z  }t1          d  j        D                        }t          j        ||z            }||n|d|z  k    }|ot5          |          dk    }|r|r|r|g }g }d}t7           j        d                   D ]W\  }}|}t9          ||          }|}||z   |k    r|                    |           g }d}|                    ||f           ||z  }Xt          |          dk    r|                    |           d|z   dz   gfgfdt7          |          D             }||g<   fh|g<   t=          d |D                       }t?          ||          } tA           t          tC          |          ]f          |j                  }!tE          | gtC          |          ]f|]f|!          }"tG          |"|          \  h}#tI          j%        hj&        j        |#j&        j                  }tI          j%        hj&        j        |#j&        j                  }d|z   dz   c]chfdt7          |          D             }$|$|c<   t+          h                                          |c<   d|z   }%|%ddf|#j        ddfi}&|&||%<   t+          |#                                          ||%<   d|z   dz   }'t%          t          j'        |'d	bd	cd	b|	c|	i
          }(|(||'<   bch||'<   nňffdt/          |	d                   D             })d|z   dz   }*|*ddft          j(        t<          |)ffi}+|+||*<   fh||*<   d|z   dz   },t%          t          j
        j        |,d	|*d	|*di
          }-|-||,<   |*h||,<   d|z   dz   ddddftR          j*        |,ddfdfi}.|.|d<   |,h|d<   t1          d   j        D                        }/|/rE]fd! j        d         D             }0]fd"tW          |0          D             }1i }2t+                      }3nd#|z   dz   ` `fd$t/          |	d                   D             }4d|z   d%z   __tR          j*        tX           j        ddfd#fdfi}5d&|z   dz   aadfd`dfgi}6t/          d|	d                   D ]}7tZ          a|7dz
  f`|7ff|6a|7f<   d'|z   d(z   ^^_afd)t/          |	d                   D             }8tI          j%        |5|4|6|8          }2 j        h}3^fd*t/          |	d                   D             }1|2|d+|z   <   |3|d+|z   <   d|z   dz   ccdfd,t7          |1          D             }$|$|c<   |/rdh|c<   n
dd+|z   h|c<   d|z   dz   }'t%          t          j'        |'d	bd	cd	b|	c|	i
          }(|(||'<   bch||'<   d|z   d-z   }%|%ddftR          j*        |,ddfdfi}&|&||%<   |,h||%<   |st          j.         j        d                   p#t1          d.  j        d         D                       }9t          j.         j        d                   p#t1          d/  j        d         D                       }:|9rW|:rU j        }; j        d         t          j/        ff}<t          j/        t          j/        f}=t          j/        ft          j/        ff}>n|9r"|:s  j        }; j        d         ]ff}<]]f}=]]f}>n|9sV|:rT j        }; j        d         t          j/        ff}<t          j/        t          j/        f}=t          j/        ft          j/        ff}>n j        d          j        d         k    r j        n j        d          j        d         f}; j        d          j        d         k    r j        n j        d          j        d         f}< j        d          j        d         k    r]]fn j        }=|=}>t?          ||          } tA           t          |;          |
j                  }?tA           t          |=          |j                  }@tE          | |'|;|<|?          }AtE          | |%|=|>|@          }B|A|BfS d0|z   d1z   }Ct%          t          j
        j0        |Cd	|%d	|%di
          }Dd|z   d2z   }E|EddftR          j*        |Cddfdfi}Fd|z   d3z   }G|GdftR          j*        |Cddfdfi}Hd|z   d4z   }I|IddftR          j*        |Cddfdfi}Jd|z   d5z   }Kt%          tb          |Kd	|'d6|Ed7|'|	|Edi
          }L|D||C<   |%h||C<   |F||E<   |Ch||E<   |L||K<   |'|Eh||K<   |H||G<   |Ch||G<   |J||I<   |Ch||I<   t          j
        0                    t          j        d j                            \  }M}N}Ote          |]          }P|}Qt          j.        |P          st5          |P          n|P}R|R}S|R}T]}Ut          |T|U          }Vt?          ||          } tA           t          |Q|Rf          |Mj                  }WtA           t          |Sf          |Nj                  }XtA           t          |V|Vf          |Oj                  }YtE          | |K|Q|Rf j        d         |Rff|W          }ZtE          | |G|Sf|Sff|X          }[tE          | |I|V|Vf]f]ff|Y          }\|Z|[|\fS )8a  Direct Tall-and-Skinny QR algorithm

    As presented in:

        A. Benson, D. Gleich, and J. Demmel.
        Direct QR factorizations for tall-and-skinny matrices in
        MapReduce architectures.
        IEEE International Conference on Big Data, 2013.
        https://arxiv.org/abs/1301.1071

    This algorithm is used to compute both the QR decomposition and the
    Singular Value Decomposition.  It requires that the input array have a
    single column of blocks, each of which fit in memory.

    Parameters
    ----------
    data: Array
    compute_svd: bool
        Whether to compute the SVD rather than the QR decomposition
    _max_vchunk_size: Integer
        Used internally in recursion to set the maximum row dimension
        of chunks in subsequent recursive calls.

    Notes
    -----
    With ``k`` blocks of size ``(m, n)``, this algorithm has memory use that
    scales as ``k * n * n``.

    The implementation here is the recursive variant due to the ultimate
    need for one "single core" QR decomposition. In the non-recursive version
    of the algorithm, given ``k`` blocks, after ``k`` ``m * n`` QR
    decompositions, there will be a "single core" QR decomposition that will
    have to work with a ``(k * n, n)`` matrix.

    Here, recursion is applied as necessary to ensure that ``k * n`` is not
    larger than ``m`` (if ``m / n >= 2``). In particular, this is done
    to ensure that single core computations do not have to work on blocks
    larger than ``(m, n)``.

    Where blocks are irregular, the above logic is applied with the "height" of
    the "tallest" block used in place of ``m``.

    Consider use of the ``rechunk`` method to control this behavior.
    Taller blocks will reduce overall memory use (assuming that many of them
    still fit in memory at once).

    See Also
    --------
    dask.array.linalg.qr
        Powered by this algorithm
    dask.array.linalg.svd
        Powered by this algorithm
    dask.array.linalg.sfqr
        Variant for short-and-fat arrays
    r   r#      a  Input must have the following properties:
  1. Have two dimensions
  2. Have only one column of blocks

Note: This function (tsqr) supports QR decomposition in the case of
tall-and-skinny matrices (single column chunk/block; see qr)
Current shape: {},
Current chunksize: {}-r#   r#   r3   dtyper6   ij)	numblocksgetitemz-q1c                <    i | ]}|d ft           j        |d fd fS r   operatorrB   ).0i
name_q_st1name_qr_st1s     r   
<dictcomp>ztsqr.<locals>.<dictcomp>   C        
QX-Q/BAF  r    z-r1c                <    i | ]}|d ft           j        |d fdfS r   r#   rE   )rG   rH   rJ   
name_r_st1s     r   rK   ztsqr.<locals>.<dictcomp>   rL   r    c              3  H   K   | ]}|D ]}t          j        |          V  d S r(   r*   r+   rG   cscs      r   	<genexpr>ztsqr.<locals>.<genexpr>   s7      !P!P"R!P!P"(1++!P!P!P!P!P!P!Pr    Nstackc                `    i | ]*\  }}|d ft           j        t          fd|D             ff+S )r   c                     g | ]
\  }}|d fS rD   r   )rG   idx_rO   s      r   
<listcomp>z#tsqr.<locals>.<dictcomp>.<listcomp>   s$    KKK&#q*c1-KKKr    )r*   vstacktuple)rG   rH   sub_block_inforO   name_r_stackeds      r   rK   ztsqr.<locals>.<dictcomp>   s]     
 
 

 ">	 Q"	KKKKNKKKL%
 
 
r    c              3  R   K   | ]"}t          t          d  |                    V  #dS )c                    | d         S r"   r   r   s    r   <lambda>z tsqr.<locals>.<genexpr>.<lambda>   s
    ad r    N)summap)rG   r^   s     r   rU   ztsqr.<locals>.<genexpr>   sG       !
 !
9GCNNN3344!
 !
 !
 !
 !
 !
r    r?   r3   chunksmeta)_max_vchunk_sizez-q2c                   i | ]\  }}t          d  |D             t          d |D                                 D ]J\  }}|dft          j        j        |dft          |d         |d                   t          d          ffKS )c                    g | ]
}|d          S rD   r   rG   r   s     r   r[   z#tsqr.<locals>.<dictcomp>.<listcomp>   s    ...!1...r    c                    g | ]
}|d          S )r#   r   rm   s     r   r[   z#tsqr.<locals>.<dictcomp>.<listcomp>   s    ===!===r    r   r#   )zipr   rF   rB   nameslice)rG   rH   r^   jer-   
name_q_st2q_inners        r   rK   ztsqr.<locals>.<dictcomp>   s     
 
 
 ">..~...==n===>> 
 
 1 A q!$!ad##uQ{{4!
 
 
 
r    zr-innerdotz-q3c                    g | ]}|d fS rD   r   )rG   rH   rO   s     r   r[   ztsqr.<locals>.<listcomp>  s     DDD1ZA&DDDr    z-qr2z-q2-auxc              3  H   K   | ]}|D ]}t          j        |          V  d S r(   rQ   rR   s      r   rU   ztsqr.<locals>.<genexpr>4  s8      &U&UrRT&U&UQrx{{&U&U&U&U&U&U&Ur    c                0    g | ]}t          |          S r   )r)   rG   rs   r-   s     r   r[   ztsqr.<locals>.<listcomp>8  s!    @@@Ac!Qii@@@r    c                h    g | ].}t          |d          |d                   t          d           f/S rN   )rq   rz   s     r   r[   ztsqr.<locals>.<listcomp>9  sE       56qtQqT""E!QKK0  r    r3   c                H    i | ]}|ft           t          j        |d fdffS )r   r3   )r)   getattrrp   )rG   rH   data	name_q2bss     r   rK   ztsqr.<locals>.<dictcomp>C  sD        AwAq0A7&K L  r    z-ncumsumrq   z-qc                Z    i | ]'}|ft           t          t          |fft          d fgf(S rD   )r]   r   rq   )rG   rH   name_blockslicename_n	name_q2css     r   rK   ztsqr.<locals>.<dictcomp>Y  sR          
 	 !!$UYN3eQ5GH'     r    c                    g | ]}|fS r   r   )rG   rH   r   s     r   r[   ztsqr.<locals>.<listcomp>f  s    NNNQ_a0NNNr    zq-blocksizesc                B    i | ]\  }}|d ft           j        d d f|fS rD   rE   )rG   rH   brt   name_q_st2_auxs      r   rK   ztsqr.<locals>.<dictcomp>m  sG     
 
 
1 A!1NAq3I1 M
 
 
r    z-r2c              3  >   K   | ]}t          j        |          V  d S r(   rQ   rG   rT   s     r   rU   ztsqr.<locals>.<genexpr>  ;       6
 6
BHQKK6
 6
 6
 6
 6
 6
r    c              3  >   K   | ]}t          j        |          V  d S r(   rQ   r   s     r   rU   ztsqr.<locals>.<genexpr>  r   r    svdz-2z-u2z-s2z-v2z-u4ikkj)3lenrh   maxndim
ValueErrorformatr3   	chunksizer   r*   r5   r6   onesr?   __dask_graph__layerscopydependenciesr   r9   rp   set__dask_layers__rangeanyceilint	enumerater)   appendr]   r   r   rd   r   tsqrtoolzmergedaskrv   r\   rF   rB   r   r}   r&   r+   nanr   r   r0   )ir~   compute_svdrj   nrnccr_maxcctokenr,   rA   qqrrr   r   
dsk_qr_st1	dsk_q_st1	dsk_r_st1single_core_compute_mchunks_well_definedprospective_blocksmeaningful_reduction_possiblecan_distribute
all_blocks
curr_blockcurr_block_szrY   a_mm_qn_qm_rdsk_r_stackedvchunks_rstackedgraphr_stacked_meta	r_stackedr_inner	dsk_q_st2
name_r_st2	dsk_r_st2
name_q_st3	dsk_q_st3to_stackname_r_st1_stackeddsk_r_st1_stackedname_qr_st2
dsk_qr_st2dsk_q_st2_auxchucks_are_all_knownq2_block_sizesblock_slicesdsk_q_blockslicesdepsdsk_q2_shapesdsk_ndsk_q2_cumsumrH   dsk_block_slicesis_unknown_mis_unknown_nq_shapeq_chunksr_shaper_chunksq_metar_metaqrname_svd_st2dsk_svd_st2
name_u_st2	dsk_u_st2
name_s_st2	dsk_s_st2
name_v_st2	dsk_v_st2
name_u_st4	dsk_u_st4uussvvhkm_un_un_sm_vhn_vhd_vhu_metas_metavh_metausvhr-   r   r   r   r   rI   rt   r   rJ   rO   r_   ru   si   `                                                                                            @@@@@@@@@@@@r   r   r   <   s%   p Q  #dk!n"5"5BT[^$$dk!nQ&7BFINNrQww8
 9?
DN9 9	
 	
 		
 (4---E:DAqQIY\\"'djAAABBFB  "")..00F&&((5::<<L ,K	9i(  J %F; #D$8$8$:$: ; ;L U"U*J    y|$$  I #F: +}L U"U*J    y|$$  I #F: +}L G!!P!P!P!P!PPPP!6!?@@"*0@	
R%! )HS1C-D-Dq-HN Q1< Q1 Q1 

!$+a.11 
	! 
	!HCCc2,,CCs"V++!!*---
 !sCj)))S MMz??Qj))) !550
 
 
 
 

 &/z%:%:
 
 
 "/~(2|^$ ! !
 !
KU!
 !
 !
 
 
 v|44(#s+,,a011
 
 
 '((!,$a(
 
 
	  	FCCCW\0',2EFF{7<#<gl>WXX &.

 
 
 
 
 
 &/z%:%:
 
 
	 'z#&w'>'>'@'@#A#AZ  &
 !Q'',1)=>	&z#&w'>'>'@'@#A#AZ  U]U*
F!9j)D	
 	
 	
	 'z$.
#;Z  
 EDDDil0C0CDDD$u_u40!Q7")eXEV9WX%6!",6<'( UlV+IL)62
 
 

 ){%7$8[! #U*Y6Q"X%5Q7JA$N
 "/~(3}^$#&&U&UT[&U&U&U#U#UU 1	O A@@@Q@@@N   :H:X:X  L !#55DD
  %%/I    y|,,  M &-F)GdiA5F+PRSTE
 !5(50I'^a)Q-@AM1il++   A&N1y!n-- &o4O           
 y|,,      !&}m5E! ! I;DNNNN%	!:M:MNNNL):~%&/3^e+, &.

 
 
 
 
!,//
 
 
	 'z 	P(6'7L$$(68N'OL$ U]U*
F!9j)D	
 	
 	
	 'z$.
#;Z  &.
 !Q'(*:[!Q<OQR)ST	&z$/=Z  ux
1.. 
# 6
 6
!%Q6
 6
 6
 3
 3
 x
1.. 
# 6
 6
!%Q6
 6
 6
 3
 3
  	L 	jGA	2Hvrv&G	BF9-HH 	, 	jGA-H!fG1vHH 	, 	jGA	2Hvrv&G	BF9-HH :a=DJqM11 

jmTZ]3  :a=DJqM11 k!ndk!n5 
 !%
1A > >q!ffDJGH v|44 s7||RX>> s7||RX>>%78&QQQ%78&QQQ!t u}t+IM!6*
 
 
 &.
 !Q'(*:\1a<PRS)TU	&.
 !_x'7,19Mq&QR	&.
 !Q'(*:\1a<PRS)TU	&.
!9j&A	
 	
 	
	  +|&0\\"&z$0>Z &z$.
#;Z &z$0>Z &z$0>Z immBG&
$K$K$KLLBAqMMHQKK.c!fffQ4v|44 sC:AA sC6{{BH==!$T4L(9(939EE*KNSF+
 
 
 %C6C6)&QQQ:dD\A4!,W
 
 
 !Rxr    c           
         t           j        d                   t           j        d                   }} j        d         d          j        d         d         }} j        dk    r|dk    r||k    s|dk    st          d          |pdt	                     z   }|dz  } j        \  }}t          j                            t          j	        d j
                            \  }	}
                                 j                                        }                                 j                                        }|d	z   }|d
z   |ddf j        ddfi||<   t!                                                     ||<    fdt%          |dz
            D             |<   t          |                   dk    r%t!                                                     |<   nt!                      |<   |dz   }|dz   }|dz   }|ddft          j        j        |ddffi||<   |h||<   |ddft&          j        |ddfdfi||<   |h||<   |ddft&          j        |ddfdfi||<   |h||<   t+          ||          }t-           t          |t/          ||          f          |	j
                  }t-           t          t/          ||          |f          |
j
                  }t1          |||t/          ||          f|t/          ||          f|          }t1          ||t/          ||          |f||f|          }|g}|dk    rt-           t          t/          ||          ||z
  f          |
j
                  }t1          |t/          ||          ||z
  f| j        d         dd         f|          }|                    |j                            |                     t9          |d          }||fS )a/  Direct Short-and-Fat QR

    Currently, this is a quick hack for non-tall-and-skinny matrices which
    are one chunk tall and (unless they are one chunk wide) have chunks
    that are wider than they are tall

    Q [R_1 R_2 ...] = [A_1 A_2 ...]

    it computes the factorization Q R_1 = A_1, then computes the other
    R_k's in parallel.

    Parameters
    ----------
    data: Array

    See Also
    --------
    dask.array.linalg.qr
        Main user API that uses this function
    dask.array.linalg.tsqr
        Variant for tall-and-skinny case
    r   r#   r;   a  Input must have the following properties:
  1. Have two dimensions
  2. Have only one row of blocks
  3. Either one column of blocks or (first) chunk size on cols
     is at most that on rows (e.g.: for a 5x20 matrix,
     chunks=((5), (8,4,8)) is fine, but chunks=((5), (4,8,8)) is not;
     still, prefer something simple like chunks=(5,10) or chunks=5)

Note: This function (sfqr) supports QR decomposition in the case
of short-and-fat matrices (single row chunk/block; see qr)zsfqr-rZ   r=   r>   A_1A_restc                2    i | ]}d |fj         d d|z   fS rN   )rp   )rG   rY   r~   name_A_rests     r   rK   zsfqr.<locals>.<dictcomp>A  s<       ;>a	1a#g6  r    Q_R_1QR_1rf   rg   Naxis)r   rh   r   r   r   r3   r*   r5   r6   r   r?   r   r   r   r   rp   r   r   r   rF   rB   r   r   r)   r   r   Trv   r   )r~   rp   r   r   crr   prefixr,   r-   r   r   r   r   name_A_1	name_Q_R1name_Qname_R_1r   Q_metaR_1_metar  r  RsA_rest_metar   Rr  s   `                         @r   sfqrr    s*   . Q  #dk!n"5"5B[^AAq 1B 
a1WW2XXa I

 

 
	
 -Wx~~-F
cMF:DAqY\\"'djAAABBFB  "")..00F&&((5::<<L ~H8#K!1a(49a*;<F8 !5!5!7!788L    BGQ--  F; 6+!##$'(<(<(>(>$?$?[!!$'EE[!  Ic\F~H#Q*RY\Ha;K,LMF9'jLq!nx'7)Q9JA&NOF6N%;L!1a(8+;iA=NPQ*RSF8'[L6<00ET33q!99~#6#6bhGGGFtS#a))R%9%9JJJHeVAs1ayy>1c!Qii.vVVVA
xAq		2Bxh
W
W
WC B	Avv%dCQAF0C,D,DBHUUUq!99a"f%Aqrr*+
 
 
 			!#''&//"""BQAa4Kr    
      c                D    t          t          |||z             |           S )a  Compression level to use in svd_compressed

    Given the size ``n`` of a space, compress that that to one of size
    ``q`` plus n_oversamples.

    The oversampling allows for greater flexibility in finding an
    appropriate subspace, a low value is often enough (10 is already a
    very conservative choice, it can be further reduced).
    ``q + oversampling`` should not be larger than ``n``.  In this
    specific implementation, ``q + n_oversamples`` is at least
    ``min_subspace_size``.

    Parameters
    ----------
    n: int
        Column/row dimension of original matrix
    q: int
        Size of the desired subspace (the actual size will be bigger,
        because of oversampling, see ``da.linalg.compression_level``)
    n_oversamples: int, default=10
        Number of oversamples used for generating the sampling matrix.
    min_subspace_size : int, default=20
        Minimum subspace size.

     Examples
    --------
    >>> compression_level(100, 10)
    20
    )r)   r   )r-   r   n_oversamplesmin_subspace_sizes       r   compression_levelr  p  s$    < s$a-&788!<<<r    powerc                   |dvrt          d| d          | j        \  }}t          t          ||          ||          }	t	          |t
                    r|}
nt          |          }
t          j        }| j	        j
        t          j        t          j        hv rt          j        }|
                    ||	f| j        d         |	ff                              |d          }|                     |          }|d	k    rt#          |          D ]{}|r#|                                }t'          |           | j                            |          }|r#|                                }t'          |           |                     |          }|t+          |          \  }}nt+          |          \  }}t#          |          D ]}|r#|                                }t'          |           t+          | j                            |                    \  }}|r#|                                }t'          |           t+          |                     |                    \  }}|j        S )
a   Randomly sample matrix to find most active subspace

    This compression matrix returned by this algorithm can be used to
    compute both the QR decomposition and the Singular Value
    Decomposition.

    Parameters
    ----------
    data: Array
    q: int
        Size of the desired subspace (the actual size will be bigger,
        because of oversampling, see ``da.linalg.compression_level``)
    iterator: {'power', 'QR'}, default='power'
        Define the technique used for iterations to cope with flat
        singular spectra or when the input matrix is very large.
    n_power_iter: int
        Number of power iterations, useful when the singular values
        decay slowly. Error decreases exponentially as `n_power_iter`
        increases. In practice, set `n_power_iter` <= 4.
    n_oversamples: int, default=10
        Number of oversamples used for generating the sampling matrix.
        This value increases the size of the subspace computed, which is more
        accurate at the cost of efficiency.  Results are rarely sensitive to this choice
        though and in practice a value of 10 is very commonly high enough.
    compute : bool
        Whether or not to compute data at each use.
        Recomputing the input while performing several passes reduces memory
        pressure, but means that we have to compute the input multiple times.
        This is a good choice if the data is larger than memory and cheap to
        recreate.

    References
    ----------
    N. Halko, P. G. Martinsson, and J. A. Tropp.
    Finding structure with randomness: Probabilistic algorithms for
    constructing approximate matrix decompositions.
    SIAM Rev., Survey and Review section, Vol. 53, num. 2,
    pp. 217-288, June 2011
    https://arxiv.org/abs/0909.4061
    )r  QRz
Iterator 'z,' not valid, must one one of ['power', 'QR'])r  r#   )sizerh   F)r   r  )r   r3   r  r)   
isinstancer   r   r*   float64r?   typefloat32	complex64standard_normalrh   astyperv   r   persistr   r  r   )r~   r   iteratorn_power_iterr  seedcomputer,   r-   
comp_levelstatedatatypeomegamat_hrZ   tmps                   r   compression_matrixr0    s9   b &&OOOO
 
 	
 :DAq"3q!99a}MMMJ$$$ "D!!zH
RZ666:!!_dk!nzm%D "  fXEf"" 
 HHUOOE7|$$ 	" 	"A U&**U##C kkmmS			HHSMMEEE{{11E{{1|$$ 	% 	%A IIKKQ

1&&DAq IIKKQ$$DAqq3Jr    Tc           	        t          | ||||||          }|r#|                                }t          |           |                    |           }	t	          |	j        d          \  }
}}|j                            |j                  }|
j        }
|ddd|f         }|d|         }|
d|ddf         }
|rt          ||
          \  }}
|||
fS )a  Randomly compressed rank-k thin Singular Value Decomposition.

    This computes the approximate singular value decomposition of a large
    array.  This algorithm is generally faster than the normal algorithm
    but does not provide exact results.  One can balance between
    performance and accuracy with input parameters (see below).

    Parameters
    ----------
    a: Array
        Input array
    k: int
        Rank of the desired thin SVD decomposition.
    iterator: {'power', 'QR'}, default='power'
        Define the technique used for iterations to cope with flat
        singular spectra or when the input matrix is very large.
    n_power_iter: int, default=0
        Number of power iterations, useful when the singular values
        decay slowly. Error decreases exponentially as `n_power_iter`
        increases. In practice, set `n_power_iter` <= 4.
    n_oversamples: int, default=10
        Number of oversamples used for generating the sampling matrix.
        This value increases the size of the subspace computed, which is more
        accurate at the cost of efficiency.  Results are rarely sensitive to this choice
        though and in practice a value of 10 is very commonly high enough.
    compute : bool
        Whether or not to compute data at each use.
        Recomputing the input while performing several passes reduces memory
        pressure, but means that we have to compute the input multiple times.
        This is a good choice if the data is larger than memory and cheap to
        recreate.
    coerce_signs : bool
        Whether or not to apply sign coercion to singular vectors in
        order to maintain deterministic results, by default True.


    Examples
    --------
    >>> u, s, v = svd_compressed(x, 20)  # doctest: +SKIP

    Returns
    -------
    u:  Array, unitary / orthogonal
    s:  Array, singular values in decreasing order (largest first)
    v:  Array, unitary / orthogonal

    References
    ----------
    N. Halko, P. G. Martinsson, and J. A. Tropp.
    Finding structure with randomness: Probabilistic algorithms for
    constructing approximate matrix decompositions.
    SIAM Rev., Survey and Review section, Vol. 53, num. 2,
    pp. 217-288, June 2011
    https://arxiv.org/abs/0909.4061
    )r&  r'  r  r(  r)  Tr   N)r0  r%  r   rv   r   r  r   )r8   r   r&  r'  r  r(  r)  coerce_signscompa_compressedvr   r   s                r   svd_compressedr7    s    B 		!#  D  ||~~T


88A;;L<>t444GAq!

13A	A	!!!RaR%A	"1"A	"1"aaa%A 1~~1a7Nr    c                   t          | j        d                   dk    r-t          | j        d                   dk    rt          |           S t          | j        d                   dk    rt          |           S t	          d          )a  
    Compute the qr factorization of a matrix.

    Parameters
    ----------
    a : Array

    Returns
    -------
    q:  Array, orthonormal
    r:  Array, upper-triangular

    Examples
    --------
    >>> q, r = da.linalg.qr(x)  # doctest: +SKIP

    See Also
    --------
    numpy.linalg.qr: Equivalent NumPy Operation
    dask.array.linalg.tsqr: Implementation for tall-and-skinny arrays
    dask.array.linalg.sfqr: Implementation for short-and-fat arrays
    r#   r   a}  qr currently supports only tall-and-skinny (single column chunk/block; see tsqr)
and short-and-fat (single row chunk/block; see sfqr) matrices

Consider use of the rechunk method. For example,

x.rechunk({0: -1, 1: 'auto'}) or x.rechunk({0: 'auto', 1: -1})

which rechunk one shorter axis to a single chunk, while allowing
the other axis to automatically grow/shrink appropriately.)r   rh   r   r  NotImplementedErrorr7   s    r   r6   r6   E  s|    0 18A;1QXa[!1!1A!5!5Aww	QXa[		Q		Aww!I
 
 	
r    c                   | j         }| j        dk    r-t          d                    | j        | j                            |d         dk    r4|d         dk    r(t          d                    | j        |                    |d         |d         cxk    rdk    rn n| j        \  }}t          | j                  }t          j        	                    t          j
        | j        d| j        j                            \  }}} t          t          j        j	        d	          | d
          \  }	}
}t          |	||f|          }	t          |
|f|          }
t          |||f|          }n|d         |d         k    r2t          | d          \  }	}
}| j        d         | j        d         k     }nFt          | j        d          \  }}
}|j        |
|j        }}
}	| j        d         | j        d         k    }|r0t          | j                  }|	ddd|f         |d|ddf         }}	|rt#          |	|          \  }	}|	|
|fS )aZ  
    Compute the singular value decomposition of a matrix.

    Parameters
    ----------
    a : (M, N) Array
    coerce_signs : bool
        Whether or not to apply sign coercion to singular vectors in
        order to maintain deterministic results, by default True.

    Examples
    --------

    >>> u, s, v = da.linalg.svd(x)  # doctest: +SKIP

    Returns
    -------

    u : (M, K) Array, unitary / orthogonal
        Left-singular vectors of `a` (in columns) with shape (M, K)
        where K = min(M, N).
    s : (K,) Array, singular values in decreasing order (largest first)
        Singular values of `a`.
    v : (K, N) Array, unitary / orthogonal
        Right-singular vectors of `a` (in rows) with shape (K, N)
        where K = min(M, N).

    Warnings
    --------

    SVD is only supported for arrays with chunking in one dimension.
    This requires that all inputs either contain a single column
    of chunks (tall-and-skinny) or a single row of chunks (short-and-fat).
    For arrays with chunking in both dimensions, see da.linalg.svd_compressed.

    See Also
    --------

    np.linalg.svd : Equivalent NumPy Operation
    da.linalg.svd_compressed : Randomized SVD for fully chunked arrays
    dask.array.linalg.tsqr : QR factorization for tall-and-skinny arrays
    dask.array.utils.svd_flip : Sign normalization for singular vectors
    r;   z1Array must be 2D.
Input shape: {}
Input ndim: {}
r   r#   zArray must be chunked in one dimension only. This function (svd) only supports tall-and-skinny or short-and-fat matrices (see da.linalg.svd_compressed for SVD on fully chunked arrays).
Input shape: {}
Input numblocks: {}
r=   r>      )noutF)full_matrices)r3   ri   Tr2  N)rA   r   r   r   r3   r9  r)   r*   r5   r   	ones_like_metar?   r   r	   r   r  r   )r8   r3  nbr,   r-   r   mumsmvr   r   r6  truncatevtuts                  r   r   r   l  s^   X 
Bv{{%vagqv66
 
 	

 
!uqyyRUQYY!$ %+F17B$7$7
 
 	
 
!u1w1LLY]]LagmDDD
 

B 1'")-a000%HHH1a1a&r2221$R0001a&r222 a52a5==1$///GAq!wqzAGAJ.HH QSd333IB2dArt!qAwqzAGAJ.H  	&AGAQQQU8Qrr111uXqA 1~~1a7Nr    c                &    t          | |d          S )NTlower)r   )r8   r   s     r   _solve_triangular_lowerrJ    s     AT2222r    c                   ddl }| j        dk    rt          d          | j        \  }}||k    rt          d          t	          t          | j        d         | j        d         z                       dk    sd}t          |          t	          | j        d                   }t	          | j        d                   }t          |           }d|z   }d	|z   }	d
|z   }
d|z   }d|z   }d|z   }d|z   }d|z   }d|z   }i }t          t          ||                    D ]}| j
        ||f}|dk    r^g }t          |          D ]6}|||||f}t          j        |||f|||ff||<   |                    |           7t          j        |t           |ff}|j        j        |f||||f<   t          |dz   |          D ]}t          j        |||f| j
        ||ff}|dk    r^g }t          |          D ]6}|||||f}t          j        |
||f|||ff||<   |                    |           7t          j        |t           |ff}t&          |
||f|f||||f<   t          |dz   |          D ]}| j
        ||f}|dk    r^g }t          |          D ]6}|||||f}t          j        |||f|||ff||<   |                    |           7t          j        |t           |ff}t          j        t&          |||ft          j        |fff||||f<   t          t          ||                    D ]}t          t          ||                    D ]}||k    rt          j        |||fdf||	||f<   t          j        |||fdf||
||f<   t          j        |||fdf||||f<   t          j        |	||f|
||ff||||f<   t          j        |||ff||||f<   t          j        |	||ff||||f<   ||k    rt          j        | j        d         |         | j        d         |         ff||	||f<   t          j        |||f|||ff||
||f<   t          j        | j        d         |         | j        d         |         ff||||f<   |||f||||f<   9t          j        | j        d         |         | j        d         |         ff||	||f<   t          j        | j        d         |         | j        d         |         ff||
||f<   |||f||||f<   |j                            t          j        d| j                            \  }}}t3          | |j                  }t3          | |j                  }t3          | |j                  }t5          j        |	|| g          }t9          ||	| j        | j        |          }t5          j        |
|| g          }t9          ||
| j        | j        |          } t5          j        ||| g          }t9          ||| j        | j        |          }!|| |!fS )a!  
    Compute the lu decomposition of a matrix.

    Examples
    --------

    >>> p, l, u = da.linalg.lu(x)  # doctest: +SKIP

    Returns
    -------

    p:  Array, permutation matrix
    l:  Array, lower triangular matrix with unit diagonal.
    u:  Array, upper triangular matrix
    r   Nr;   z/Dimension must be 2 to perform lu decompositionz9Input must be a square matrix to perform lu decompositionr#   zqAll chunks must be a square matrix to perform lu decomposition. Use .rechunk method to change the size of chunks.zlu-lu-zlu-p-zlu-l-zlu-u-z	lu-p-inv-zlu-l-permute-zlu-u-transpose-zlu-plu-dot-z
lu-lu-dot-r=   r>   rf   r   rg   )scipy.linalgr   r   r3   r   r   rh   r   r   r)   rp   r*   rv   r   rF   subrd   r5   lurJ  	transposerB   zerosr   r?   r   r   from_collectionsr   )"r8   scipyxdimydimmsgvdimhdimr   name_luname_pname_lname_u
name_p_invname_l_permutedname_u_transposedname_plu_dotname_lu_dotdskrH   targetprevspprevrr   r   ppllr   pp_metall_metauu_metar   lr   s"                                     r   rO  rO    s     v{{JKKKJD$t||TUUUs18A;!,--..!33@ 	 ooqx{Dqx{DQKKEGu_Fu_Fu_F u$J%-O)E1 5(L&K
C3tT??## * *&!Qq55E1XX # ##Q1a/Voq!%<vq!nMD	T""""lFS%L9F#lov6GQM q1ud## 		S 		SAfz1a0161a.AF1uuq ' 'A&1a2D!#&!Q&!Q HCILL&&&&",e="9FAq>6!RCA q1ud## 	 	Afa^F1uuq ' 'A'Aq!3D!#/1a)@61a. QCILL&&&&",e= +&1-\6*"CA	& 3tT??## 4 4s4'' 	4 	4AAvv%-%5A$JFAqL!%-%5A$JFAqL!%-%5A$JFAqL! /1fvq!nvqRSn-UOQ)*02vq!n/M%q!+,)+1~(FJ1$%%Q%'XAA/O$PFAqL! &(Vj!Q-?'1a$QFAqL!%'XAA/O$PFAqL!.5q!_OQ)**%'XAA/O$PFAqL!%'XAA/O$PFAqL!%,aOFAqL!!-	42 vQW!E!E!EFFJBBarx000Garx000Garx000G+FCqcJJJEeV1718'JJJA+FCqcJJJEeV1718'JJJA+FCqcJJJEeV1718'JJJAa7Nr    c           	     h   | j         dk    rt          d          j         dk    rY| j        d         j        d         k    rt          d          | j        d         j        d         k    rd}t          |          nt          d          t	          | j        d                   }j         dk    rdnt	          j        d                   }t          | |          }d|z   d	|z   }fd
}fd}	i }
|rt          |          D ]}t          |          D ]} |||          }|dk    rjg }t          |          D ]B}|||||f}t          j        | j	        ||f |	||          f|
|<   |
                    |           Ct          j        |t          |ff}t          | j	        ||f|f|
 |	||          <   nt          |          D ]}t          |          D ]} |||          }||dz
  k     rng }t          |dz   |          D ]B}|||||f}t          j        | j	        ||f |	||          f|
|<   |
                    |           Ct          j        |t          |ff}t          | j	        ||f|f|
 |	||          <   t!          j        |
| g          }t%          |           }t%                    }t          t'          ddgddgg| j        |          t'          ddgj        |                    }t%          | j         |j                  }t+          |j        j        |          S )a  
    Solve the equation `a x = b` for `x`, assuming a is a triangular matrix.

    Parameters
    ----------
    a : (M, M) array_like
        A triangular matrix
    b : (M,) or (M, N) array_like
        Right-hand side matrix in `a x = b`
    lower : bool, optional
        Use only data contained in the lower triangle of `a`.
        Default is to use upper triangle.

    Returns
    -------
    x : (M,) or (M, N) array
        Solution to the system `a x = b`. Shape of return matches `b`.
    r;   za must be 2 dimensionalr#   r   z'a.shape[1] and b.shape[0] must be equalz\a.chunks[1] and b.chunks[0] must be equal. Use .rechunk method to change the size of chunks.zb must be 1 or 2 dimensionalzsolve-triangular-zsolve-tri-dot-c                @    j         dk    r	j        | fS j        | |fS r"   )r   rp   )rH   rr   r   s     r   _b_initz!solve_triangular.<locals>._b_init  s(    6Q;;61961a<r    c                ,    j         dk    r| fS | |fS r"   )r   )rH   rr   r   rp   s     r   _keyzsolve_triangular.<locals>._key  s#    6Q;;7NA:r    rL  r?   likerf   rg   )r   r   r3   rh   r   r   r   r*   rv   rp   r   rF   rN  rd   rJ  r   r   rR  r   r   r?   r   )r8   r   rI  rV  vchunkshchunksr   	name_mdotro  rq  rb  rH   rr   rc  rd  r   rf  r   a_metab_metaresri   rp   s    `                    @r   solve_triangularrz  U  s   ( 	v{{2333v{{71:##FGGG8A;!(1+%%D  S//! & 7888!(1+G6Q;;aaC$4$4GQ5!!E&D !5(I               C w 
	T 
	TA7^^ 	T 	T Aq55E"1XX + +(!Q14%'Vafa^TT!QZZ$HD	T****&lFS%LAF#:QVQNF"SDDAJJ	T
	T w 	 	A7^^   Aw{??E"1q5'22 + +(!Q14%'Vafa^TT!QZZ$HD	T****&lFS%LAF)VQN#DDAJJ +D#QFKKKEQFQF
!QFQF#17@@@Aq6v666 C 1afCI666DAGAH4HHHHr    genc                H   |t          j        dt                     |rd}|dk    rt          |           \  }}nG|dk    r.t	          |           \  }}}|j                            |          }nt          d|d          t          ||d	          }t          ||          S )
a^  
    Solve the equation ``a x = b`` for ``x``. By default, use LU
    decomposition and forward / backward substitutions. When ``assume_a = "pos"``
    use Cholesky decomposition.

    Parameters
    ----------
    a : (M, M) array_like
        A square matrix.
    b : (M,) or (M, N) array_like
        Right-hand side matrix in ``a x = b``.
    sym_pos : bool, optional
        Assume a is symmetric and positive definite. If ``True``, use Cholesky
        decomposition.

        .. note::
            ``sym_pos`` is deprecated and will be removed in a future version.
            Use ``assume_a = 'pos'`` instead.

    assume_a : {'gen', 'pos'}, optional
        Type of data matrix. It is used to choose the dedicated solver.
        Note that Dask does not support 'her' and 'sym' types.

        .. versionchanged:: 2022.8.0
            ``assume_a = 'pos'`` was previously defined as ``sym_pos = True``.

    Returns
    -------
    x : (M,) or (M, N) Array
        Solution to the system ``a x = b``.  Shape of the return matches the
        shape of `b`.

    See Also
    --------
    scipy.linalg.solve
    NzThe sym_pos keyword is deprecated and should be replaced by using ``assume_a = 'pos'``.``sym_pos`` will be removed in a future version.)categoryposr{  zassume_a = zT is not a recognized matrix structure, valid structures in Dask are 'pos' and 'gen'.TrH  )	warningswarnFutureWarning	_choleskyrO  r  rv   r   rz  )r8   r   sym_posassume_arl  r   re  uys           r   solver    s    J ?"	
 	
 	
 	

  	H5||11	U		Q%%1aCGGAJJpxppp
 
 	
 
!Qd	+	+	+BAr"""r    c                x    t          | t          | j        d         | j        d         d                             S )a  
    Compute the inverse of a matrix with LU decomposition and
    forward / backward substitutions.

    Parameters
    ----------
    a : array_like
        Square matrix to be inverted.

    Returns
    -------
    ainv : Array
        Inverse of the matrix `a`.
    r   )rh   )r  r
   r3   rh   r7   s    r   invr    s1     C
18A;q>:::;;;r    c                @    t           j                            |           S r(   )r*   r5   choleskyr7   s    r   _cholesky_lowerr    s    9a   r    c                2    t          |           \  }}|r|S |S )a  
    Returns the Cholesky decomposition, :math:`A = L L^*` or
    :math:`A = U^* U` of a Hermitian positive-definite matrix A.

    Parameters
    ----------
    a : (M, M) array_like
        Matrix to be decomposed
    lower : bool, optional
        Whether to compute the upper or lower triangular Cholesky
        factorization.  Default is upper-triangular.

    Returns
    -------
    c : (M, M) Array
        Upper- or lower-triangular Cholesky factor of `a`.
    )r  )r8   rI  rl  r   s       r   r  r    s%    & Q<<DAq r    c                   | j         dk    rt          d          | j        \  }}||k    rt          d          t          t	          | j        d         | j        d         z                       dk    sd}t          |          t          | j        d                   }t          | j        d                   }t          |           }d|z   }d|z   }d	|z   }	i }
t          |          D ]}t          |          D ]}||k     r`t          t          j
        | j        d         |         | j        d         |         f
          t          |           f|
|||f<   |||f|
|	||f<   i||k    r| j        ||f}|dk    r^g }t          |          D ]6}|||||f}t          j        |||f|	||ff|
|<   |                    |           7t          j        |t"          |ff}t$          |f|
|||f<   t          j        |||ff|
|	||f<   | j        ||f}|dk    r^g }t          |          D ]6}|||||f}t          j        |||f|	||ff|
|<   |                    |           7t          j        |t"          |ff}t(          |||f|f|
|	||f<   t          j        |	||ff|
|||f<   t+          j        |	|
| g          }t+          j        ||
| g          }t          |           }t          j                            t3          ddgddgg| j        |                    }t          | |j                  }t7          ||| j        | j        |          }t7          ||	| j        | j        |          }||fS )zq
    Private function to perform Cholesky decomposition, which returns both
    lower and upper triangulars.
    r;   z5Dimension must be 2 to perform cholesky decompositionz?Input must be a square matrix to perform cholesky decompositionr   r#   zwAll chunks must be a square matrix to perform cholesky decomposition. Use .rechunk method to change the size of chunks.z	cholesky-zcholesky-lt-dot-zcholesky-upper-r2   rL     rr  rf   rg   )r   r   r3   r   r   rh   r   r   r   r*   r4   r   rp   rv   r   rF   rN  rd   r  rP  rJ  r   rR  r5   r  r   r?   r   )r8   rT  rU  rV  rW  rX  r   rp   name_lt_dot
name_upperrb  rH   rr   rc  rd  re  rf  graph_uppergraph_lowerrw  chori   rI  uppers                           r   r  r  "  s    	v{{PQQQJD$t||M
 
 	
 s18A;!,--..!33@ 	 ooqx{Dqx{DQKKED %u,K #U*J C4[[  E  Et 	E 	EA1uuBM!(1+a.!(1+a.1QRRR#A&&#D!QJ *.q!J1$%%a&!Qq55E"1XX + +*Aq!Q6%'VdAq\J1;M$ND	T****&lFS%LAF#2F";D!QJ)+a|(DJ1$%%
 &!Qq55E"1XX + +*Aq!Q6%'VdAq\J1;M$ND	T****&lFS%LAF)@4A,PV(WJ1$%#%<*a1C"DD!QJ?	EB !1*cQRPSTTTK 1$1#NNNKQF
)

Z!Q!Q(8fUUU
V
VC1CI...D+t1718$OOOE+zPTUUUE%<r    c                    | d d d         S )Nr   rb   s    r   _reverser  s  s    TTrT7Nr    c           	     p   t          |           \  }}t          ||j                                                            |                    }||                     |          z
  }t          |dz                                d|j        dk              }t          | |          }d|z   }|ft          j
        j        |j        ddffi}t          j        |||g          }	t          |	|ddt                     }
d	|z   }|j                                        }|dft"          t          j        t          j
        j        t          j        |j        ddf|j        ddfffffi}t          j        ||||g          }	t)          |d          }t          |	||j        d         f|j        d         |
          }|||
|fS )a7  
    Return the least-squares solution to a linear matrix equation using
    QR decomposition.

    Solves the equation `a x = b` by computing a vector `x` that
    minimizes the Euclidean 2-norm `|| b - a x ||^2`.  The equation may
    be under-, well-, or over- determined (i.e., the number of
    linearly independent rows of `a` can be less than, equal to, or
    greater than its number of linearly independent columns).  If `a`
    is square and of full rank, then `x` (but for round-off error) is
    the "exact" solution of the equation.

    Parameters
    ----------
    a : (M, N) array_like
        "Coefficient" matrix.
    b : {(M,), (M, K)} array_like
        Ordinate or "dependent variable" values. If `b` is two-dimensional,
        the least-squares solution is calculated for each of the `K` columns
        of `b`.

    Returns
    -------
    x : {(N,), (N, K)} Array
        Least-squares solution. If `b` is two-dimensional,
        the solutions are in the `K` columns of `x`.
    residuals : {(1,), (K,)} Array
        Sums of residuals; squared Euclidean 2-norm for each column in
        ``b - a*x``.
        If `b` is 1-dimensional, this is a (1,) shape array.
        Otherwise the shape is (K,).
    rank : Array
        Rank of matrix `a`.
    s : (min(M, N),) Array
        Singular values of `a`.
    r;   r   r#   r  keepdimszlstsq-rank-rL  r   )r3   rh   r?   zlstsq-singular-rg   )r6   rz  r  conjrv   absrd   r   r   r*   r5   matrix_rankrp   r   rR  r   r   r  sqrteigvalshr   r3   )r8   r   r   r   r   	residualsr   rnamerdskr   ranksnamertsdskri   r   s                   r   lstsqr  w  s   J a55DAqACHHJJNN1--..AAEE!HHIIqL!!%%1qv{%CCIQNNE
 E!EHry,qvq!n=>D+E4qcJJJER#>>>D %E	
B	
Wry)BFRWaOafaQR^+TUV
D +E4r1gNNNE9a((DeU171:-
NNNAiq  r    c                v
   |"t          t          | j                            }n5t          |t                    rt          |          f}nt          |          }t          |          dk    rt          d          |dk    r$d }t          |          dk    rt          d          |                     t          j
        | j        t                              }|,t          |          dz                      ||          dz  }n3|dk    rmt          |          dk    rt          d          | j        dk    rt          d	          t!          |           d         d                              |
          }n|t          j        k    rt          |          }t          |          dk    r|                    ||          }nu|                    |d         d                              |d         d          }|du r|                    |          }n!|t          j         k    rt          |          }t          |          dk    r|                    ||          }n|                    |d         d                              |d         d          }|du r|                    |          }n|dk    rWt          |          dk    rt          d          |dk                        |j                                      ||          }n$|dk    rt          |          }t          |          dk    r|                    ||          }n|                    |d         d                              |d         d          }|du r|                    |          }nt          |          dk    rg|dk    rat          |                              |d         d                              |d         d          }|du r|                    |          }nt          |          dk    rP|dk    rJ| j        dk    rt          d	          t!          |           d         d                              |
          }nt          |          dk    rP|dk    rJ| j        dk    rt          d	          t!          |           d         d                              |
          }nOt          |          dk    rt          d          t          |          |z                      ||          d|z  z  }|S )Nr;   z&Improper number of dimensions to norm.fror#   zInvalid norm order for vectors.r  g      ?nucz+SVD based norm not implemented for ndim > 2)r  Tr   Fr  z Invalid norm order for matrices.r  g      ?)r]   r   r   r  r   r   r   r   r$  r*   promote_typesr?   floatr  rd   r9  r   infr   squeezer)   )r   ordr  r  r   s        r   normr    s   |U16]]##	D&	!	! D		|T{{
4yy1}}ABBB
e||t99>>>??? 	
!!'51122A
{VVq[4(;;sB	t99>>>???6A::%&STTTFF1IdO22	FFt99>>4(33AA47T2266DGd6SSA5  II4I((	FFt99>>4(33AA47T2266DGd6SSA5  II4I((	t99>>?@@@!VOOAG$$((dX(FF	FFt99>>4(33AA47T2266DGd6SSA5  II4I((	TaC2IIFFJJDGdJ3377T!Wt7TTu		t	$$A	TaC1HH6A::%&STTTFF1IdO22	TaC2II6A::%&STTTFF1IdO22t99>>?@@@VVs]TH==#)LHr    )FNr(   )r  r  )r  r   r  NF)r  r   r  NFT)T)F)Nr{  )NNF)>
__future__r   rF   r  	functoolsr   numbersr   numpyr*   tlzr   dask.array.corer   r   r   r	   dask.array.creationr
   dask.array.randomr   r   dask.array.utilsr   r   r   r   	dask.baser   r   dask.blockwiser   dask.delayedr   dask.highlevelgraphr   
dask.utilsr   r   r   r&   r0   r9   r   r  r  r0  r7  r6   r   rJ  rO  rz  r  r  r  r  r  r  r  r5   r  r   r    r   <module>r     sR   " " " " " "                       E E E E E E E E E E E E # # # # # # 6 6 6 6 6 6 6 6            % $ $ $ $ $ $ $ $ $ $ $ $ $             . . . . . . * * * * * * * *& & &$ $ $) ) )  E E E EPi i i iX= = = =H 	X X X X| 	V V V Vr$
 $
 $
NZ Z Z Zz3 3 3E E EP^I ^I ^I ^IB9# 9# 9# 9#x< < <$! ! !   4N N Nb  B! B! B!J biK K K K K Kr    