Exemplo n.º 1
0
def filter_convolve(data, filters, filter_rot=False, method='scipy'):
    r"""Filter convolve

    This method convolves the input image with the wavelet filters.

    Parameters
    ----------
    data : numpy.ndarray
        Input data, 2D array
    filters : numpy.ndarray
        Wavelet filters, 3D array
    filter_rot : bool, optional
        Option to rotate wavelet filters (default is `False`)
    method : {'astropy', 'scipy'}, optional
        Convolution method (default is 'scipy')

    Returns
    -------
    numpy.ndarray
        Convolved data

    Examples
    --------
    >>> from modopt.signal.wavelet import filter_convolve
    >>> x = np.arange(9).reshape(3, 3).astype(float)
    >>> y = np.arange(36).reshape(4, 3, 3).astype(float)
    >>> filter_convolve(x, y)
    array([[[  174.,   165.,   174.],
            [   93.,    84.,    93.],
            [  174.,   165.,   174.]],
    <BLANKLINE>
           [[  498.,   489.,   498.],
            [  417.,   408.,   417.],
            [  498.,   489.,   498.]],
    <BLANKLINE>
           [[  822.,   813.,   822.],
            [  741.,   732.,   741.],
            [  822.,   813.,   822.]],
    <BLANKLINE>
           [[ 1146.,  1137.,  1146.],
            [ 1065.,  1056.,  1065.],
            [ 1146.,  1137.,  1146.]]])

    >>> filter_convolve(y, y, filter_rot=True)
    array([[ 14550.,  14586.,  14550.],
           [ 14874.,  14910.,  14874.],
           [ 14550.,  14586.,  14550.]])

    """

    if filter_rot:
        return np.sum([
            convolve(coef, f, method=method)
            for coef, f in zip(data, rotate_stack(filters))
        ],
                      axis=0)

    else:
        return np.array([convolve(data, f, method=method) for f in filters])
Exemplo n.º 2
0
    def test_convolve_astropy(self):
        """Test convolve using astropy."""
        npt.assert_allclose(
            convolve.convolve(self.data1[0], self.data2[0], method='astropy'),
            np.array([
                [210.0, 201.0, 210.0],
                [129.0, 120.0, 129.0],
                [210.0, 201.0, 210.0],
            ]),
            err_msg='Incorrect convolution: astropy',
        )

        npt.assert_raises(
            ValueError,
            convolve.convolve,
            self.data1[0],
            self.data2,
        )

        npt.assert_raises(
            ValueError,
            convolve.convolve,
            self.data1[0],
            self.data2[0],
            method='bla',
        )
Exemplo n.º 3
0
def find_n_pc(u_vec, factor=0.5):
    """Find number of principal components.

    This method finds the minimum number of principal components required.

    Parameters
    ----------
    u_vec : numpy.ndarray
        Left singular vector of the original data
    factor : float, optional
        Factor for testing the auto correlation (default is ``0.5``)

    Returns
    -------
    int
        Number of principal components

    Raises
    ------
    ValueError
        Invalid left singular vector

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.linalg import svd
    >>> from modopt.signal.svd import find_n_pc
    >>> x = np.arange(18).reshape(9, 2).astype(float)
    >>> find_n_pc(svd(x)[0])
    1

    """
    if np.sqrt(u_vec.shape[0]) % 1:
        raise ValueError(
            'Invalid left singular vector. The size of the first '
            + 'dimenion of ``u_vec`` must be perfect square.',
        )

    # Get the shape of the array
    array_shape = np.repeat(np.int(np.sqrt(u_vec.shape[0])), 2)

    # Find the auto correlation of the left singular vector.
    u_auto = [
        convolve(
            elem.reshape(array_shape),
            np.rot90(elem.reshape(array_shape), 2),
        )
        for elem in u_vec.T
    ]

    # Return the required number of principal components.
    return np.sum([
        (
            u_val[tuple(zip(array_shape // 2))] ** 2 <= factor
            * np.sum(u_val ** 2),
        )
        for u_val in u_auto
    ])
Exemplo n.º 4
0
 def test_convolve_scipy(self):
     """Test convolve using scipy."""
     npt.assert_allclose(
         convolve.convolve(self.data1[0], self.data2[0], method='scipy'),
         np.array([
             [14.0, 35.0, 38.0],
             [57.0, 120.0, 111.0],
             [110.0, 197.0, 158.0],
         ]),
         err_msg='Incorrect convolution: scipy',
     )
Exemplo n.º 5
0
def psf_convolve(data, psf, psf_rot=False, psf_type='fixed', method='scipy'):
    """Convolve data with PSF

    This method convolves an image with a PSF

    Parameters
    ----------
    data : np.ndarray
        Input data array, normally an array of 2D images
    psf : np.ndarray
        Input PSF array, normally either a single 2D PSF or an array of 2D
        PSFs
    psf_rot: bool
        Option to rotate PSF by 180 degrees
    psf_type : str {'fixed', 'obj_var'}, optional
        PSF type (default is 'fixed')
    method : str {'astropy', 'scipy'}, optional
        Convolution method (default is 'astropy')

        'fixed':
            The PSF is fixed, i.e. it is the same for each image

        'obj_var':
            The PSF is object variant, i.e. it is different for each image

    Returns
    -------
    np.ndarray convolved data

    Raises
    ------
    ValueError
        If `psf_type` is not 'fixed' or 'obj_var'

    """

    if psf_type not in ('fixed', 'obj_var'):
        raise ValueError('Invalid PSF type. Options are "fixed" or "obj_var"')

    if psf_rot and psf_type == 'fixed':
        psf = rotate(psf)

    elif psf_rot:
        psf = rotate_stack(psf)

    if psf_type == 'fixed':
        return np.array([convolve(data_i, psf, method=method) for data_i in
                        data])

    elif psf_type == 'obj_var':

        return convolve_stack(data, psf, method=method)
Exemplo n.º 6
0
def psf_convolve(data, psf, psf_rot=False, psf_type='fixed', method='scipy'):
    """Convolve data with PSF

    This method convolves an image with a PSF

    Parameters
    ----------
    data : np.ndarray
        Input data array, normally an array of 2D images
    psf : np.ndarray
        Input PSF array, normally either a single 2D PSF or an array of 2D
        PSFs
    psf_rot: bool
        Option to rotate PSF by 180 degrees
    psf_type : str {'fixed', 'obj_var'}, optional
        PSF type (default is 'fixed')
    method : str {'astropy', 'scipy'}, optional
        Convolution method (default is 'astropy')

        'fixed':
            The PSF is fixed, i.e. it is the same for each image

        'obj_var':
            The PSF is object variant, i.e. it is different for each image

    Returns
    -------
    np.ndarray convolved data

    Raises
    ------
    ValueError
        If `psf_type` is not 'fixed' or 'obj_var'

    """

    if psf_type not in ('fixed', 'obj_var'):
        raise ValueError('Invalid PSF type. Options are "fixed" or "obj_var"')

    if psf_rot and psf_type == 'fixed':
        psf = rotate(psf)

    elif psf_rot:
        psf = rotate_stack(psf)

    if psf_type == 'fixed':
        return np.array(
            [convolve(data_i, psf, method=method) for data_i in data])

    elif psf_type == 'obj_var':

        return convolve_stack(data, psf, method=method)
Exemplo n.º 7
0
def psf_convolve(data, psf, psf_rot=False):
    """PSF Convolution.

    Parameters
    ----------
    data : np.ndarray
        Input data, 2D image
    psf : np.ndarray
        Input PSF, 2D image
    psf_rot : bool, optional
        Option to rotate the input PSF (default is False)

    Returns
    -------
    np.ndarray convolved image

    """
    if psf_rot:
        psf = rotate(psf)

    return convolve(data, psf)
Exemplo n.º 8
0
def find_n_pc(u, factor=0.5):
    """Find number of principal components

    This method finds the minimum number of principal components required

    Parameters
    ----------
    u : np.ndarray
        Left singular vector of the original data
    factor : float, optional
        Factor for testing the auto correlation (default is '0.5')

    Returns
    -------
    int number of principal components

    Examples
    --------
    >>> from scipy.linalg import svd
    >>> from modopt.signal.svd import find_n_pc
    >>> x = np.arange(18).reshape(9, 2).astype(float)
    >>> find_n_pc(svd(x)[0])
    array([3])

    """

    if np.sqrt(u.shape[0]) % 1:
        raise ValueError('Invalid left singular value. The size of the first '
                         'dimenion of u must be perfect square.')

    # Get the shape of the array
    array_shape = np.repeat(np.int(np.sqrt(u.shape[0])), 2)

    # Find the auto correlation of the left singular vector.
    u_auto = [convolve(a.reshape(array_shape),
              np.rot90(a.reshape(array_shape), 2)) for a in u.T]

    # Return the required number of principal components.
    return np.sum((a[list(zip(array_shape // 2))] ** 2 <= factor *
                  np.sum(a ** 2)) for a in u_auto)[0]
Exemplo n.º 9
0
"""

import numpy as np
from pysap import Image
from pysap.data import get_sample_data
from pysap.plugins.astro.deconvolve.deconvolve import sparse_deconv_condatvu
from modopt.signal.noise import add_noise
from modopt.math.convolve import convolve

# Load the example images
galaxy = get_sample_data('astro-galaxy')
psf = get_sample_data('astro-psf')

# Show the clean galaxy image
galaxy.show()

# Generate a noisy observed image
obs_data = add_noise(convolve(galaxy.data, psf.data), sigma=0.0005)
image_obs = Image(data=np.abs(obs_data))
image_obs.show()

# Deconvolve the observed image
deconv_data = sparse_deconv_condatvu(obs_data, psf.data, n_iter=3000)
image_rec = Image(data=np.abs(deconv_data))
image_rec.show()

# Show the residual
residual = Image(data=np.abs(galaxy.data - deconv_data))
residual.show()