B
    Ú‹dØ«  ã            ²   @   sx  d dl Z d dlZd dlZd dlmZ d dlZd dlmZm	Z	 ddl
mZmZ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 d dlmZ d dlmZ ddlmZmZm Z  ej! "e#¡Z$ye	de$ƒZ%W n e&k
rò   e'dƒ‚Y nX e%j(Z)de)_*eej+ddhdeej+ddej,eej-ddeej+ddeej-ddej.ej.ej,g	e)_/e 0d 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,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dd€dd‚dƒd„d…d†d‡dˆd‰dŠd‹dŒddŽddd‘d’d“d”d•d–d—d˜d™dšd›dœddž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¹dºd»d¼d½d¾d¿dÀg°¡Z1e2e 3e1dÁ ¡ƒZ4dÂdÃgiZ5ddÄdÅdÆgZ6dÇdÈ„ Z7e8dÉdddfdÊdË„Z9edÌdÍdÝdÓdÔ„ƒZ:edÌdÍdÄdÎdÏdÐdÒdÑddÐdÑdddÎdÑej;j<ej;j=e>fdÕdÖ„ƒZ?e:fd×dØ„Z@dÞdÙdÚ„ZAdßdÛdÜ„ZBdS )àé    N)Úpartial)Ú	ndpointerÚload_libraryé   )ÚKernelÚKernel1DÚKernel2DÚMAX_NORMALIZATION)ÚAstropyUserWarning)Úhuman_file_size)Úunits)Úsupport_nddata)ÚCompoundModel)ÚSPECIAL_OPERATORS)ÚConvolution)ÚKernelSizeErrorÚhas_even_axisÚraise_even_kernel_exceptionÚ	_convolvez<Convolution C extension is missing. Try re-building astropy.ZC_CONTIGUOUSZ	WRITEABLE)Úflagsé   é   é   é   é   é   é	   é
   é   é   é   é   é   é   é   é   é   é    é$   é(   é-   é0   é2   é6   é<   é@   éH   éK   éP   éQ   éZ   é`   éd   él   éx   é}   é€   é‡   é   é–   é    é¢   é´   éÀ   éÈ   éØ   éá   éð   éó   éú   é   i  i   i,  i@  iD  ih  iw  i€  i  i•  i°  iÂ  ià  iæ  iô  i   i  i@  iX  iq  i€  iˆ  i£  iÐ  iÙ  iî  i   i   i*  i`  i„  iÀ  iÌ  iè  i   i8  ie  i€  i°  i¿  iâ  i   i  iF  i   i²  iÜ  i   i@  iT  iÀ  i  iS  i€  i˜  iÐ  ié  i   ip  i‹  iÊ  i 	  i`	  i~	  iÄ	  i 
  i 
  iŒ
  i@  id  i¸  i   i5  i€  i¨  i/  i€  i  i=  i¦  i   i0  i   iÒ  i   ià  i  i”  i   iÀ  iü  iˆ  i   i@  i  iù  i€  iÈ  ip  i»  i   ij  i   iP  i¡  i^  i   i   iz  iL  i   i`  i@  i¤  i    iÀ!  i,"  i(#  i $  iŸ$  i€%  iø%  i'  éÿÿÿÿ)Úconvolve_fftz	scipy.fftÚfillÚwrapÚextendc          	      sÐ   y ddl ‰ t ‡ fdd„| D ƒ¡S  tk
r4   Y nX tjtt | ¡ƒtd}x|t| ƒD ]p\}}dt	tt 
t |¡¡ƒt dƒ }xDtD ]}|| |krˆ|| ||< P qˆW td|› dtd	 | › d
ƒ‚qXW |S )a  
    Find optimal or good sizes to pad an array of ``shape`` to for better
    performance with `numpy.fft.*fft` and `scipy.fft.*fft`.
    Calculated directly with `scipy.fft.next_fast_len`, if available; otherwise
    looked up from list and scaled by powers of 10, if necessary.
    r   Nc                s   g | ]}ˆ j  |¡‘qS © )ÚfftZnext_fast_len)Ú.0Új)ÚscipyrN   úi/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/astropy/convolution/convolve.pyú
<listcomp>U   s    z&_next_fast_lengths.<locals>.<listcomp>)Údtyper   zNo next fast length for z! found in list of _good_sizes <= rI   Ú.)Z	scipy.fftÚnpÚarrayÚImportErrorÚemptyÚlenZ
atleast_1dÚintÚ	enumerateÚmaxÚceilÚlog10Ú_good_rangeÚ_good_sizesÚ
ValueError)ÚshapeÚnewshapeÚirQ   ÚscaleÚnrN   )rR   rS   Ú_next_fast_lengthsK   s    "
"ri   ÚCc          
   C   sè   t | tƒr| jn| } t| dƒr$| j} | }yŠ|dksFtj | ¡sF|d k	rœtj | ¡rrtj| |d|dd}| |¡}ntj| |d|dd}|d k	r°|||dk< ntj| |d|dd}W n0 t	t
fk
râ } zt	d|ƒ‚W d d }~X Y nX |S )NÚunitrK   FT)rU   ÚcopyÚorderZsubokr   zIinput should be a Numpy array or something convertible into a float array)Ú
isinstancer   rX   ÚhasattrÚvaluerW   ÚmaZ	is_maskedZfilledÚ	TypeErrorrc   )ÚinputrU   rm   Únan_treatmentÚmaskÚ
fill_valueÚoutputÚerN   rN   rS   Ú_copy_input_if_neededf   s"    
ry   rX   )Údataç        ÚinterpolateTFç:Œ0âŽyE>c	             C   s¤  |t krtdt › ƒ‚|dkr&tdƒ‚d}	|}
| }t|td||tjd}t|d|jƒ}t|
tddd|d}t|ƒrxt	ƒ  t
|tƒr¨t
|
tƒr¨t d	t¡ d
}d}d}d}|jdkr¼tdƒ‚n(|jdkrÐtdƒ‚n|j|jkrätdƒ‚t |j¡}t |j¡}|d }|dkr*t |d| k¡s*tdƒ‚|dko@t | ¡ ¡}|sN|rŒ| ¡ }tj|d|d}|dt k sz|rŒtd dt ¡ƒ‚|sœ|d
kr¸t |¡}|d
kr¸|||< tj|jtdd}d}|}|dkr>d}|d
kr¼tj|d|  |tdd}|jdkr.|||d |d |d  …< nŒ|jdkrp|||d |d |d  …|d |d |d  …f< nJ|||d |d |d  …|d |d |d  …|d |d |d  …f< n‚ddddœ}|| }|d }|jdkrð|d f}n>|jdkr|d f|d ff}n|d f|d f|d ff}tj|||d}t|||jtj|jtj dd|tj|tj dd|||	ƒ	 |rŒ|sš|| }n|rš||9 }|rÂ|sÂt | ¡ ¡rÂt dt¡ |rÒtj||< t|d dƒ}|dk	rð||K }t
|tƒrbt
|t!ƒrt!|d!}n t
|t"ƒr,t"|d!}nt#d"ƒ‚d|_$|j%|_%t
|
tƒr^|j%oZ|
j%|_%|S |j&d#krœy|j'|dd$S  t#k
r˜   | '|¡S X n|S dS )%a  
    Convolve an array with a kernel.

    This routine differs from `scipy.ndimage.convolve` because
    it includes a special treatment for ``NaN`` values. Rather than
    including ``NaN`` values in the array in the convolution calculation, which
    causes large ``NaN`` holes in the convolved array, ``NaN`` values are
    replaced with interpolated values using the kernel as an interpolation
    function.

    Parameters
    ----------
    array : `~astropy.nddata.NDData` or array-like
        The array to convolve. This should be a 1, 2, or 3-dimensional array
        or a list or a set of nested lists representing a 1, 2, or
        3-dimensional array.  If an `~astropy.nddata.NDData`, the ``mask`` of
        the `~astropy.nddata.NDData` will be used as the ``mask`` argument.
    kernel : `numpy.ndarray` or `~astropy.convolution.Kernel`
        The convolution kernel. The number of dimensions should match those for
        the array, and the dimensions should be odd in all directions.  If a
        masked array, the masked values will be replaced by ``fill_value``.
    boundary : str, optional
        A flag indicating how to handle boundaries:
            * `None`
                Set the ``result`` values to zero where the kernel
                extends beyond the edge of the array.
            * 'fill'
                Set values outside the array boundary to ``fill_value`` (default).
            * 'wrap'
                Periodic boundary that wrap to the other side of ``array``.
            * 'extend'
                Set values outside the array to the nearest ``array``
                value.
    fill_value : float, optional
        The value to use outside the array when using ``boundary='fill'``
    normalize_kernel : bool, optional
        Whether to normalize the kernel to have a sum of one.
    nan_treatment : {'interpolate', 'fill'}
        interpolate will result in renormalization of the kernel at each
        position ignoring (pixels that are NaN in the image) in both the image
        and the kernel.
        'fill' will replace the NaN pixels with a fixed numerical value (default
        zero, see ``fill_value``) prior to convolution
        Note that if the kernel has a sum equal to zero, NaN interpolation
        is not possible and will raise an exception.
    preserve_nan : bool
        After performing convolution, should pixels that were originally NaN
        again become NaN?
    mask : None or ndarray
        A "mask" array.  Shape must match ``array``, and anything that is masked
        (i.e., not 0/`False`) will be set to NaN for the convolution.  If
        `None`, no masking will be performed unless ``array`` is a masked array.
        If ``mask`` is not `None` *and* ``array`` is a masked array, a pixel is
        masked of it is masked in either ``mask`` *or* ``array.mask``.
    normalization_zero_tol : float, optional
        The absolute tolerance on whether the kernel is different than zero.
        If the kernel sums to zero to within this precision, it cannot be
        normalized. Default is "1e-8".

    Returns
    -------
    result : `numpy.ndarray`
        An array with the same dimensions and as the input array,
        convolved with kernel.  The data type depends on the input
        array type.  If array is a floating point type, then the
        return array keeps the same data type, otherwise the type
        is ``numpy.float``.

    Notes
    -----
    For masked arrays, masked values are treated as NaNs.  The convolution
    is always done at ``numpy.float`` precision.
    z(Invalid boundary option: must be one of )r|   rK   z1nan_treatment must be one of 'interpolate','fill'r   rj   )rU   rm   rt   ru   rv   rU   Nz¢Both array and kernel are Kernel instances, hardwiring the following parameters: boundary='fill', fill_value=0, normalize_Kernel=True, nan_treatment='interpolate'rK   r   Tr|   z$cannot convolve 0-dimensional arraysr   zBconvolve only supports 1, 2, and 3-dimensional arrays at this timez5array and kernel have differing number of dimensions.r   ztfor boundary=None all kernel axes must be smaller than array's - use boundary in ['fill', 'extend', 'wrap'] instead.)Zatolg      ð?zeThe kernel can't be normalized, because its sum is close to zero. The sum of the given kernel is < {})rU   rm   )rK   rM   rL   F)rv   rU   rm   ZconstantÚedgerL   )Ú	pad_widthÚmodezÓnan_treatment='interpolate', however, NaN values detected post convolution. A contiguous region of NaN values, larger than the kernel size, are present in the input array. Increase the kernel size to avoid this.rk   )rX   z%Only 1D and 2D Kernels are supported.Úf)rl   )(ÚBOUNDARY_OPTIONSrc   ry   ÚfloatrW   ÚnanÚgetattrrU   r   r   rn   r   ÚwarningsÚwarnr
   ÚndimÚ	ExceptionÚNotImplementedErrorrX   rd   Úallr   ÚisnanÚsumÚiscloser	   ÚformatÚzerosÚfullÚpadÚ_convolveNd_cÚctypesÚc_size_tr   r   rr   Z_is_boolZ
_separableÚkindZastype)rX   ÚkernelÚboundaryrv   rt   Únormalize_kernelru   Úpreserve_nanÚnormalization_zero_tolZ	n_threadsZpassed_kernelZpassed_arrayZarray_internalZarray_dtypeZkernel_internalZarray_shapeZkernel_shaper   Znan_interpolateZ
kernel_sumZkernel_sums_to_zeroZinitially_nanÚresultZ!embed_result_within_padded_regionZarray_to_convolveZnp_pad_mode_dictZnp_pad_modeZnp_pad_widthÚ
array_unitZ
new_resultrN   rN   rS   Úconvolve’   sÐ    N









6L


rž   c       /   	   C   st  t |tƒr"|j}t | tƒr"tdƒ‚|dkr2tdƒ‚t| ddƒ}t| td||tj	d} t|tddddd}| j
|j
kr|td	ƒ‚| j}|j}tj|tjd
t |¡j tj }|dtj krÐ|sÐtdt|ƒ› dƒ‚t | ¡t | ¡B }|dkrö|| |< nd| |< t |¡t |¡B }d||< |dkr^| ¡ dt k rHtd dt ¡ƒ‚| ¡ }|| }d}nV|rv||ƒ}|| }n>| ¡ }t |¡|k r¬|dkr¢tdƒ‚nd}|}n|| }|dkrèt dt¡ |dkrØd}|dkrld}n„|dkr&|dkrt d|› dt¡ nd}|dkrld}nF|dkrZ|r>tdƒ‚d}|rPtdƒ‚d}d}n|dkrltdƒ‚|rˆt |¡t |¡ }nt ||¡}|r¢t |ƒ}tj|tjd
t |¡j tj }|dtj krî|sîtdt|ƒ› dƒ‚g }g }x|t!t"|||ƒƒD ]h\}\}} }!||d d  }"|t#|"| d  |"| d d  ƒg7 }|t#|"|!d  |"|!d d  ƒg7 }qW t$|ƒ}t$|ƒ}t %||k¡sÌt &|¡r´tj'||d
| }#ntj(||d
}#| |#|< n| }#t %||k¡søtj(||d
}$||$|< n|}$||#ƒ}%|tj) *|$¡ƒ}&|%|& }'|dk}(|(rŒt &|¡sFtj(||d
})ntj'||d
})d||(  |)|< ||)ƒ}*|*|& }+||+ƒ},|,j+| |)|< nd})t |'¡ ,¡ r¨tdƒ‚|'|9 }'|dk	rÂ|'|K }'|
rÌ|'S |(r:tj-ddd  ||'ƒ|) }-W dQ R X t .|)¡sB|d!krtj	|-|)|k < nd!|-|)d"t /|)j¡j0 k < n||'ƒ}-|rVtj	|-| |< |	rj|-| j+}.|.S |-j+S dS )#a"  
    Convolve an ndarray with an nd-kernel.  Returns a convolved image with
    ``shape = array.shape``.  Assumes kernel is centered.

    `convolve_fft` is very similar to `convolve` in that it replaces ``NaN``
    values in the original image with interpolated values using the kernel as
    an interpolation function.  However, it also includes many additional
    options specific to the implementation.

    `convolve_fft` differs from `scipy.signal.fftconvolve` in a few ways:

    * It can treat ``NaN`` values as zeros or interpolate over them.
    * ``inf`` values are treated as ``NaN``
    * It optionally pads to the nearest faster sizes to improve FFT speed.
      These sizes are optimized for the numpy and scipy implementations, and
      ``fftconvolve`` uses them by default as well; when using other external
      functions (see below), results may vary.
    * Its only valid ``mode`` is 'same' (i.e., the same shape array is returned)
    * It lets you use your own fft, e.g.,
      `pyFFTW <https://pypi.org/project/pyFFTW/>`_ or
      `pyFFTW3 <https://pypi.org/project/PyFFTW3/0.2.1/>`_ , which can lead to
      performance improvements, depending on your system configuration.  pyFFTW3
      is threaded, and therefore may yield significant performance benefits on
      multi-core machines at the cost of greater memory requirements.  Specify
      the ``fftn`` and ``ifftn`` keywords to override the default, which is
      `numpy.fft.fftn` and `numpy.fft.ifftn`.  The `scipy.fft` functions also
      offer somewhat better performance and a multi-threaded option.

    Parameters
    ----------
    array : `numpy.ndarray`
        Array to be convolved with ``kernel``.  It can be of any
        dimensionality, though only 1, 2, and 3d arrays have been tested.
    kernel : `numpy.ndarray` or `astropy.convolution.Kernel`
        The convolution kernel. The number of dimensions should match those
        for the array.  The dimensions *do not* have to be odd in all directions,
        unlike in the non-fft `convolve` function.  The kernel will be
        normalized if ``normalize_kernel`` is set.  It is assumed to be centered
        (i.e., shifts may result if your kernel is asymmetric)
    boundary : {'fill', 'wrap'}, optional
        A flag indicating how to handle boundaries:

            * 'fill': set values outside the array boundary to fill_value
              (default)
            * 'wrap': periodic boundary

        The `None` and 'extend' parameters are not supported for FFT-based
        convolution
    fill_value : float, optional
        The value to use outside the array when using boundary='fill'
    nan_treatment : {'interpolate', 'fill'}
        ``interpolate`` will result in renormalization of the kernel at each
        position ignoring (pixels that are NaN in the image) in both the image
        and the kernel.  ``fill`` will replace the NaN pixels with a fixed
        numerical value (default zero, see ``fill_value``) prior to
        convolution.  Note that if the kernel has a sum equal to zero, NaN
        interpolation is not possible and will raise an exception.
    normalize_kernel : callable or boolean, optional
        If specified, this is the function to divide kernel by to normalize it.
        e.g., ``normalize_kernel=np.sum`` means that kernel will be modified to be:
        ``kernel = kernel / np.sum(kernel)``.  If True, defaults to
        ``normalize_kernel = np.sum``.
    normalization_zero_tol : float, optional
        The absolute tolerance on whether the kernel is different than zero.
        If the kernel sums to zero to within this precision, it cannot be
        normalized. Default is "1e-8".
    preserve_nan : bool
        After performing convolution, should pixels that were originally NaN
        again become NaN?
    mask : None or ndarray
        A "mask" array.  Shape must match ``array``, and anything that is masked
        (i.e., not 0/`False`) will be set to NaN for the convolution.  If
        `None`, no masking will be performed unless ``array`` is a masked array.
        If ``mask`` is not `None` *and* ``array`` is a masked array, a pixel is
        masked of it is masked in either ``mask`` *or* ``array.mask``.
    crop : bool, optional
        Default on.  Return an image of the size of the larger of the input
        image and the kernel.
        If the image and kernel are asymmetric in opposite directions, will
        return the largest image in both directions.
        For example, if an input image has shape [100,3] but a kernel with shape
        [6,6] is used, the output will be [100,6].
    return_fft : bool, optional
        Return the ``fft(image)*fft(kernel)`` instead of the convolution (which is
        ``ifft(fft(image)*fft(kernel))``).  Useful for making PSDs.
    fft_pad : bool, optional
        Default on.  Zero-pad image to the nearest size supporting more efficient
        execution of the FFT, generally values factorizable into the first 3-5
        prime numbers.  With ``boundary='wrap'``, this will be disabled.
    psf_pad : bool, optional
        Zero-pad image to be at least the sum of the image sizes to avoid
        edge-wrapping when smoothing.  This is enabled by default with
        ``boundary='fill'``, but it can be overridden with a boolean option.
        ``boundary='wrap'`` and ``psf_pad=True`` are not compatible.
    min_wt : float, optional
        If ignoring ``NaN`` / zeros, force all grid points with a weight less than
        this value to ``NaN`` (the weight of a grid point with *no* ignored
        neighbors is 1.0).
        If ``min_wt`` is zero, then all zero-weight points will be set to zero
        instead of ``NaN`` (which they would be otherwise, because 1/0 = nan).
        See the examples below.
    allow_huge : bool, optional
        Allow huge arrays in the FFT?  If False, will raise an exception if the
        array or kernel size is >1 GB.
    fftn : callable, optional
        The fft function.  Can be overridden to use your own ffts,
        e.g. an fftw3 wrapper or scipy's fftn, ``fft=scipy.fftpack.fftn``.
    ifftn : callable, optional
        The inverse fft function. Can be overridden the same way ``fttn``.
    complex_dtype : complex type, optional
        Which complex dtype to use.  `numpy` has a range of options, from 64 to
        256.

    Raises
    ------
    ValueError:
        If the array is bigger than 1 GB after padding, will raise this
        exception unless ``allow_huge`` is True

    See Also
    --------
    convolve:
        Convolve is a non-fft version of this code.  It is more memory
        efficient and for small kernels can be faster.

    Returns
    -------
    default : ndarray
        ``array`` convolved with ``kernel``.  If ``return_fft`` is set, returns
        ``fft(array) * fft(kernel)``.  If crop is not set, returns the
        image, but with the fft-padded size instead of the input size

    Notes
    -----
        With ``psf_pad=True`` and a large PSF, the resulting data can become
        large and consume a lot of memory.  See Issue
        https://github.com/astropy/astropy/pull/4366 and the update in
        https://github.com/astropy/astropy/pull/11533 for further details.

    Examples
    --------
    >>> convolve_fft([1, 0, 3], [1, 1, 1])
    array([0.33333333, 1.33333333, 1.        ])

    >>> convolve_fft([1, np.nan, 3], [1, 1, 1])
    array([0.5, 2. , 1.5])

    >>> convolve_fft([1, 0, 3], [0, 1, 0])
    array([ 1.00000000e+00, -3.70074342e-17,  3.00000000e+00])

    >>> convolve_fft([1, 2, 3], [1])
    array([1., 2., 3.])

    >>> convolve_fft([1, np.nan, 3], [0, 1, 0], nan_treatment='interpolate')
    array([1., 0., 3.])

    >>> convolve_fft([1, np.nan, 3], [0, 1, 0], nan_treatment='interpolate',
    ...              min_wt=1e-8)
    array([ 1., nan,  3.])

    >>> convolve_fft([1, np.nan, 3], [1, 1, 1], nan_treatment='interpolate')
    array([0.5, 2. , 1.5])

    >>> convolve_fft([1, np.nan, 3], [1, 1, 1], nan_treatment='interpolate',
    ...               normalize_kernel=True)
    array([0.5, 2. , 1.5])

    >>> import scipy.fft  # optional - requires scipy
    >>> convolve_fft([1, np.nan, 3], [1, 1, 1], nan_treatment='interpolate',
    ...               normalize_kernel=True,
    ...               fftn=scipy.fft.fftn, ifftn=scipy.fft.ifftn)
    array([0.5, 2. , 1.5])

    >>> fft_mp = lambda a: scipy.fft.fftn(a, workers=-1)  # use all available cores
    >>> ifft_mp = lambda a: scipy.fft.ifftn(a, workers=-1)
    >>> convolve_fft([1, np.nan, 3], [1, 1, 1], nan_treatment='interpolate',
    ...               normalize_kernel=True, fftn=fft_mp, ifftn=ifft_mp)
    array([0.5, 2. , 1.5])
    zDCan't convolve two kernels with convolve_fft.  Use convolve instead.)r|   rK   z1nan_treatment must be one of 'interpolate','fill'rk   Nrj   )rU   rm   rt   ru   rv   r   z4Image and kernel must have same number of dimensions)rU   r   zSize Error: Arrays will be z2.  Use allow_huge=True to override this exception.rK   Tg      ð?zeThe kernel can't be normalized, because its sum is close to zero. The sum of the given kernel is < {}r|   z5Cannot interpolate NaNs with an unnormalizable kernelz¡The convolve_fft version of boundary=None is equivalent to the convolve boundary='fill'.  There is no FFT equivalent to convolve's zero-if-kernel-leaves-boundaryFzpsf_pad was set to z., which overrides the boundary='fill' setting.rL   z0With boundary='wrap', psf_pad cannot be enabled.z0With boundary='wrap', fft_pad cannot be enabled.rM   z@The 'extend' option is not implemented for fft-based convolutionr   z2Encountered NaNs in convolve.  This is disallowed.Úignore)ÚdivideÚinvalidg        r   )1rn   r   rX   rr   rc   r…   ry   ÚcomplexrW   r„   rˆ   rd   ÚproductZint64rU   ÚitemsizeÚuÚbyteÚGBr   rŒ   Úisinfr   r	   r‰   r   Úabsr†   r‡   r
   rŠ   Úmaximumri   r]   ÚzipÚsliceÚtupler‹   ÚisfiniteZonesr   rO   Z	ifftshiftÚrealÚanyZerrstateZisscalarZfinfoZeps)/rX   r—   r˜   rv   rt   r™   r›   rš   ru   ÚcropZ
return_fftZfft_padZpsf_padZmin_wtZ
allow_hugeÚfftnÚifftnZcomplex_dtyper   Z
arrayshapeZ	kernshapeZarray_size_BZnanmaskarrayZnanmaskkernelZkernel_scaleZnormalized_kernelre   Zarray_size_CZarrayslicesZ
kernslicesÚiiZ
newdimsizeZarraydimsizeZkerndimsizeÚcenterZbigarrayZ	bigkernelZarrayfftZkernfftZfftmultZinterpolate_nanZbigimwtZwtfftZ	wtfftmultZwtsmZrifftrœ   rN   rN   rS   rJ   ¬  s
    A















 




rJ   c             K   sT   t  t  | ¡¡s|  ¡ S |  ¡ }|| |fddddœ|—Ž}t  | ¡}|| ||< |S )a\  
    Given a data set containing NaNs, replace the NaNs by interpolating from
    neighboring data points with a given kernel.

    Parameters
    ----------
    array : `numpy.ndarray`
        Array to be convolved with ``kernel``.  It can be of any
        dimensionality, though only 1, 2, and 3d arrays have been tested.
    kernel : `numpy.ndarray` or `astropy.convolution.Kernel`
        The convolution kernel. The number of dimensions should match those
        for the array.  The dimensions *do not* have to be odd in all directions,
        unlike in the non-fft `convolve` function.  The kernel will be
        normalized if ``normalize_kernel`` is set.  It is assumed to be centered
        (i.e., shifts may result if your kernel is asymmetric).  The kernel
        *must be normalizable* (i.e., its sum cannot be zero).
    convolve : `convolve` or `convolve_fft`
        One of the two convolution functions defined in this package.

    Returns
    -------
    newarray : `numpy.ndarray`
        A copy of the original array with NaN pixels replaced with their
        interpolated counterparts
    r|   TF)rt   r™   rš   )rW   r°   rŒ   rl   )rX   r—   rž   ÚkwargsZnewarrayZ	convolvedrŒ   rN   rN   rS   Úinterpolate_replace_nansK  s    

r·   c             K   sX   |dkrt  dttf|Ž¡}n.|dkr<t  dttf|Ž¡}ntd|› dƒ‚t|| |ƒS )aç  
    Convolve two models using `~astropy.convolution.convolve_fft`.

    Parameters
    ----------
    model : `~astropy.modeling.core.Model`
        Functional model
    kernel : `~astropy.modeling.core.Model`
        Convolution kernel
    mode : str
        Keyword representing which function to use for convolution.
            * 'convolve_fft' : use `~astropy.convolution.convolve_fft` function.
            * 'convolve' : use `~astropy.convolution.convolve`.
    **kwargs : dict
        Keyword arguments to me passed either to `~astropy.convolution.convolve`
        or `~astropy.convolution.convolve_fft` depending on ``mode``.

    Returns
    -------
    default : `~astropy.modeling.core.CompoundModel`
        Convolved model
    rJ   rž   zMode z is not supported.)r   Úaddr   rJ   rž   rc   r   )Úmodelr—   r€   r¶   ÚoperatorrN   rN   rS   Úconvolve_modelst  s    r»   c             K   s&   t  dttf|Ž¡}t|| ||||ƒS )aº  
    Convolve two models using `~astropy.convolution.convolve_fft`.

    Parameters
    ----------
    model : `~astropy.modeling.core.Model`
        Functional model
    kernel : `~astropy.modeling.core.Model`
        Convolution kernel
    bounding_box : tuple
        The bounding box which encompasses enough of the support of both
        the ``model`` and ``kernel`` so that an accurate convolution can be
        computed.
    resolution : float
        The resolution that one wishes to approximate the convolution
        integral at.
    cache : optional, bool
        Default value True. Allow for the storage of the convolution
        computation for later reuse.
    **kwargs : dict
        Keyword arguments to be passed either to `~astropy.convolution.convolve`
        or `~astropy.convolution.convolve_fft` depending on ``mode``.

    Returns
    -------
    default : `~astropy.modeling.core.CompoundModel`
        Convolved model
    rJ   )r   r¸   r   rJ   r   )r¹   r—   Zbounding_boxÚ
resolutionÚcacher¶   rº   rN   rN   rS   Úconvolve_models_fft–  s    r¾   )rK   r{   r|   TNFr}   )rJ   )T)Cr†   Úosr”   Ú	functoolsr   ÚnumpyrW   Znumpy.ctypeslibr   r   Úcorer   r   r   r	   Zastropy.utils.exceptionsr
   Zastropy.utils.consoler   Zastropyr   r¥   Zastropy.nddatar   Zastropy.modeling.corer   r   Zastropy.modeling.convolutionr   Úutilsr   r   r   ÚpathÚdirnameÚ__file__ZLIBRARY_PATHr   r‰   rY   ZconvolveNd_cr“   ÚrestypeZc_doubleZc_uintr•   Zc_boolZargtypesrX   rb   r\   r`   ra   Z__doctest_requires__r‚   ri   rƒ   ry   rž   rO   r²   r³   r¢   rJ   r·   r»   r¾   rN   rN   rN   rS   Ú<module>   s   

+       )
"