a :jgt@sgdZddlZddlZddlZddlZddlmZddlmZddl m Z m Z m Z ddlm Zejejdd Zd d Zeed d ZddZeeddZddZeeddZddZdddddZeedddddZeedddddZd=dddd d!Zeed>dddd"d#Zeejd$ejZeej d$ej Z!eej"d$ej"Z#d%d&Z$gfd'd(Z%d)d*Z&d+d,Z'd-d.Z(d?d/d0Z)d@d1d2Z*d3d4Z+ee+d5d6Z,d7d8Z-d9d:Z.d;d<Z/dS)A) atleast_1d atleast_2d atleast_3dblockhstackstackvstackN)numeric) overrides)array asanyarraynormalize_axis_index) fromnumericnumpy)modulecGs|SNarysrr@/usr/local/lib/python3.9/site-packages/numpy/_core/shape_base.py_atleast_1d_dispatchersrcGsZg}|D]0}t|}|jdkr*|d}n|}||qt|dkrN|dSt|SdS)a Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. Parameters ---------- arys1, arys2, ... : array_like One or more input arrays. Returns ------- ret : ndarray An array, or tuple of arrays, each with ``a.ndim >= 1``. Copies are made only if necessary. See Also -------- atleast_2d, atleast_3d Examples -------- >>> np.atleast_1d(1.0) array([1.]) >>> x = np.arange(9.0).reshape(3,3) >>> np.atleast_1d(x) array([[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]) >>> np.atleast_1d(x) is x True >>> np.atleast_1d(1, [3, 4]) (array([1]), array([3, 4])) rr N)r ndimreshapeappendlentuplerresZaryresultrrrrs(    rcGs|Srrrrrr_atleast_2d_dispatcherMsr cGszg}|D]P}t|}|jdkr,|dd}n"|jdkrJ|tjddf}n|}||qt|dkrn|dSt|SdS)a] View inputs as arrays with at least two dimensions. Parameters ---------- arys1, arys2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved. Returns ------- res, res2, ... : ndarray An array, or tuple of arrays, each with ``a.ndim >= 2``. Copies are avoided where possible, and views with two or more dimensions are returned. See Also -------- atleast_1d, atleast_3d Examples -------- >>> np.atleast_2d(3.0) array([[3.]]) >>> x = np.arange(3.0) >>> np.atleast_2d(x) array([[0., 1., 2.]]) >>> np.atleast_2d(x).base is x True >>> np.atleast_2d(1, [1, 2], [[1, 2]]) (array([[1]]), array([[1, 2]]), array([[1, 2]])) rr Nr rr_nxnewaxisrrrrrrrrQs&    rcGs|Srrrrrr_atleast_3d_dispatchersr$cGsg}|D]z}t|}|jdkr.|ddd}nJ|jdkrP|tjddtjf}n(|jdkrt|ddddtjf}n|}||qt|dkr|dSt|SdS)a View inputs as arrays with at least three dimensions. Parameters ---------- arys1, arys2, ... : array_like One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved. Returns ------- res1, res2, ... : ndarray An array, or tuple of arrays, each with ``a.ndim >= 3``. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape ``(N,)`` becomes a view of shape ``(1, N, 1)``, and a 2-D array of shape ``(M, N)`` becomes a view of shape ``(M, N, 1)``. See Also -------- atleast_1d, atleast_2d Examples -------- >>> np.atleast_3d(3.0) array([[[3.]]]) >>> x = np.arange(3.0) >>> np.atleast_3d(x).shape (1, 3, 1) >>> x = np.arange(12.0).reshape(4,3) >>> np.atleast_3d(x).shape (4, 3, 1) >>> np.atleast_3d(x).base is x.base # x is a reshape, so not base itself True >>> for arr in np.atleast_3d([1, 2], [[1, 2]], [[[1, 2]]]): ... print(arr, arr.shape) # doctest: +SKIP ... [[[1] [2]]] (1, 2, 1) [[[1] [2]]] (1, 2, 1) [[[1 2]]] (1, 1, 2) rr Nr!rrrrrs2     rcCst|dstdt|S)N __getitem__zJarrays to stack must be passed as a "sequence" type such as list or tuple.)hasattr TypeErrorr)arraysrrr_arrays_for_stack_dispatchers r*dtypecastingcCst|Sr)r*)tupr,r-rrr_vhstack_dispatchersr/Z same_kindcCs*t|}t|ts|f}tj|d||dS)a Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape `(N,)` have been reshaped to `(1,N)`. Rebuilds arrays divided by `vsplit`. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions `concatenate`, `stack` and `block` provide more general stacking and concatenation operations. Parameters ---------- tup : sequence of ndarrays The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length. dtype : str or dtype If provided, the destination array will have this dtype. Cannot be provided together with `out`. .. versionadded:: 1.24 casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional Controls what kind of data casting may occur. Defaults to 'same_kind'. .. versionadded:: 1.24 Returns ------- stacked : ndarray The array formed by stacking the given arrays, will be at least 2-D. See Also -------- concatenate : Join a sequence of arrays along an existing axis. stack : Join a sequence of arrays along a new axis. block : Assemble an nd-array from nested lists of blocks. hstack : Stack arrays in sequence horizontally (column wise). dstack : Stack arrays in sequence depth wise (along third axis). column_stack : Stack 1-D arrays as columns into a 2-D array. vsplit : Split an array into multiple sub-arrays vertically (row-wise). Examples -------- >>> a = np.array([1, 2, 3]) >>> b = np.array([4, 5, 6]) >>> np.vstack((a,b)) array([[1, 2, 3], [4, 5, 6]]) >>> a = np.array([[1], [2], [3]]) >>> b = np.array([[4], [5], [6]]) >>> np.vstack((a,b)) array([[1], [2], [3], [4], [5], [6]]) rr+)r isinstancerr" concatenater.r,r-arrsrrrrsA rcCsRt|}t|ts|f}|r<|djdkr>> a = np.array((1,2,3)) >>> b = np.array((4,5,6)) >>> np.hstack((a,b)) array([1, 2, 3, 4, 5, 6]) >>> a = np.array([[1],[2],[3]]) >>> b = np.array([[4],[5],[6]]) >>> np.hstack((a,b)) array([[1, 4], [2, 5], [3, 6]]) rr r+N)rr0rrr"r1r2rrrr"s = rcCs&t|}|dur"t|}|||Sr)r*listr)r)axisoutr,r-rrr_stack_dispatcheris  r7csdd|D}|stddd|D}t|dkr>> arrays = [np.random.randn(3, 4) for _ in range(10)] >>> np.stack(arrays, axis=0).shape (10, 3, 4) >>> np.stack(arrays, axis=1).shape (3, 10, 4) >>> np.stack(arrays, axis=2).shape (3, 4, 10) >>> a = np.array([1, 2, 3]) >>> b = np.array([4, 5, 6]) >>> np.stack((a, b)) array([[1, 2, 3], [4, 5, 6]]) >>> np.stack((a, b), axis=-1) array([[1, 4], [2, 5], [3, 6]]) cSsg|] }t|qSr)r .0arrrrr zstack..z need at least one array to stackcSsh|] }|jqSr)shaper8rrr r<zstack..r z)all input arrays must have the same shaperNcsg|] }|qSrrr8slrrr;r<)r5r6r,r-) ValueErrorrrrslicer"r#r1)r)r5r6r,r-shapes result_ndimZexpanded_arraysrr?rrssG   r __wrapped__cCsddd|D}d|S)zM Convert a list of indices ``[0, 1, 2]`` into ``"arrays[0][1][2]"``. css |]}|durd|VqdS)Nz[{}])format)r9irrr r<z&_block_format_index..r))join)indexZidx_strrrr_block_format_indexsrLc s t|tur tdtnt|turt|dkrȇfddt|D}t|\}}}|D]\\}}}||7}||kr~|}t|t|krt dt|t|t||ddur`|}q`|||fSt|turt|dkrdgddfSt |}t ||fSdS)a Recursive function checking that the depths of nested lists in `arrays` all match. Mismatch raises a ValueError as described in the block docstring below. The entire index (rather than just the depth) needs to be calculated for each innermost list, in case an error needs to be raised, so that the index of the offending list can be printed as part of the error. Parameters ---------- arrays : nested list of arrays The arrays to check parent_index : list of int The full index of `arrays` within the nested lists passed to `_block_check_depths_match` at the top of the recursion. Returns ------- first_index : list of int The full index of an element from the bottom of the nesting in `arrays`. If any element at the bottom is an empty list, this will refer to it, and the last index along the empty axis will be None. max_arr_ndim : int The maximum of the ndims of the arrays nested in `arrays`. final_size: int The number of elements in the final array. This is used the motivate the choice of algorithm used using benchmarking wisdom. z{} is a tuple. Only lists can be used to arrange blocks, and np.block does not allow implicit conversion from tuple to ndarray.rc3s"|]\}}t||gVqdSr)_block_check_depths_match)r9rHr: parent_indexrrrI sz,_block_check_depths_match..zcList depths are mismatched. First element was at depth {}, but there is an element at depth {} ({})N) typerr(rGrLr4r enumeratenextrA_size_ndim) r)rOZ idxs_ndimsZ first_indexZ max_arr_ndim final_sizerKrsizerrNrrMs<    rMcCst||dddS)NT)ZndmincopyZsubok)r )arrrr _atleast_nd(srZcCstt|Sr)r4 itertools accumulate)valuesrrr _accumulate.sr^csfdd|D}|d}|d|ddtfdd|Dr^tdt|f|dd}t|}d dtdg||D}||fS) aGiven array shapes, return the resulting shape and slices prefixes. These help in nested concatenation. Returns ------- shape: tuple of int This tuple satisfies:: shape, _ = _concatenate_shapes([arr.shape for shape in arrs], axis) shape == concatenate(arrs, axis).shape slice_prefixes: tuple of (slice(start, end), ) For a list of arrays being concatenated, this returns the slice in the larger array at axis that needs to be sliced into. For example, the following holds:: ret = concatenate([a, b, c], axis) _, (sl_a, sl_b, sl_c) = concatenate_slices([a, b, c], axis) ret[(slice(None),) * axis + sl_a] == a ret[(slice(None),) * axis + sl_b] == b ret[(slice(None),) * axis + sl_c] == c These are called slice prefixes since they are used in the recursive blocking algorithm to compute the left-most slices during the recursion. Therefore, they must be prepended to rest of the slice that was computed deeper in the recursion. These are returned as tuples to ensure that they can quickly be added to existing slice tuple without creating a new tuple every time. csg|] }|qSrrr9r=r5rrr;Vr<z'_concatenate_shapes..rNr c3s2|]*}|dkp(|ddkVqdS)Nr rr_r5Zfirst_shape_postZfirst_shape_prerrrI]sz&_concatenate_shapes..z/Mismatched array shapes in block along axis {}.cSsg|]\}}t||fqSr)rB)r9startendrrrr;es)anyrArGsumr^zip)rCr5Z shape_at_axisZ first_shaper=Zoffsets_at_axisslice_prefixesrrar_concatenate_shapes2s$$  rhc skrntfdd|D\}}}}t||\}}ddt||D}ttj|}|||fSt|} | jdg| gfSdS)a Returns the shape of the final array, along with a list of slices and a list of arrays that can be used for assignment inside the new array Parameters ---------- arrays : nested list of arrays The arrays to check max_depth : list of int The number of nested lists result_ndim : int The number of dimensions in thefinal array. Returns ------- shape : tuple of int The shape that the final array will take on. slices: list of tuple of slices The slices into the full array required for assignment. These are required to be prepended with ``(Ellipsis, )`` to obtain to correct final index. arrays: list of ndarray The data to assign to each slice of the full array csg|]}t|dqSr )_block_info_recursionr8depth max_depthrDrrr;sz)_block_info_recursion..cSs"g|]\}}|D] }||qqSrr)r9Z slice_prefixZ inner_slices the_slicerrrr;srN)rfrh functoolsreduceoperatoraddrZr=) r)rmrDrlrCslicesr5r=rgr:rrkrrjks    rjcs>kr0fdd|D}t| dSt|SdS)aZ Internal implementation of block based on repeated concatenation. `arrays` is the argument passed to block. `max_depth` is the depth of nested lists within `arrays` and `result_ndim` is the greatest of the dimensions of the arrays in `arrays` and the depth of the lists in `arrays` (see block docstring for details). csg|]}t|dqSri)_blockr8rkrrr;sz_block..r`N) _concatenaterZ)r)rmrDrlr3rrkrrts rtccs0t|tur&|D]}t|EdHqn|VdSr)rQr4_block_dispatcher)r)Z subarraysrrrrvs rvcCs8t|\}}}}||dkr(t|||St|||SdS)ar Assemble an nd-array from nested lists of blocks. Blocks in the innermost lists are concatenated (see `concatenate`) along the last dimension (-1), then these are concatenated along the second-last dimension (-2), and so on until the outermost list is reached. Blocks can be of any dimension, but will not be broadcasted using the normal rules. Instead, leading axes of size 1 are inserted, to make ``block.ndim`` the same for all blocks. This is primarily useful for working with scalars, and means that code like ``np.block([v, 1])`` is valid, where ``v.ndim == 1``. When the nested list is two levels deep, this allows block matrices to be constructed from their components. .. versionadded:: 1.13.0 Parameters ---------- arrays : nested list of array_like or scalars (but not tuples) If passed a single ndarray or scalar (a nested list of depth 0), this is returned unmodified (and not copied). Elements shapes must match along the appropriate axes (without broadcasting), but leading 1s will be prepended to the shape as necessary to make the dimensions match. Returns ------- block_array : ndarray The array assembled from the given blocks. The dimensionality of the output is equal to the greatest of: * the dimensionality of all the inputs * the depth to which the input list is nested Raises ------ ValueError * If list depths are mismatched - for instance, ``[[a, b], c]`` is illegal, and should be spelt ``[[a, b], [c]]`` * If lists are empty - for instance, ``[[a, b], []]`` See Also -------- concatenate : Join a sequence of arrays along an existing axis. stack : Join a sequence of arrays along a new axis. vstack : Stack arrays in sequence vertically (row wise). hstack : Stack arrays in sequence horizontally (column wise). dstack : Stack arrays in sequence depth wise (along third axis). column_stack : Stack 1-D arrays as columns into a 2-D array. vsplit : Split an array into multiple sub-arrays vertically (row-wise). Notes ----- When called with only scalars, ``np.block`` is equivalent to an ndarray call. So ``np.block([[1, 2], [3, 4]])`` is equivalent to ``np.array([[1, 2], [3, 4]])``. This function does not enforce that the blocks lie on a fixed grid. ``np.block([[a, b], [c, d]])`` is not restricted to arrays of the form:: AAAbb AAAbb cccDD But is also allowed to produce, for some ``a, b, c, d``:: AAAbb AAAbb cDDDD Since concatenation happens along the last axis first, `block` is *not* capable of producing the following directly:: AAAbb cccbb cccDD Matlab's "square bracket stacking", ``[A, B, ...; p, q, ...]``, is equivalent to ``np.block([[A, B, ...], [p, q, ...]])``. Examples -------- The most common use of this function is to build a block matrix >>> A = np.eye(2) * 2 >>> B = np.eye(3) * 3 >>> np.block([ ... [A, np.zeros((2, 3))], ... [np.ones((3, 2)), B ] ... ]) array([[2., 0., 0., 0., 0.], [0., 2., 0., 0., 0.], [1., 1., 3., 0., 0.], [1., 1., 0., 3., 0.], [1., 1., 0., 0., 3.]]) With a list of depth 1, `block` can be used as `hstack` >>> np.block([1, 2, 3]) # hstack([1, 2, 3]) array([1, 2, 3]) >>> a = np.array([1, 2, 3]) >>> b = np.array([4, 5, 6]) >>> np.block([a, b, 10]) # hstack([a, b, 10]) array([ 1, 2, 3, 4, 5, 6, 10]) >>> A = np.ones((2, 2), int) >>> B = 2 * A >>> np.block([A, B]) # hstack([A, B]) array([[1, 1, 2, 2], [1, 1, 2, 2]]) With a list of depth 2, `block` can be used in place of `vstack`: >>> a = np.array([1, 2, 3]) >>> b = np.array([4, 5, 6]) >>> np.block([[a], [b]]) # vstack([a, b]) array([[1, 2, 3], [4, 5, 6]]) >>> A = np.ones((2, 2), int) >>> B = 2 * A >>> np.block([[A], [B]]) # vstack([A, B]) array([[1, 1], [1, 1], [2, 2], [2, 2]]) It can also be used in places of `atleast_1d` and `atleast_2d` >>> a = np.array(0) >>> b = np.array([1]) >>> np.block([a]) # atleast_1d(a) array([0]) >>> np.block([b]) # atleast_1d(b) array([1]) >>> np.block([[a]]) # atleast_2d(a) array([[0]]) >>> np.block([[b]]) # atleast_2d(b) array([[1]]) iN) _block_setup_block_slicing_block_concatenate)r) list_ndimrDrVrrrrs   rcCsNt|\}}}t|}|r8|ddur8tdt|t||}||||fS)zD Returns (`arrays`, list_ndim, result_ndim, final_size) rPNzList at {} cannot be empty)rMrrArGrLmax)r)Z bottom_indexZarr_ndimrVrzrDrrrrwos rwc Cst|||\}}}tjdd|D}tdd|D}tdd|D}|rV|sVdnd}tj|||d} t||D]\} } | | tf| <qt| S) NcSsg|] }|jqSr)r,r8rrrr;r<z"_block_slicing..css|]}|jdVqdS)Z F_CONTIGUOUSNflagsr8rrrrIr<z!_block_slicing..css|]}|jdVqdS)Z C_CONTIGUOUSNr|r8rrrrIr<FC)r=r,order)rjr"Z result_typeallemptyrfEllipsis) r)rzrDr=rsr,ZF_orderZC_orderrrrnr:rrrrxs rxcCs t|||}|dkr|}|S)Nr)rtrX)r)rzrDrrrrrys ry)NN)rN)r)r)0__all__ror[rqwarningsrFr r"r Z multiarrayr r rrZ_from_nxpartialZarray_function_dispatchrrr rr$rr*r/rrr7rgetattrrWrTrrUr1rurLrMrZr^rhrjrtrvrrwrxryrrrrsd    5 5 CFF Z L9 5   1