U
    Gvfh                     @   sB  d dl Zd dlmZ d dlmZmZ d dlmZ d dl	Z	d.ddZ
d/ddZd0d	d
Zd1ddZd2ddZdd Zdd Zdd Zdd Zdd Zdd ZdZddZd eefddZd Zd!Zd"dZeeeeZe	jee	jjd#d$Zd%Zd&Zd'dZeeeeZe	jee	jjd(d$Zd)dZd d*d(dd d+g fd,d-Z dS )3    N)wraps)FunctionDoc	Parameter)_contains_nanc                 C   s6   t | |d}|dkr"|gt|  }dd t| |D S )P
    Broadcast shapes of arrays, ignoring incompatibility of specified axes
    axisNc                 S   s   g | ]\}}t ||qS  )npbroadcast_to).0array	new_shaper	   r	   @/tmp/pip-unpacked-wheel-96ln3f52/scipy/stats/_axis_nan_policy.py
<listcomp>   s   z%_broadcast_arrays.<locals>.<listcomp>)_broadcast_array_shapeslenzip)arraysr   
new_shapesr	   r	   r   _broadcast_arrays   s    r   c                 C   s   dd | D }t ||S )r   c                 S   s   g | ]}t |jqS r	   )r
   asarrayshaper   arrr	   r	   r   r      s     z+_broadcast_array_shapes.<locals>.<listcomp>)_broadcast_shapesr   r   shapesr	   r	   r   r      s    r   c           	         s  | s| S |dk	r>t |}|t}t ||s:t d|}tdd | D }t jt| |ftd}t	|| D ] \}}||t|t| d< qp|dk	r,|||dk   ||dk < t 
|}|d |ks|d dk rd| }t |tt |t|krt d	|dd|f }t j||d
d}t j|dd|jdd9 t |d
k|kB  rltd|dk	r|t t|   fdd|D }|S tS dS )zF
    Broadcast shapes, ignoring incompatibility of specified axes
    Nz:`axis` must be an integer, a tuple of integers, or `None`.c                 S   s   g | ]}t |qS r	   r   r   r   r	   r	   r   r   2   s     z%_broadcast_shapes.<locals>.<listcomp>)dtyper   z/`axis` is out of bounds for array of dimension z*`axis` must contain only distinct elements   r   z/Array shapes are incompatible for broadcasting.c                    s   g | ]}t t |qS r	   )tupler
   insert)r   Zremoved_shapeZnew_axisr   r	   r   r   V   s   )r
   
atleast_1dastypeintZarray_equalZ	AxisErrormaxonesr   r   sortuniquedeleteallany
ValueErrorZaranger#   )	r   r   Zaxis_intn_dimsr   rowr   messageZremoved_shapesr	   r%   r   r   !   sB    








r   c                 C   s   dd | D }t ||S )a  
    Broadcast shapes of arrays, dropping specified axes

    Given a sequence of arrays `arrays` and an integer or tuple `axis`, find
    the shape of the broadcast result after consuming/dropping `axis`.
    In other words, return output shape of a typical hypothesis test on
    `arrays` vectorized along `axis`.

    Examples
    --------
    >>> import numpy as np
    >>> a = np.zeros((5, 2, 1))
    >>> b = np.zeros((9, 3))
    >>> _broadcast_array_shapes((a, b), 1)
    (5, 3)
    c                 S   s   g | ]
}|j qS r	   r   r   r	   r	   r   r   p   s     z7_broadcast_array_shapes_remove_axis.<locals>.<listcomp>)_broadcast_shapes_remove_axisr   r	   r	   r   #_broadcast_array_shapes_remove_axis]   s    r6   c                 C   s.   t | |} | d }|dk	r&t||}t|S )z
    Broadcast shapes, dropping specified axes

    Same as _broadcast_array_shapes, but given a sequence
    of array shapes `shapes` instead of the arrays themselves.
    r   N)r   r
   r-   r#   )r   r   r   r	   r	   r   r5   t   s
    
r5   c                 C   s   t | |} tj| |d}|S )z3Concatenate arrays along an axis with broadcasting.r   )r   r
   Zconcatenate)r   r   resr	   r	   r   _broadcast_concatenate   s    
r8   c                    sX   |sdd | D S t | d }| dd D ]}|t |B }q,|   fdd| D S )z.Remove nans from paired or unpaired 1D samplesc                 S   s   g | ]}|t |  qS r	   r
   isnanr   sampler	   r	   r   r      s     z _remove_nans.<locals>.<listcomp>r   r"   Nc                    s   g | ]}|  qS r	   r	   r;   Znot_nansr	   r   r      s     r9   )samplespairedZnansr<   r	   r=   r   _remove_nans   s    r@   c                    sX   |sfdd| D S | d k}| dd D ]}||kB }q.|   fdd| D S )z9Remove sentinel values from paired or unpaired 1D samplesc                    s   g | ]}|| k qS r	   r	   r;   )sentinelr	   r   r      s     z$_remove_sentinel.<locals>.<listcomp>r   r"   Nc                    s   g | ]}|  qS r	   r	   r;   )not_sentinelsr	   r   r      s     r	   )r>   r?   rA   Z	sentinelsr<   r	   )rB   rA   r   _remove_sentinel   s    rC   c                 C   s  d}| D ]}t |dd}|p$t|}q|s4| d fS tj|  }t|tjrP|ntj}tt| D ]}| | j	|dd| |< qbt|tj
}|rtjntj}||j||j }}	|rtjndd }
|}||	kr| D ]$}t||kr|
|tj } qq֐qqd}t|g }| D ]b}t |dd }|d k	rlt||j}t|rT|j n|j}t|}|||< || q||fS )NFmaskcopyc                 S   s   | d S )Nr"   r	   )x_r	   r	   r   <lambda>       z2_masked_arrays_2_sentinel_arrays.<locals>.<lambda>zThis function replaces masked elements with sentinel values, but the data contains all distinct values of this data type. Consider promoting the dtype to `np.float64`.)getattrr
   r/   Zresult_typeZ
issubdtypenumberZfloat64ranger   r'   inexactZfinfoZiinfor)   min	nextafterinfr0   r   r   datarF   r   append)r>   Zhas_maskr<   rD   r    irN   infoZmax_possibleZmin_possiblerP   rA   r3   Zout_samplesr	   r	   r    _masked_arrays_2_sentinel_arrays   sB    



rV   c                 C   s4   t dd | D sdS t| |}t|tj }|S )zU
    Check for empty sample; return appropriate output for a vectorized hypotest
    c                 s   s   | ]}|j d kV  qdS )r   N)sizer;   r	   r	   r   	<genexpr>   s     z&_check_empty_inputs.<locals>.<genexpr>N)r/   r6   r
   r*   nan)r>   r   Zoutput_shapeoutputr	   r	   r   _check_empty_inputs   s
    
r[   c                    s   |r fdd| D S | S )z^
    Add reduced axes back to all the arrays in the result object
    if keepdims = True.
    c                    s   g | ]}t | qS r	   )r
   Zexpand_dims)r   rZ   reduced_axesr	   r   r      s     z%_add_reduced_axes.<locals>.<listcomp>r	   )r7   r]   keepdimsr	   r\   r   _add_reduced_axes   s    r_   r   zIf an int, the axis of the input along which to compute the statistic.
The statistic of each axis-slice (e.g. row) of the input will appear in a
corresponding element of the output.
If ``None``, the input will be raveled before computing the statistic.
c                 C   s2   d|  }t |||}tj |tj j| d}||fS )Nzint or None, default: default)r   inspectKEYWORD_ONLY)default_axis_name_desc_type_axis_parameter_doc_axis_parameterr	   r	   r   _get_axis_params  s    
rk   
nan_policyz{'propagate', 'omit', 'raise'}a  Defines how to handle input NaNs.

- ``propagate``: if a NaN is present in the axis slice (e.g. row) along
  which the  statistic is computed, the corresponding entry of the output
  will be NaN.
- ``omit``: NaNs will be omitted when performing the calculation.
  If insufficient data remains in the axis slice along which the
  statistic is computed, the corresponding entry of the output will be
  NaN.
- ``raise``: if a NaN is present, a ``ValueError`` will be raised.	propagatera   r^   zbool, default: FalsezIf this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the input array.Fa  
Beginning in SciPy 1.9, ``np.matrix`` inputs (not recommended for new
code) are converted to ``np.ndarray`` before the calculation is performed. In
this case, the output will be a scalar or ``np.ndarray`` of appropriate shape
rather than a 2D ``np.matrix``. Similarly, while masked elements of masked
arrays are ignored, the output will be a scalar or ``np.ndarray`` rather than a
masked array with ``mask=False``.r"      c           	         s:   dkrdd fdd fdd}|S )a
  Factory for a wrapper that adds axis/nan_policy params to a function.

    Parameters
    ----------
    tuple_to_result : callable
        Callable that returns an object of the type returned by the function
        being wrapped (e.g. the namedtuple or dataclass returned by a
        statistical test) provided the separate components (e.g. statistic,
        pvalue).
    default_axis : int, default: 0
        The default value of the axis argument. Standard is 0 except when
        backwards compatibility demands otherwise (e.g. `None`).
    n_samples : int or callable, default: 1
        The number of data samples accepted by the function
        (e.g. `mannwhitneyu`), a callable that accepts a dictionary of
        parameters passed into the function and returns the number of data
        samples (e.g. `wilcoxon`), or `None` to indicate an arbitrary number
        of samples (e.g. `kruskal`).
    paired : {False, True}
        Whether the function being wrapped treats the samples as paired (i.e.
        corresponding elements of each sample should be considered as different
        components of the same sample.)
    result_to_tuple : callable, optional
        Function that unpacks the results of the function being wrapped into
        a tuple. This is essentially the inverse of `tuple_to_result`. Default
        is `None`, which is appropriate for statistical tests that return a
        statistic, pvalue tuple (rather than, e.g., a non-iterable datalass).
    too_small : int, default: 0
        The largest unnacceptably small sample for the function being wrapped.
        For example, some functions require samples of size two or more or they
        raise an error. This argument prevents the error from being raised when
        input is not 1D and instead places a NaN in the corresponding element
        of the result.
    n_outputs : int or callable, default: 2
        The number of outputs produced by the function given 1d sample(s). For
        example, hypothesis tests that return a namedtuple or result object
        with attributes ``statistic`` and ``pvalue`` use the default
        ``n_outputs=2``; summary statistics with scalar output use
        ``n_outputs=1``. Alternatively, may be a callable that accepts a
        dictionary of arguments passed into the wrapped function and returns
        the number of outputs corresponding with those arguments.
    kwd_samples : sequence, default: []
        The names of keyword parameters that should be treated as samples. For
        example, `gmean` accepts as its first argument a sample `a` but
        also `weights` as a fourth, optional keyword argument. In this case, we
        use `n_samples=1` and kwd_samples=['weights'].
    Nc                 S   s   | S Nr	   )r7   r	   r	   r   result_to_tuplej  s    z1_axis_nan_policy_factory.<locals>.result_to_tuplec                    s    | D ]}t | kr dS qdS )NTFr   )r>   r<   )	too_smallr	   r   is_too_smallm  s    z._axis_nan_policy_factory.<locals>.is_too_smallc           	         sj  t  dd f	dd
}t\}}t|}dd |d D }d|krl||d |d< n|d | d	|krt|d |d	< n|d t d
|krt|d |d
< n|d t |d  t7  < t|	ddd }t||_
t|}|j}t| }d|kr,|| d	|kr@|t d
|krT|t |j|d}||_|S )NF)_no_decoc              
      sJ  | r|S t tj}d krHdd tt|D |dd   }tt||}t|t@ }|rj	 dt |d  d}t
|| trnpt|trȈfddD tsnfdd	fd
d|d   D }d|kr(dnd}d dd}	dd}
~t|\}	 } d kr|rtdd |D }tt|}dd |D }ndt| d}t  t  fdd|D }dd |D }fdd|D }dd t||D }d tdd |D }t|dkrg }|D ]}t||	\}}|| q6t|r|	dkrttj}t|||
}| S t|r|	dkrt|}	rt|	}|}|}t|||
}| S t| d k	r fddtD }t|||
}| S t fdd|D }t|
t | }t||	\}}|r|s	s|d i}|}t|||
}| S |r|	dkrʇ	
f
dd}nN|r|	dkr	
f
dd}n	
f
d d}t!| d}tj"|d|d!}t|||
}| S )"Nc                 S   s   g | ]}d | qS )argr	   r   rT   r	   r	   r   r     s     zp_axis_nan_policy_factory.<locals>.axis_nan_policy_decorator.<locals>.axis_nan_policy_wrapper.<locals>.<listcomp>r"   z%() got multiple values for argument 'r   'c                    s    g | ]}  |d d k	r|qS ro   )get)r   namekwdsr	   r   r     s    c                     s2   t t| d  }||  | d  |S ro   )dictr   update)r>   rz   Znew_kwds)hypotest_fun_inkwd_sampn_sampr	   r   hypotest_fun_out  s    
zv_axis_nan_policy_factory.<locals>.axis_nan_policy_decorator.<locals>.axis_nan_policy_wrapper.<locals>.hypotest_fun_outc                    s   g | ]}t  |qS r	   )r
   r&   popr   paramry   r	   r   r     s   r   TFrl   rm   r^   c                 S   s   g | ]
}|j qS r	   ndimr;   r	   r	   r   r     s     c                 S   s   g | ]}t | qS r	   )r
   r   Zravelr;   r	   r	   r   r     s     r   c              	      s&   g | ]}t | tt  d qS )r   )r
   moveaxisrM   r   r;   r   r	   r   r     s   c                 S   s   g | ]
}|j qS r	   r4   r;   r	   r	   r   r     s     c                    s0   g | ](}|d    t |  d  f qS ro   )r
   prodr   )n_axesr	   r   r     s   c                 S   s   g | ]\}}| |qS r	   )Zreshape)r   r<   r   r	   r	   r   r     s   r!   c                 S   s   g | ]
}|j qS r	   r   r;   r	   r	   r   r     s     Zomitc                    s   g | ]}   qS r	   rE   ru   )empty_outputr	   r   r     s     c                    s   g | ]}|j   qS r	   r4   r;   r   r	   r   r     s     c                    sV   t | 	d   }t|}r2t|}|rHt t jS  |S ro   )r
   splitr@   rC   fullrY   rG   r>   
r   rr   rz   
n_kwd_sampn_outr   r?   rp   rA   split_indicesr	   r   hypotest_fun  s    
zr_axis_nan_policy_factory.<locals>.axis_nan_policy_decorator.<locals>.axis_nan_policy_wrapper.<locals>.hypotest_func                    sh   t |  rt t jS t | 	d   }rDt|}|rZt t jS  |S ro   )r
   r:   r/   r   rY   r   rC   r   r   r	   r   r   !  s    c                    sL   t | 	d   }r(t|}|r>t t jS  |S ro   )r
   r   rC   r   rY   r   r   r	   r   r   -  s    )r   r   )#listrc   	signature
parametersrM   r   r{   r   set__name__	TypeErrorr|   callabler   rV   r
   r)   r#   r   r&   r   r.   r   rS   r/   r   rY   r_   r@   rC   r[   Zcumsumr8   r   Zapply_along_axis)rs   argsrz   paramsZd_argsintersectionr3   r>   Z
vectorizedrl   r^   r]   r1   r   r   ZndimsZcontains_nansr<   Zcontains_nanrH   r7   lengthsrG   r   )	re   r}   rr   kwd_samples	n_outputs	n_samplesr?   rp   tuple_to_result)r   r   r   r~   rz   r   r   r   r   rA   r   r   axis_nan_policy_wrappert  s    
"












 
 z\_axis_nan_policy_factory.<locals>.axis_nan_policy_decorator.<locals>.axis_nan_policy_wrapperc                 S   s   g | ]
}|j qS r	   )rx   r   r	   r	   r   r   <  s     zO_axis_nan_policy_factory.<locals>.axis_nan_policy_decorator.<locals>.<listcomp>Z
Parametersr   rl   r^   ZNotesr`   r"   )r   )r   rk   r   indexrS   _nan_policy_parameter_doc_keepdims_parameter_doc_standard_note_additionstrr   __doc__rc   r   r   r   values_nan_policy_parameter_keepdims_parameterreplace__signature__)	r}   r   ri   rj   docZparameter_namessigr   Zparameter_list)re   rr   r   r   r   r?   rp   r   )r}   r   axis_nan_policy_decorators  sB    $ F







z;_axis_nan_policy_factory.<locals>.axis_nan_policy_decoratorr	   )	r   re   r   r?   rp   rq   r   r   r   r	   )	re   rr   r   r   r   r?   rp   rq   r   r   _axis_nan_policy_factory5  s    4 kr   )N)N)N)N)N)!Znumpyr
   	functoolsr   Zscipy._lib._docscraper   r   Zscipy._lib._utilr   rc   r   r   r   r6   r5   r8   r@   rC   rV   r[   r_   rf   r   rg   rk   rh   r   rd   r   r   r   r   r   r	   r	   r	   r   <module>   sn   


<

8
	
	   