B
    Afxaz              /   @   s4  d Z ddlZddlmZ ddlmZ ddlmZmZm	Z	 ddl
mZmZ ddlmZmZ i Zi Zd	d
 Zdd ZdddZdd ZddddZdd ZdddZdd ZdddZddddd gZd!d"d#d$d%d&gZd'd(iZd)d*d*d*d*d*d*d)d)d)d)d)d)d)d+d+d+d+d+d+d,d-d,d-d)d)d.Zd/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLgZdMdNdOdPgZ dQdRdSdSdSdTdUdQdVdWdWdWdRdXZ!xeD ]Z"edYe"dddZ qW xeD ]Z"edYe"d[ddZ qW x&e# D ]\Z"Z$edYe"d[e$dZ qW x*e# D ]\Z"\Z%Z$edYe"e%e$dZ qW xeD ]Z"edYe"d[d\dZ qW xe D ]Z"edYe"dd\dZ q:W x&e!# D ]\Z"Z&edYe"de&dZ q^W ed]dYd^d_ Z'ed`dYdadb Z(edcdYddde Z)edfdYdgdh Z*edidYdjdk Z+edldmdndo Z,edpdmddsdtZ-edudmddvdwZ.edxdmdydz Z/ed{dmd|d} Z0ed~dmdd Z1eddmdddZ2eddmdddZ3eddmdd Z4eddmdddZ5eddmdddZ6eddmdd Z7eddmdd Z8eddmdd Z9dddZ:xddddddddddddddddddddddddddddgdrfddgdrfdddgdrfdddgdrfdddgdfdddgdfdddddgdrfddddgdrfdddgdrfddddgdrfddddddgdrfdddddgdfdddgdrfg-D ]\Z;Z<Z=e:e;e<e= qW dd߄ Z>xdD ]Z;e>e; qW dd Z?xdD ]Z;e?e; qW xdD ]Z;edme;d[d\dZ q.W xdD ]Z;edme;dddZ qNW xdD ]Z;edme;ddWdZ qnW xdD ]Z;edme;ddRdZ qW xdD ]Z;edme;dddZ qW xdD ]Z;edme;dddZ qW xdD ]Z;edme;dddZ qW xdD ]Z;edme;dddZ qW dd Z@dS )z
    pint.numpy_func
    ~~~~~~~~~~~~~~~

    :copyright: 2019 by Pint Authors, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
    N)	signature)chain   )is_upcast_typenpzero_or_nan)DimensionalityErrorUnitStrippedWarning)iterablesizedc             C   s   t | dot | dS )zTest for _units and _magnitude attrs.

    This is done in place of isinstance(Quantity, arg), which would cause a circular import.

    Parameters
    ----------
    obj : Object


    Returns
    -------
    bool
    Z_units
_magnitude)hasattr)obj r   .lib/python3.7/site-packages/pint/numpy_func.py_is_quantity   s    r   c             C   s.   t | o,t| o,t| t o,tdd | D S )zTest for sequences of quantities.

    Parameters
    ----------
    obj : object


    Returns
    -------
    True if obj is a sequence and at least one element is a Quantity; False otherwise
    c             s   s   | ]}t |V  qd S )N)r   ).0itemr   r   r   	<genexpr>9   s    z6_is_sequence_with_quantity_elements.<locals>.<genexpr>)r
   r   
isinstancestrany)r   r   r   r   #_is_sequence_with_quantity_elements)   s    r   c             C   sT   |pi }x>t | | D ],}t|r*|jS t|rtdd |D S qW tddS )zAObtain the first valid unit from a collection of args and kwargs.c             s   s   | ]}t |r|jV  qd S )N)r   units)r   Zarg_ir   r   r   r   D   s    z)_get_first_input_units.<locals>.<genexpr>z*Expected at least one Quantity; found noneN)r   valuesr   r   r   next	TypeError)argskwargsargr   r   r   _get_first_input_units=   s    r    c                s    dk	rvt | r|  S t| r4 fdd| D S | dk	r jrT j|  S t | sjt| drj| S td n(t | r| jS t| r fdd| D S | S )zConvert quantities and sequences of quantities to pre_calc_units and strip units.

    Helper function for convert_to_consistent_units. pre_calc_units must be given as a
    pint Unit or None.
    Nc                s   g | ]}t | qS r   )convert_arg)r   r   )pre_calc_unitsr   r   
<listcomp>R   s    zconvert_arg.<locals>.<listcomp>Tdimensionlessc                s   g | ]}t | qS r   )r!   )r   r   )r"   r   r   r#   ]   s    )	r   m_asr   r$   	_REGISTRYQuantityr   r   m)r   r"   r   )r"   r   r!   H   s     
r!   )r"   c                s,   t  fdd|D  fdd| D fS )a  Prepare args and kwargs for wrapping by unit conversion and stripping.

    If pre_calc_units is not None, takes the args and kwargs for a NumPy function and
    converts any Quantity or Sequence of Quantities into the units of the first
    Quantity/Sequence of Quantities and returns the magnitudes. Other args/kwargs are
    treated as dimensionless Quantities. If pre_calc_units is None, units are simply
    stripped.
    c             3   s   | ]}t | d V  qdS ))r"   N)r!   )r   r   )r"   r   r   r   k   s    z.convert_to_consistent_units.<locals>.<genexpr>c                s   i | ]\}}t | d |qS ))r"   )r!   )r   keyr   )r"   r   r   
<dictcomp>l   s   z/convert_to_consistent_units.<locals>.<dictcomp>)tupleitems)r"   r   r   r   )r"   r   convert_to_consistent_unitsa   s    

r-   c                 sH   t dd | D r| dd fS t|  t| d i\} }|  fddfS )zStrip units from args while providing a rewrapping function.

    Returns the given args as parsed by convert_to_consistent_units assuming units of
    first arg with units, along with a wrapper to restore that unit to the output.

    c             s   s   | ]}t | V  qd S )N)r   )r   r   r   r   r   r   z   s    z3unwrap_and_wrap_consistent_units.<locals>.<genexpr>c             S   s   | S )Nr   )xr   r   r   <lambda>{       z2unwrap_and_wrap_consistent_units.<locals>.<lambda>r"   c                s    j |  S )N)r&   r'   )value)first_input_unitsr   r   r/      r0   )allr    r-   )r   _r   )r2   r    unwrap_and_wrap_consistent_unitss   s    r5   c             C   s&  |pg }| dkr&d| d|  j }n| dkrd|jd}x |D ]}t|dr@||j 9 }q@W |}n| dkrd| d|  j }n| dkrd| d|  j }x(|dd D ]}t|dr||j  }qW |}nT| d	kr"t|d
 d|jd}x(|dd D ]}t|dr||j  }qW |}n | dkrDd| d|  d j }n| dkrX|d }n| dkrl|d }n| dkr|d }n| dkr|d }n| dkr|dkrtd|| }nh| dkrt|d
 d|jd}x,|dd D ]}t|dr||j  }qW |d }ntd| |S )a|  Determine resulting unit from given operation.

    Options for `unit_op`:

    - "sum": `first_input_units`, unless non-multiplicative, which raises
      OffsetUnitCalculusError
    - "mul": product of all units in `all_args`
    - "delta": `first_input_units`, unless non-multiplicative, which uses delta version
    - "delta,div": like "delta", but divided by all units in `all_args` except the first
    - "div": unit of first argument in `all_args` (or dimensionless if not a Quantity) divided
      by all following units
    - "variance": square of `first_input_units`, unless non-multiplicative, which raises
      OffsetUnitCalculusError
    - "square": square of `first_input_units`
    - "sqrt": square root of `first_input_units`
    - "reciprocal": reciprocal of `first_input_units`
    - "size": `first_input_units` raised to the power of `size`
    - "invdiv": inverse of `div`, product of all following units divided by first argument unit

    Parameters
    ----------
    unit_op :

    first_input_units :

    all_args :
         (Default value = None)
    size :
         (Default value = None)

    Returns
    -------

    sumr   mul r   deltaz	delta,divNdivr   variance   squaresqrtg      ?cbrtgUUUUUU?
reciprocalsizez0size argument must be given when unit_op=="size"invdivz$Output unit method {} not understood)r   r&   parse_unitsr   getattr
ValueErrorformat)unit_opr2   Zall_argsrB   result_unitproductr.   r   r   r   get_op_output_unit   s^    #


















rK   c                s    fdd}|S )z]Register an __array_function__/__array_ufunc__ implementation for Quantity
    objects.

    c                s6    dkr| t < n  dkr$| t< ntd | S )NfunctionufunczInvalid func_type {})HANDLED_FUNCTIONSHANDLED_UFUNCSrF   rG   )func)	func_typenumpy_func_stringr   r   	decorator   s    

zimplements.<locals>.decoratorr   )rR   rQ   rS   r   )rQ   rR   r   
implements   s    	rT   c                sp   t dkrdS |d}tt |d d  dkr2dS x|dd D ]}t | q@W t||  fdd}dS )a`  Add default-behavior NumPy function/ufunc to the handled list.

    Parameters
    ----------
    func_type : str
        "function" for NumPy functions, "ufunc" for NumPy ufuncs
    func_str : str
        String representing the name of the NumPy function/ufunc to add
    input_units : pint.Unit or str or None
        Parameter to control how the function downcasts to magnitudes of arguments. If
        `pint.Unit`, converts all args and kwargs to this unit before downcasting to
        magnitude. If "all_consistent", converts all args and kwargs to the unit of the
        first Quantity in args and kwargs before downcasting to magnitude. If some
        other string, the string is parsed as a unit, and all args and kwargs are
        converted to that unit. If None, units are stripped without conversion.
    output_unit : pint.Unit or str or None
        Parameter to control the unit of the output. If `pint.Unit`, output is wrapped
        with that unit. If "match_input", output is wrapped with the unit of the first
        Quantity in args and kwargs. If a string representing a unit operation defined
        in `get_op_output_unit`, output is wrapped by the unit determined by
        `get_op_output_unit`. If some other string, the string is parsed as a unit,
        which becomes the unit of the output. If None, the bare magnitude is returned.


    N.r   r   c                 s   t | |}dkr*t| d|i|\}}n2ttrB|j}n}t| d|i|\}} ||}d krr|S dkr|}n(dkrt|tt| |	 }n}|j
||S )Nall_consistentr"   match_input)r6   r7   r9   z	delta,divr:   rC   r;   r=   r>   r?   r@   rB   )r    r-   r   r   r&   rD   rK   r+   r   r   r'   )r   r   r2   Zstripped_argsZstripped_kwargsr"   Zresult_magnituderI   )rP   input_unitsoutput_unitr   r   implementation  s&    


z&implement_func.<locals>.implementation)r   splitrE   rT   )rQ   func_strrX   rY   Zfunc_str_splitZfunc_str_piecerZ   r   )rP   rX   rY   r   implement_func   s    
r]   isnanZisinfZisfiniteZsignbitsignZequalZgreaterZgreater_equalZlessZ
less_equalZ	not_equalZarctan2radian)r8   r8   )r8   r`   )r`   r8   )degreer`   )r`   ra   )cumprodZarccosZarcsinZarctanZarccoshZarcsinhZarctanhZexpZexpm1Zexp2logZlog10Zlog1pZlog2ZsinZcosZtanZsinhZcoshZtanhZradiansZdegreesZdeg2radZrad2degZ	logaddexpZ
logaddexp2compressZconj	conjugatecopydiagonalmaxmeanminptpravelrepeatreshaperoundsqueezeswapaxesZtakeZtrace	transposeZceilZfloorZhypotZrintZcopysignZ	nextafterZtruncZabsolutenegativeZmaximumZminimumZfabsZldexpZfmodmodZ	remainderr=   r7   r:   r>   r?   r@   r6   )varZmultiplyZtrue_divideZdivideZfloor_divider>   r?   r=   r@   stdr6   cumsummatmulrM   )rX   rY   rV   rW   modfc                s2   t | \\}  t fddtj| f||D S )Nc             3   s   | ]} |V  qd S )Nr   )r   y)output_wrapr   r   r     s    z_modf.<locals>.<genexpr>)r5   r+   r   ry   )r.   r   r   r   )r{   r   _modf  s    r|   frexpc             O   s0   t | \\} }tj| f||\}}|||fS )N)r5   r   r}   )r.   r   r   r{   Zmantissaexponentr   r   r   _frexp  s    r   Zpowerc             C   s   t | r| | S || S d S )N)r   __rpow__)x1x2r   r   r   _power  s    r   addc             O   s*   t | |\\} }}|tj| |f||S )N)r5   r   r   )r   r   r   r   r{   r   r   r   _add  s    r   subtractc             O   s*   t | |\\} }}|tj| |f||S )N)r5   r   r   )r   r   r   r   r{   r   r   r   	_subtract  s    r   meshgridrL   c              O   s8   dd | D }t jdd | D |}dd t||D S )Nc             s   s   | ]}|j V  qd S )N)r   )r   r.   r   r   r   r     s    z_meshgrid.<locals>.<genexpr>c             s   s   | ]}|j V  qd S )N)r(   )r   r.   r   r   r   r     s    c             S   s   g | ]\}}|| qS r   r   )r   outunitr   r   r   r#   	  s    z_meshgrid.<locals>.<listcomp>)r   r   zip)Zxir   rX   Zresr   r   r   	_meshgrid  s    r   Z	full_likeKTc          	   C   sL   t |dr0|jtj| ||||d|j |jS tj| ||||d| S d S )Nr&   )dtypeordersubokshape)r   r&   r'   r   	ones_liker(   r   )aZ
fill_valuer   r   r   r   r   r   r   
_full_like  s    
r   interpc          	   C   sF   t | ||\\} }}}t |||\\}}}}|tj| |||||dS )N)leftrightperiod)r5   r   r   )r.   Zxpfpr   r   r   r4   r{   r   r   r   _interp  s    r   wherec             G   s    t | \}}|tj| f| S )N)r5   r   r   )Z	conditionr   r{   r   r   r   _where'  s    r   concatenatec             O   s"   t |  \} }|tj| f||S )N)r5   r   r   )Zsequencer   r   r{   r   r   r   _concatenate-  s    r   stackc             O   s"   t |  \} }|tj| f||S )N)r5   r   r   )arraysr   r   r{   r   r   r   _stack3  s    r   unwraprA   c             C   s:   |d krt jn|}| jt j| d||dd| jS )NZrad)axis)r   Zpir&   r'   r   r%   tor   )pZdiscontr   r   r   r   _unwrap9  s     r   copyto	same_kindc             C   sZ   t | r2t |r|| j}tj| j|||d n$tjdtdd tj| |j	||d d S )N)castingr   zAThe unit of the quantity is stripped when copying to non-quantityr<   )
stacklevel)
r   r%   r   r   r   r   warningswarnr	   r(   )dstsrcr   r   r   r   r   _copytoB  s    r   einsumc             O   s8   t |dd i\}}tdt||}tj| f||| S )Nr"   r7   )r-   rK   r    r   r   )Z
subscriptsZoperandsr   Zoperand_magnitudesr4   rY   r   r   r   _einsumQ  s    r   isinFc          	   C   s   t | stdt |rJy|| j}W q tk
rF   t| jdS X n|t|rg }x@|D ]8}t |shy|	|| j W q\ tk
r   Y q\X q\W |}n(| j
st| jdS | j|| j tj| j|||dS )Nz>Cannot test if unit-aware elements are in not-unit-aware arrayF)assume_uniqueinvert)r   rF   r%   r   r   r   Zfullr   r   appendr$   r&   r'   r   r(   )elementZtest_elementsr   r   Zcompatible_test_elementsZtest_elementr   r   r   _isinX  s*    

r   padconstantc                s^    fdd | j }x&dD ]}||kr || |||< qW |jtj| j|fd|i||S )Nc                sb   t | r t fdd| D S t| sX| dks:t| rJ j|  } n j| d} |  S )Nc             3   s   | ]} |d V  qdS ))r   Nr   )r   r   )_recursive_convertr   r   r   r     s    z3_pad.<locals>._recursive_convert.<locals>.<genexpr>r   r$   )r
   r+   r   r   r^   r&   r'   r%   )r   r   )r   )r   r   r     s    z _pad.<locals>._recursive_convert)Zconstant_valuesZ
end_valuesmode)r   r&   r'   r   r   r   )arrayZ	pad_widthr   r   r   r)   r   )r   r   _pad}  s    
r   r   c             O   s&   | j rtj| jf||S tdd S )Nz8Boolean value of Quantity with offset unit is ambiguous.)_is_multiplicativer   r   r   rF   )r   r   r   r   r   r   _any  s    r   r3   c             O   s&   | j rtj| jf||S tdd S )Nz8Boolean value of Quantity with offset unit is ambiguous.)r   r   r3   r   rF   )r   r   r   r   r   r   _all  s    r   prodc             O   s  d}t f t t|||}|dd }|dd }| jj}|d k	r|d k	rt| j|\}}	ttj	|	|d}
t
|
dkst
|
dkrd|
kr| jt|
 }q|j}| |} nD|d k	r| j| j|  }n*|d k	rt	|}| j| }n| j| j }tj| jf||}|||S )N)r   r   r   Zkeepdimsinitialr   r   r   )r   r   r<   r   )dictr   getr   r&   r   Zbroadcast_arraysr   uniquer6   lenrh   r$   r   r   rB   r   r'   )r   r   r   Z	arg_namesZ
all_kwargsr   r   registryr4   Zwhere_Z	exponentsr   r~   resultr   r   r   _prod  s(     
r   c                s   t d krd S d| kr"tt | d  n@| d}t }x |d d D ]}t||d }q>W t||d d   d krnd S t| d fdd}d S )NrU   rA   rL   c                 s   t j| |  fddD }t fdd|D  \}}x"t|D ]\}}| j|| < qFW  j j}rz||S |S d S )Nc                s(   g | ] }| j kr j | d k	r|qS )N)	arguments)r   label)
bound_argsr   r   r#     s   zRimplement_consistent_units_by_argument.<locals>.implementation.<locals>.<listcomp>c             3   s   | ]} j | V  qd S )N)r   )r   r   )r   r   r   r     s    zQimplement_consistent_units_by_argument.<locals>.implementation.<locals>.<genexpr>)r   Zbindr5   	enumerater   r   r   )r   r   Zvalid_unit_argumentsZunwrapped_unit_argsr{   iZunwrapped_unit_argret)rP   unit_argumentswrap_output)r   r   rZ     s    
z>implement_consistent_units_by_argument.<locals>.implementation)r   rE   r[   rT   )r\   r   r   partsmodulepartrZ   r   )rP   r   r   r   &implement_consistent_units_by_argument  s    
r   )Zexpand_dimsr   T)rp   r   T)Zrollaxisr   T)Zmoveaxisr   T)Zaroundr   T)rg   r   T)ri   r   T)rk   r   T)rl   r   T)Zround_r   T)sortr   T)Zmedianr   T)Z	nanmedianr   T)rr   r   T)rf   r   T)Zaverager   T)Znanmeanr   T)rq   r   T)Znanminr   T)Znanmaxr   T)Z
percentiler   T)Znanpercentiler   T)Zquantiler   T)Znanquantiler   T)Zflipr(   T)Zfixr.   TZ
trim_zerosZfiltZbroadcast_tor   Zamaxr   r   ZaminZsearchsortedvZisclosebZ
nan_to_numr.   nanZposinfZneginfZclipZa_minZa_maxr   Zarrr   )rd   r   TZlinspacestartstop)ZtileAT)z%lib.stride_tricks.sliding_window_viewr.   T)Zrot90r(   Tinsert)Zresizer   T)rn   r   TZallcloseZintersect1dZar1Zar2c                s0   t d krd S tt |  t| d fdd}d S )NrL   c                 sP   t |  \}} | }t| dkr4dd t|| D S | d j}|j||S d S )Nr   c             S   s.   g | ]&\}}t |d s|n|j||jqS )r&   )r   r&   r'   r   )r   Zarray_magnitudeZoriginalr   r   r   r#   <  s   z@implement_atleast_nd.<locals>.implementation.<locals>.<listcomp>r   )r-   r   r   r   r&   r'   )r   Zstripped_arraysr4   Zarrays_magnituderY   )rP   r   r   rZ   6  s    
z,implement_atleast_nd.<locals>.implementation)r   rE   rT   )r\   rZ   r   )rP   r   implement_atleast_nd/  s    
r   )Z
atleast_1dZ
atleast_2dZ
atleast_3dc                s0   t d krd S tt |  t| d fdd}d S )NrL   c                s2   t | | jdd\\}}| j |f||S )Nr$   )r"   )r-   r&   rD   r'   )r   r   r   Z
a_strippedr4   )rP   r   r   rZ   S  s    zDimplement_single_dimensionless_argument_func.<locals>.implementation)r   rE   rT   )r\   rZ   r   )rP   r   ,implement_single_dimensionless_argument_funcL  s    
r   )rb   Z
cumproductZ
nancumprod)blockZhstackZvstackZdstackZcolumn_stack)rB   ZisrealZ	iscomplexr   r   Z
zeros_likeZ
empty_likeZargsortZargminZargmaxZalenndimZ	nanargmaxZ	nanargminZcount_nonzeroZnonzeroZresult_type)rv   Znanstdr6   Znansumrw   Z	nancumsum)ZcrossZtrapzdot)ZdiffZediff1dr9   )Zgradientz	delta,div)zlinalg.solverC   )ru   Znanvarr;   c             C   s~   | dkr0t }d|jddd |jg }n"| dkrDt}|j}ntd| ||ksltdd |D rpt	S || ||S )	zAReturn the result from a NumPy function/ufunc as wrapped by Pint.rL   rU   r   NrM   zInvalid func_type {}c             s   s   | ]}t |V  qd S )N)r   )r   tr   r   r   r     s    znumpy_wrap.<locals>.<genexpr>)
rN   join
__module__r[   __name__rO   rF   rG   r   NotImplemented)rQ   rP   r   r   typesZhandlednamer   r   r   
numpy_wrap  s    $r   )N)NN)NN)Nr   TN)NNN)NrA   )r   T)FF)r   )T)A__doc__r   inspectr   	itertoolsr   compatr   r   r   errorsr   r	   utilr
   r   rO   rN   r   r   r    r!   r-   r5   rK   rT   r]   Zstrip_unit_input_output_ufuncsZ!matching_input_bare_output_ufuncsZ&matching_input_set_units_output_ufuncsZset_units_ufuncsZ'matching_input_copy_units_output_ufuncsZcopy_units_output_ufuncsZop_units_output_ufuncsZ	ufunc_strr,   Zout_unitZin_unitrH   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r\   r   r   r   r   r   r   r   r   r   <module>   s  

[
m



	$		!
/











