photutils/psf/models.py
def create_from_image(cls, imdata, positions, size, fluxes=None,
                          mask=None, mode='mean', subsampling=1,
                          fix_nan=False):
        """
        Create a discrete point response function (PRF) from image data.

        Given a list of positions and size this function estimates an
        image of the PRF by extracting and combining the individual PRFs
        from the given positions.

        NaN values are either ignored by passing a mask or can be
        replaced by the mirrored value with respect to the center of the
        PRF.

        Note that if fluxes are *not* specified explicitly, it will be
        flux estimated from an aperture of the same size as the PRF
        image. This does *not* account for aperture corrections so often
        will *not* be what you want for anything other than quick-look
        needs.

        Parameters
        ----------
        imdata : array
            Data array with the image to extract the PRF from
        positions : List or array or `~astropy.table.Table`
            List of pixel coordinate source positions to use in creating
            the PRF.  If this is a `~astropy.table.Table` it must have
            columns called ``x_0`` and ``y_0``.
        size : odd int
            Size of the quadratic PRF image in pixels.
        mask : bool array, optional
            Boolean array to mask out bad values.
        fluxes : array, optional
            Object fluxes to normalize extracted PRFs. If not given (or
            None), the flux is estimated from an aperture of the same
            size as the PRF image.
        mode : {'mean', 'median'}
            One of the following modes to combine the extracted PRFs:
                * 'mean':  Take the pixelwise mean of the extracted PRFs.
                * 'median':  Take the pixelwise median of the extracted PRFs.
        subsampling : int
            Factor of subsampling of the PRF (default = 1).
        fix_nan : bool
            Fix NaN values in the data by replacing it with the mirrored
            value. Assuming that the PRF is symmetrical.

        Returns
        -------
        prf : `photutils.psf.sandbox.DiscretePRF`
            Discrete PRF model estimated from data.
        """

        # Check input array type and dimension.
        if np.iscomplexobj(imdata):
            raise TypeError('Complex type not supported')
        if imdata.ndim != 2:
            raise ValueError('{0}-d array not supported. '
                             'Only 2-d arrays supported.'.format(imdata.ndim))
        if size % 2 == 0:
            raise TypeError("Size must be odd.")

        if fluxes is not None and len(fluxes) != len(positions):
            raise TypeError('Position and flux arrays must be of equal '
                            'length.')

        if mask is None:
            mask = np.isnan(imdata)

        if isinstance(positions, (list, tuple)):
            positions = np.array(positions)

        if isinstance(positions, Table) or \
            (isinstance(positions, np.ndarray) and
             positions.dtype.names is not None):
            # One can do clever things like
            # positions['x_0', 'y_0'].as_array().view((positions['x_0'].dtype,
            #                                          2))
            # but that requires positions['x_0'].dtype is
            # positions['y_0'].dtype.
            # Better do something simple to allow type promotion if required.
            pos = np.empty((len(positions), 2))
            pos[:, 0] = positions['x_0']
            pos[:, 1] = positions['y_0']
            positions = pos

        if isinstance(fluxes, (list, tuple)):
            fluxes = np.array(fluxes)

        if mode == 'mean':
            combine = np.ma.mean
        elif mode == 'median':
            combine = np.ma.median
        else:
            raise Exception('Invalid mode to combine prfs.')

        data_internal = np.ma.array(data=imdata, mask=mask)
        prf_model = np.ndarray(shape=(subsampling, subsampling, size, size))
        positions_subpixel_indices = \
            np.array([subpixel_indices(_, subsampling) for _ in positions],
                     dtype=np.int)

        for i in range(subsampling):
            for j in range(subsampling):
                extracted_sub_prfs = []
                sub_prf_indices = np.all(positions_subpixel_indices == [j, i],
                                         axis=1)
                positions_sub_prfs = positions[sub_prf_indices]
                for k, position in enumerate(positions_sub_prfs):
                    x, y = position
                    extracted_prf = extract_array(data_internal, (size, size),
                                                  (y, x))
                    # Check shape to exclude incomplete PRFs at the boundaries
                    # of the image
                    if (extracted_prf.shape == (size, size) and
                            np.ma.sum(extracted_prf) != 0):
                        # Replace NaN values by mirrored value, with respect
                        # to the prf's center
                        if fix_nan:
                            prf_nan = extracted_prf.mask
                            if prf_nan.any():
                                if (prf_nan.sum() > 3 or
                                        prf_nan[size // 2, size // 2]):
                                    continue
                                else:
                                    extracted_prf = mask_to_mirrored_num(
                                        extracted_prf, prf_nan,
                                        (size // 2, size // 2))
                        # Normalize and add extracted PRF to data cube
                        if fluxes is None:
                            extracted_prf_norm = (np.ma.copy(extracted_prf) /
                                                  np.ma.sum(extracted_prf))
                        else:
                            fluxes_sub_prfs = fluxes[sub_prf_indices]
                            extracted_prf_norm = (np.ma.copy(extracted_prf) /
                                                  fluxes_sub_prfs[k])
                        extracted_sub_prfs.append(extracted_prf_norm)
                    else:
                        continue
                prf_model[i, j] = np.ma.getdata(
                    combine(np.ma.dstack(extracted_sub_prfs), axis=2))
        return cls(prf_model, subsampling=subsampling)

        Create a discrete point response function (PRF) from image data.

        Given a list of positions and size this function estimates an
        image of the PRF by extracting and combining the individual PRFs
        from the given positions.

        NaN values are either ignored by passing a mask or can be
        replaced by the mirrored value with respect to the center of the
        PRF.

        Note that if fluxes are *not* specified explicitly, it will be
        flux estimated from an aperture of the same size as the PRF
        image. This does *not* account for aperture corrections so often
        will *not* be what you want for anything other than quick-look
        needs.

        Parameters
        ----------
        imdata : array
            Data array with the image to extract the PRF from
        positions : List or array or `~astropy.table.Table`
            List of pixel coordinate source positions to use in creating
            the PRF.  If this is a `~astropy.table.Table` it must have
            columns called ``x_0`` and ``y_0``.
        size : odd int
            Size of the quadratic PRF image in pixels.
        mask : bool array, optional
            Boolean array to mask out bad values.
        fluxes : array, optional
            Object fluxes to normalize extracted PRFs. If not given (or
            None), the flux is estimated from an aperture of the same
            size as the PRF image.
        mode : {'mean', 'median'}
            One of the following modes to combine the extracted PRFs:
                * 'mean':  Take the pixelwise mean of the extracted PRFs.
                * 'median':  Take the pixelwise median of the extracted PRFs.
        subsampling : int
            Factor of subsampling of the PRF (default = 1).
        fix_nan : bool
            Fix NaN values in the data by replacing it with the mirrored
            value. Assuming that the PRF is symmetrical.

        Returns
        -------
        prf : `photutils.psf.sandbox.DiscretePRF`
            Discrete PRF model estimated from data.
        
Create a discrete point response function (PRF) from image data.
Given a list of positions and size this function estimates an
image of the PRF by extracting and combining the individual PRFs
from the given positions.

NaN values are either ignored by passing a mask or can be
replaced by the mirrored value with respect to the center of the
PRF.

Note that if fluxes are *not* specified explicitly, it will be
flux estimated from an aperture of the same size as the PRF
image. This does *not* account for aperture corrections so often
will *not* be what you want for anything other than quick-look
needs.

Parameters

imdata : array
Data array with the image to extract the PRF from
positions : List or array or `~astropy.table.Table`
List of pixel coordinate source positions to use in creating
the PRF.

Returns

prf : `photutils.psf.sandbox.DiscretePRF`
Discrete PRF model estimated from data.
Create a discrete point response function ( PRF ) from image data . Given a list of positions and size this function estimates an image of the PRF by extracting and combining the individual PRFs from the given positions . NaN values are either ignored by passing a mask or can be replaced by the mirrored value with respect to the center of the PRF . Note that if fluxes are * not * specified explicitly it will be flux estimated from an aperture of the same size as the PRF image . This does * not * account for aperture corrections so often will * not * be what you want for anything other than quick - look needs . Parameters imdata : array Data array with the image to extract the PRF from positions : List or array or ` ~astropy . table . Table ` List of pixel coordinate source positions to use in creating the PRF . Returns prf : ` photutils . psf . sandbox . DiscretePRF ` Discrete PRF model estimated from data .
def create_from_image(cls, imdata, positions, size, fluxes=None,
                          mask=None, mode='mean', subsampling=1,
                          fix_nan=False):
        if np.iscomplexobj(imdata):
            raise TypeError('Complex type not supported')
        if imdata.ndim != 2:
            raise ValueError('{0}-d array not supported. '
                             'Only 2-d arrays supported.'.format(imdata.ndim))
        if size % 2 == 0:
            raise TypeError("Size must be odd.")
        if fluxes is not None and len(fluxes) != len(positions):
            raise TypeError('Position and flux arrays must be of equal '
                            'length.')
        if mask is None:
            mask = np.isnan(imdata)
        if isinstance(positions, (list, tuple)):
            positions = np.array(positions)
        if isinstance(positions, Table) or \
            (isinstance(positions, np.ndarray) and
             positions.dtype.names is not None):
            pos = np.empty((len(positions), 2))
            pos[:, 0] = positions['x_0']
            pos[:, 1] = positions['y_0']
            positions = pos
        if isinstance(fluxes, (list, tuple)):
            fluxes = np.array(fluxes)
        if mode == 'mean':
            combine = np.ma.mean
        elif mode == 'median':
            combine = np.ma.median
        else:
            raise Exception('Invalid mode to combine prfs.')
        data_internal = np.ma.array(data=imdata, mask=mask)
        prf_model = np.ndarray(shape=(subsampling, subsampling, size, size))
        positions_subpixel_indices = \
            np.array([subpixel_indices(_, subsampling) for _ in positions],
                     dtype=np.int)
        for i in range(subsampling):
            for j in range(subsampling):
                extracted_sub_prfs = []
                sub_prf_indices = np.all(positions_subpixel_indices == [j, i],
                                         axis=1)
                positions_sub_prfs = positions[sub_prf_indices]
                for k, position in enumerate(positions_sub_prfs):
                    x, y = position
                    extracted_prf = extract_array(data_internal, (size, size),
                                                  (y, x))
                    if (extracted_prf.shape == (size, size) and
                            np.ma.sum(extracted_prf) != 0):
                        if fix_nan:
                            prf_nan = extracted_prf.mask
                            if prf_nan.any():
                                if (prf_nan.sum() > 3 or
                                        prf_nan[size // 2, size // 2]):
                                    continue
                                else:
                                    extracted_prf = mask_to_mirrored_num(
                                        extracted_prf, prf_nan,
                                        (size // 2, size // 2))
                        if fluxes is None:
                            extracted_prf_norm = (np.ma.copy(extracted_prf) /
                                                  np.ma.sum(extracted_prf))
                        else:
                            fluxes_sub_prfs = fluxes[sub_prf_indices]
                            extracted_prf_norm = (np.ma.copy(extracted_prf) /
                                                  fluxes_sub_prfs[k])
                        extracted_sub_prfs.append(extracted_prf_norm)
                    else:
                        continue
                prf_model[i, j] = np.ma.getdata(
                    combine(np.ma.dstack(extracted_sub_prfs), axis=2))
        return cls(prf_model, subsampling=subsampling)
def create_from_image ( cls , imdata , positions , size , fluxes = None , mask = None , mode = 'mean' , subsampling = 1 , fix_nan = False ) : if np . iscomplexobj ( imdata ) : raise TypeError ( 'Complex type not supported' ) if imdata . ndim != 2 : raise ValueError ( '{0}-d array not supported. ' 'Only 2-d arrays supported.' . format ( imdata . ndim ) ) if size % 2 == 0 : raise TypeError ( "Size must be odd." ) if fluxes is not None and len ( fluxes ) != len ( positions ) : raise TypeError ( 'Position and flux arrays must be of equal ' 'length.' ) if mask is None : mask = np . isnan ( imdata ) if isinstance ( positions , ( list , tuple ) ) : positions = np . array ( positions ) if isinstance ( positions , Table ) or ( isinstance ( positions , np . ndarray ) and positions . dtype . names is not None ) : pos = np . empty ( ( len ( positions ) , 2 ) ) pos [ : , 0 ] = positions [ 'x_0' ] pos [ : , 1 ] = positions [ 'y_0' ] positions = pos if isinstance ( fluxes , ( list , tuple ) ) : fluxes = np . array ( fluxes ) if mode == 'mean' : combine = np . ma . mean elif mode == 'median' : combine = np . ma . median else : raise Exception ( 'Invalid mode to combine prfs.' ) data_internal = np . ma . array ( data = imdata , mask = mask ) prf_model = np . ndarray ( shape = ( subsampling , subsampling , size , size ) ) positions_subpixel_indices = np . array ( [ subpixel_indices ( _ , subsampling ) for _ in positions ] , dtype = np . int ) for i in range ( subsampling ) : for j in range ( subsampling ) : extracted_sub_prfs = [ ] sub_prf_indices = np . all ( positions_subpixel_indices == [ j , i ] , axis = 1 ) positions_sub_prfs = positions [ sub_prf_indices ] for k , position in enumerate ( positions_sub_prfs ) : x , y = position extracted_prf = extract_array ( data_internal , ( size , size ) , ( y , x ) ) if ( extracted_prf . shape == ( size , size ) and np . ma . sum ( extracted_prf ) != 0 ) : if fix_nan : prf_nan = extracted_prf . mask if prf_nan . any ( ) : if ( prf_nan . sum ( ) > 3 or prf_nan [ size // 2 , size // 2 ] ) : continue else : extracted_prf = mask_to_mirrored_num ( extracted_prf , prf_nan , ( size // 2 , size // 2 ) ) if fluxes is None : extracted_prf_norm = ( np . ma . copy ( extracted_prf ) / np . ma . sum ( extracted_prf ) ) else : fluxes_sub_prfs = fluxes [ sub_prf_indices ] extracted_prf_norm = ( np . ma . copy ( extracted_prf ) / fluxes_sub_prfs [ k ] ) extracted_sub_prfs . append ( extracted_prf_norm ) else : continue prf_model [ i , j ] = np . ma . getdata ( combine ( np . ma . dstack ( extracted_sub_prfs ) , axis = 2 ) ) return cls ( prf_model , subsampling = subsampling )
Create a discrete point response function (PRF) from image data.
Create a discrete point response function ( PRF ) from image data .
"""
        Create a discrete point response function (PRF) from image data.

        Given a list of positions and size this function estimates an
        image of the PRF by extracting and combining the individual PRFs
        from the given positions.

        NaN values are either ignored by passing a mask or can be
        replaced by the mirrored value with respect to the center of the
        PRF.

        Note that if fluxes are *not* specified explicitly, it will be
        flux estimated from an aperture of the same size as the PRF
        image. This does *not* account for aperture corrections so often
        will *not* be what you want for anything other than quick-look
        needs.

        Parameters
        ----------
        imdata : array
            Data array with the image to extract the PRF from
        positions : List or array or `~astropy.table.Table`
            List of pixel coordinate source positions to use in creating
            the PRF.  If this is a `~astropy.table.Table` it must have
            columns called ``x_0`` and ``y_0``.
        size : odd int
            Size of the quadratic PRF image in pixels.
        mask : bool array, optional
            Boolean array to mask out bad values.
        fluxes : array, optional
            Object fluxes to normalize extracted PRFs. If not given (or
            None), the flux is estimated from an aperture of the same
            size as the PRF image.
        mode : {'mean', 'median'}
            One of the following modes to combine the extracted PRFs:
                * 'mean':  Take the pixelwise mean of the extracted PRFs.
                * 'median':  Take the pixelwise median of the extracted PRFs.
        subsampling : int
            Factor of subsampling of the PRF (default = 1).
        fix_nan : bool
            Fix NaN values in the data by replacing it with the mirrored
            value. Assuming that the PRF is symmetrical.

        Returns
        -------
        prf : `photutils.psf.sandbox.DiscretePRF`
            Discrete PRF model estimated from data.
        """ # Check input array type and dimension. # One can do clever things like # positions['x_0', 'y_0'].as_array().view((positions['x_0'].dtype, #                                          2)) # but that requires positions['x_0'].dtype is # positions['y_0'].dtype. # Better do something simple to allow type promotion if required. # Check shape to exclude incomplete PRFs at the boundaries # of the image # Replace NaN values by mirrored value, with respect # to the prf's center # Normalize and add extracted PRF to data cube
cls
imdata
positions
size
fluxes
mask
mode
subsampling
fix_nan