
    Cd*                        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m	Z	 d dl
mZ d dlZd dl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mZ dZd Zd Z d Z!ddZ"dS )    )annotationsN)Counter)reduce)product)mul)config)Arraynormalize_chunks)meta_from_array)tokenize)flatten)HighLevelGraph)Mparse_bytesa  
Dask's reshape only supports operations that merge or split existing dimensions
evenly. For example:

>>> x = da.ones((6, 5, 4), chunks=(3, 2, 2))
>>> x.reshape((3, 2, 5, 4))  # supported, splits 6 into 3 & 2
>>> x.reshape((30, 4))       # supported, merges 6 & 5 into 30
>>> x.reshape((4, 5, 6))     # unsupported, existing dimensions split unevenly

To work around this you may call reshape in multiple passes, or (if your data
is small enough) call ``compute`` first and handle reshaping in ``numpy``
directly.
c           
         t          d D                       sJ t                     dz
  }t          |          dz
  }d t          t                               D             }d t          t          |                    D             }|dk    s|dk    r |         ||         k    r!|         ||<   |         ||<   |dz  }|dz  }@ |         }||         }|dk    rd||<   |dz  }n'|dk    rd||<   |dz  }n||k     r|dz
  }	|	dk    rSt          t           |	|dz                      |k     r/|	dz  }	|	dk    r$t          t           |	|dz                      |k     /t          t           |	|dz                      |k    rt          t                    t           fdt          |          D                       r\t          |dz             D ]}
|
         ||
<   |         t          j        t          t          |	|                             z  ||<   nt          |	dz   |dz             D ]}
 |
         f||
<   t          t          t          t          |	dz   |dz                                }t          |	         |          ||	<   t          t           |	dz   |dz                      t          fd||	         D                       ||<   |dz  }|	dz
  }n,||k    r%|dz
  }|dk    rSt          t          |||dz                      |k     r/|dz  }|dk    r$t          t          |||dz                      |k     /t          t          |||dz                      |k    rt          t                    t          t          ||dz   |dz                      t          |                   ||<   t          |dz   |dz             D ]}
||
         f||
<   t          fd	||         D                       ||<   |dz
  }|dz  }|dk    |dk    t          |          t          |          fS )
Nc              3  @   K   | ]}t          |t                    V  d S N)
isinstancetuple.0cs     2lib/python3.11/site-packages/dask/array/reshape.py	<genexpr>z"reshape_rechunk.<locals>.<genexpr>$   s,      66z!U##666666       c                    g | ]}d S r    r   is     r   
<listcomp>z#reshape_rechunk.<locals>.<listcomp>'   s    999t999r   c                    g | ]}d S r   r   r   s     r   r!   z#reshape_rechunk.<locals>.<listcomp>(   s    ;;;;;;r   r   r   c              3  V   K   | ]#}t          |                   |         k    V  $d S r   )len)r   r    inchunksinshapes     r   r   z"reshape_rechunk.<locals>.<genexpr>D   s8      EEa3x{##wqz1EEEEEEr   c              3  "   K   | ]	}|z  V  
d S r   r   )r   r   prods     r   r   z"reshape_rechunk.<locals>.<genexpr>R   s8       - -!"D1H- - - - - -r   c              3  "   K   | ]	}|z  V  
d S r   r   )r   r   css     r   r   z"reshape_rechunk.<locals>.<genexpr>f   s'      +Q+QAG+Q+Q+Q+Q+Q+Qr   )allr%   ranger   r   NotImplementedError_not_implemented_messagemathr)   mapexpand_tupler   contract_tuple)r'   outshaper&   iioiresult_inchunksresult_outchunksdindoutileftr    chunk_reductionoleftr+   r)   s   ` `          @@r   reshape_rechunkr>   #   s   66X66666666	W	B	X	B99U3w<<%8%8999O;;eCMM&:&:;;;
''R1WW2;(2,&&"*2,OB#+B<R !GB!GBbk|!88"&OB!GBBQYY#'R !GBB4ZZFE

vc7526>+BCCdJJ
 

vc7526>+BCCdJJ c7526>233t;;)*BCCC EEEEE599EEEEE rAv 5 5A)1!OA&&'/|diXeBh/007 7 ( $$ uqy"q&11 7 7A*1!*OA&&"(c#x	BQRF@R7S.T.T"U"U)5huo)W)W&c7519rAv+=#>??', - - - -&5e&<- - - ( ( $ !GBBB4ZZFE1**Xeb1fn-E!F!F!L!L
 1**Xeb1fn-E!F!F!L!Lc8EBFN344;;)*BCCCXeai"q&&89::B"0"r"B"BOB519b1f-- 5 5'/{n ##&++Q+Q+Q+Q_R=P+Q+Q+Q&Q&QU#B!GB ''R1WWB !!5)9#:#:::r   c                f   |dk    r| S g }| D ]t}|}t          ||z  d          }|d|z  k    r=|                    t          |                     |t          |          z  }|d|z  k    =|r|                    |           ut          |           t          |          k    sJ t	          |          S )z

    >>> expand_tuple((2, 4), 2)
    (1, 1, 2, 2)

    >>> expand_tuple((2, 4), 3)
    (1, 1, 1, 1, 2)

    >>> expand_tuple((3, 4), 2)
    (1, 2, 2, 2)

    >>> expand_tuple((7, 4), 3)
    (2, 2, 3, 1, 1, 2)
    r      )maxappendintsumr   )chunksfactoroutr   xparts         r   r2   r2   n   s     {{
C  1v:q!!1t8mmJJs4yy!!!TNA 1t8mm  	JJqMMMv;;#c((""""::r   c                    t          |           |z  dk    sJ g }d}| D ]-}||z  }||z  }||z  }||z  }|r|                    |           .t          |          S )zReturn simple chunks tuple such that factor divides all elements

    Examples
    --------

    >>> contract_tuple((2, 2, 8, 4), 4)
    (4, 8, 4)
    r   )rD   rB   r   )rE   rF   rG   residualchunkdivgoods          r   r3   r3      s     v;;1$$$$
CH  vo6>| 	JJt::r   Tc                4	   ddl m} ddlm} t	          t          ||                    }d |D             }t          |          t          |          k     rt          |          t          |          z
  dk    rt          d          t          |          dk    r| j        dk    r| S  || j	        t          t          |d          z            t	          fd|D                       }t          j        t          | j                            r$t          dt!          | j                  z            t          t          |d          | j	        k    rt          d	          | j        |k    r| S t#          | t          |                    }d
t%          | |          z   }| j        dk    rt)          t+          |                                                     }	|fdt          |          z  z   t.          j        |	|fi}
t	          d |D                       }t3          j        ||
| g          }t7          ||||          S t          | j                  }t          |          }|s5||k    r/|                     d t;          ||z
            D                       } t=          | j        || j                  \  }}t          t          d |D                       | j         j!        z  }|7tE          tG          j$        d                    }tG          j$        dd          }ntE          |          }d}||k    r|d}tK          j&        ||d           n|rtO          |          tO          |          z  }g }|D ]I}||         dk    r&|(                    |           ||xx         dz  cc<   4|(                    d           JtS          |||| j         |          }|                     |          }tU          tW          |j,        ggd |D             R            }tU          tW          |ggd |D             R            }tU          tW          |           }d t[          |||          D             }
t3          j        ||
|g          }t7          ||||          S )ab  Reshape array to new shape

    Parameters
    ----------
    shape : int or tuple of ints
        The new shape should be compatible with the original shape. If
        an integer, then the result will be a 1-D array of that length.
        One shape dimension can be -1. In this case, the value is
        inferred from the length of the array and remaining dimensions.
    merge_chunks : bool, default True
        Whether to merge chunks using the logic in :meth:`dask.array.rechunk`
        when communication is necessary given the input array chunking and
        the output shape. With ``merge_chunks==False``, the input array will
        be rechunked to a chunksize of 1, which can create very many tasks.
    limit: int (optional)
        The maximum block size to target in bytes. If no limit is provided,
        it defaults to using the ``array.chunk-size`` Dask config value.

    Notes
    -----
    This is a parallelized version of the ``np.reshape`` function with the
    following limitations:

    1.  It assumes that the array is stored in `row-major order`_
    2.  It only allows for reshapings that collapse or merge dimensions like
        ``(1, 2, 3, 4) -> (1, 6, 4)`` or ``(64,) -> (4, 4, 4)``

    .. _`row-major order`: https://en.wikipedia.org/wiki/Row-_and_column-major_order

    When communication is necessary this algorithm depends on the logic within
    rechunk.  It endeavors to keep chunk sizes roughly the same when possible.

    See :ref:`array-chunks.reshaping` for a discussion the tradeoffs of
    ``merge_chunks``.

    See Also
    --------
    dask.array.rechunk
    numpy.reshape
    r   )PerformanceWarning)sanitize_indexc                    g | ]
}|d k    |S )r   )r   ss     r   r!   zreshape.<locals>.<listcomp>   s    ///qBww1wwwr   r   z&can only specify one unknown dimensionc              3  ,   K   | ]}|d k    rn|V  dS )rS   Nr   )r   rT   missing_sizes     r   r   zreshape.<locals>.<genexpr>   s/      DDa2ggll1DDDDDDr   z_Array chunk size or shape is unknown. shape: %s

Possible solution with x.compute_chunk_sizes()z)total size of new array must be unchangedzreshape-)r   c              3     K   | ]}|fV  d S r   r   )r   ds     r   r   zreshape.<locals>.<genexpr>   s$      ++t++++++r   )dependencies)metac                    i | ]}|d S r#   r   r   s     r   
<dictcomp>zreshape.<locals>.<dictcomp>   s    777q!777r   c                ,    g | ]}t          |          S r   )rA   r   s     r   r!   zreshape.<locals>.<listcomp>   s    )D)D)DQ#a&&)D)D)Dr   Nzarray.chunk-sizez array.slicing.split-large-chunksTa  Reshaping is producing a large chunk. To accept the large
chunk and silence this warning, set the option
    >>> with dask.config.set(**{'array.slicing.split_large_chunks': False}):
    ...     array.reshape(shape)

To avoid creating the large chunks, set the option
    >>> with dask.config.set(**{'array.slicing.split_large_chunks': True}):
    ...     array.reshape(shape)Explictly passing ``limit`` to ``reshape`` will also silence this warning
    >>> array.reshape(shape, limit='128 MiB')   )
stacklevelauto)shapelimitdtypeprevious_chunksc                F    g | ]}t          t          |                    S r   r-   r%   r   s     r   r!   zreshape.<locals>.<listcomp>(  s$    'H'H'H!c!ff'H'H'Hr   c                F    g | ]}t          t          |                    S r   rf   r   s     r   r!   zreshape.<locals>.<listcomp>)  s$    %G%G%GeCFFmm%G%G%Gr   c                6    i | ]\  }}}|t           j        ||fS r   )r   reshape)r   abra   s       r   r\   zreshape.<locals>.<dictcomp>+  s)    
V
V
V1e1qy!U#
V
V
Vr   ).dask.array.corerP   dask.array.slicingrQ   r   r1   r%   
ValueErrorndimsizer   r   npisnanrD   ra   strr   r   npartitionsnextr   __dask_keys__r   ri   r   from_collectionsr	   rechunkr-   r>   rE   rc   itemsizer   r   getwarningswarnr   rB   r
   listr   namezip)rH   ra   merge_chunksrb   rP   rQ   known_sizesrZ   r~   keydskrE   graphr9   r:   r&   	outchunksmax_chunksize_in_bytessplitmsgmatching_chunks
chunk_planrG   x2in_keysout_keysshapesrV   s                              @r   ri   ri      s   T 322222111111#ne,,--E//e///K
;#e**$$u::K(((1,,EFFF u::??qv{{H%~afvc;/J/J&JKKDDDDeDDDDD	xAG 
=?B17||L
 
 	

 c5!&&DEEEw%1c%jj))DE***D}71??,,--..wE

**QYU,CD++U+++++/cLLLUD&t4444 ag,,Cu::D 9C$JJII77U3:%6%677788)!'5!(CCHi#C)D)D))D)D)DEEHXX}FJ'9::;;
=tDDE""%%=@  M#1a@@@@@ 	%h//')2D2DDOJ  . ."3'!++%%c***#C(((A-((((%%f----(g (  I 
8		B 7BG9I'H'Hx'H'H'HIIIJJGGTFH%G%GY%G%G%GHHHIIH'9%&&F
V
Vs8Wf7U7U
V
V
VC+D#RDIIIEid3333r   )TN)#
__future__r   r0   r{   collectionsr   	functoolsr   	itertoolsr   operatorr   numpyrq   daskr   rl   r	   r
   dask.array.utilsr   	dask.baser   	dask.corer   dask.highlevelgraphr   
dask.utilsr   r   r/   r>   r2   r3   ri   r   r   r   <module>r      sd   " " " " " "                                     3 3 3 3 3 3 3 3 , , , , , ,             . . . . . . % % % % % % % % H; H; H;V  >  .J4 J4 J4 J4 J4 J4r   