Esempio n. 1
0
    def _lnlike():
        """
        Internal function for the log likelihood function. Noise of each pixel is assumed to follow
        either a Poisson distribution (see Wertz et al. 2017) or a Gaussian distribution with a
        correction for small sample statistics (see Mawet et al. 2014).

        Returns
        -------
        float
            Log likelihood.
        """

        sep, ang, mag = param

        fake = fake_planet(images=images,
                           psf=psf,
                           parang=parang - extra_rot,
                           position=(sep / pixscale, ang),
                           magnitude=mag,
                           psf_scaling=psf_scaling)

        _, im_res = pca_psf_subtraction(images=fake * mask,
                                        angles=-1. * parang + extra_rot,
                                        pca_number=pca_number,
                                        indices=indices)

        stack = combine_residuals(method=residuals, res_rot=im_res)

        merit = merit_function(residuals=stack[0, ],
                               function='sum',
                               variance=variance,
                               aperture=aperture,
                               sigma=0.)

        return -0.5 * merit
Esempio n. 2
0
    def _lnlike():
        """
        Internal function for the log likelihood function.

        Returns
        -------
        float
            Log likelihood.
        """

        sep, ang, mag = param

        fake = fake_planet(images=images,
                           psf=psf,
                           parang=parang - extra_rot,
                           position=(sep / pixscale, ang),
                           magnitude=mag,
                           psf_scaling=psf_scaling)

        _, im_res = pca_psf_subtraction(images=fake * mask,
                                        angles=-1. * parang + extra_rot,
                                        pca_number=pca_number,
                                        indices=indices)

        res_stack = combine_residuals(method=residuals, res_rot=im_res)

        chi_square = merit_function(residuals=res_stack[0, ],
                                    merit=merit,
                                    aperture=aperture,
                                    sigma=0.)

        return -0.5 * chi_square
Esempio n. 3
0
        def _objective(arg):
            sys.stdout.write('.')
            sys.stdout.flush()

            pos_y = arg[0]
            pos_x = arg[1]
            mag = arg[2]

            sep_ang = cartesian_to_polar(center, pos_y, pos_x)

            fake = fake_planet(images=images,
                               psf=psf,
                               parang=parang,
                               position=(sep_ang[0], sep_ang[1]),
                               magnitude=mag,
                               psf_scaling=self.m_psf_scaling)

            mask = create_mask(fake.shape[-2:], (self.m_cent_size, self.m_edge_size))

            if self.m_reference_in_port is None:
                _, im_res = pca_psf_subtraction(images=fake*mask,
                                                angles=-1.*parang+self.m_extra_rot,
                                                pca_number=self.m_pca_number,
                                                pca_sklearn=None,
                                                im_shape=None,
                                                indices=None)

            else:
                im_reshape = np.reshape(fake*mask, (im_shape[0], im_shape[1]*im_shape[2]))

                _, im_res = pca_psf_subtraction(images=im_reshape,
                                                angles=-1.*parang+self.m_extra_rot,
                                                pca_number=self.m_pca_number,
                                                pca_sklearn=sklearn_pca,
                                                im_shape=im_shape,
                                                indices=None)

            res_stack = combine_residuals(method=self.m_residuals, res_rot=im_res)

            self.m_res_out_port.append(res_stack, data_dim=3)

            chi_square = merit_function(residuals=res_stack[0, ],
                                        merit=self.m_merit,
                                        aperture=aperture,
                                        sigma=self.m_sigma)

            position = rotate_coordinates(center, (pos_y, pos_x), -self.m_extra_rot)

            res = np.asarray([position[1],
                              position[0],
                              sep_ang[0]*pixscale,
                              (sep_ang[1]-self.m_extra_rot) % 360.,
                              mag,
                              chi_square])

            self.m_flux_position_port.append(res, data_dim=2)

            return chi_square
Esempio n. 4
0
    def run(self):
        """
        Run method of the module. Shifts the reference PSF to the location of the fake planet
        with an additional correction for the parallactic angle and writes the stack with images
        with the injected planet signal.

        :return: None
        """

        self.m_image_out_port.del_all_data()
        self.m_image_out_port.del_all_attributes()

        parang = self.m_image_in_port.get_attribute("PARANG")
        pixscale = self.m_image_in_port.get_attribute("PIXSCALE")

        self.m_position = (self.m_position[0] / pixscale, self.m_position[1])

        psf, ndim_psf, ndim, frames = self._init()

        for j, _ in enumerate(frames[:-1]):
            progress(j, len(frames[:-1]), "Running FakePlanetModule...")

            images = np.copy(self.m_image_in_port[frames[j]:frames[j + 1]])
            angles = parang[frames[j]:frames[j + 1]]

            if ndim_psf == 3:
                psf = np.copy(images)

            im_fake = fake_planet(images,
                                  psf,
                                  angles,
                                  self.m_position,
                                  self.m_magnitude,
                                  self.m_psf_scaling,
                                  interpolation="spline")

            if ndim == 2:
                self.m_image_out_port.set_all(im_fake)
            elif ndim == 3:
                self.m_image_out_port.append(im_fake, data_dim=3)

        sys.stdout.write("Running FakePlanetModule... [DONE]\n")
        sys.stdout.flush()

        self.m_image_out_port.copy_attributes_from_input_port(
            self.m_image_in_port)

        self.m_image_out_port.add_history_information("FakePlanetModule",
                                                      "(sep, angle, mag) = " + "(" + \
                                                      "{0:.2f}".format(self.m_position[0]* \
                                                       pixscale)+", "+ \
                                                      "{0:.2f}".format(self.m_position[1])+", "+ \
                                                      "{0:.2f}".format(self.m_magnitude)+")")

        self.m_image_out_port.close_port()
Esempio n. 5
0
    def gaussian_noise(self,
                       images,
                       psf,
                       parang,
                       aperture):
        """
        Function to compute the (constant) variance for the likelihood function when the
        variance parameter is set to gaussian (see Mawet et al. 2014). The planet is first removed
        from the dataset with the values specified as *param* in the constructor of the instance.

        Parameters
        ----------
        images : numpy.ndarray
            Input images.
        psf : numpy.ndarray
            PSF template.
        parang : numpy.ndarray
            Parallactic angles (deg).
        aperture : dict
            Properties of the circular aperture. The radius is recommended to be larger than or
            equal to 0.5*lambda/D.

        Returns
        -------
        float
            Variance.
        """

        pixscale = self.m_image_in_port.get_attribute("PIXSCALE")

        fake = fake_planet(images=images,
                           psf=psf,
                           parang=parang,
                           position=(self.m_param[0]/pixscale, self.m_param[1]),
                           magnitude=self.m_param[2],
                           psf_scaling=self.m_psf_scaling)

        _, res_arr = pca_psf_subtraction(images=fake,
                                         angles=-1.*parang+self.m_extra_rot,
                                         pca_number=self.m_pca_number)

        stack = combine_residuals(method=self.m_residuals, res_rot=res_arr)

        _, noise, _, _ = false_alarm(image=stack[0, ],
                                     x_pos=aperture['pos_x'],
                                     y_pos=aperture['pos_y'],
                                     size=aperture['radius'],
                                     ignore=False)

        return noise**2
Esempio n. 6
0
        def _objective(arg):
            sys.stdout.write('.')
            sys.stdout.flush()

            pos_y = arg[0]
            pos_x = arg[1]
            mag = arg[2]

            sep = math.sqrt((pos_y - center[0])**2 + (pos_x - center[1])**2)
            ang = math.atan2(pos_y - center[0],
                             pos_x - center[1]) * 180. / math.pi - 90.

            fake = fake_planet(images=images,
                               psf=psf,
                               parang=parang,
                               position=(sep, ang),
                               magnitude=mag,
                               psf_scaling=self.m_psf_scaling)

            im_shape = (fake.shape[-2], fake.shape[-1])

            mask = create_mask(im_shape, [self.m_cent_size, self.m_edge_size])

            _, im_res = pca_psf_subtraction(images=fake * mask,
                                            angles=-1. * parang +
                                            self.m_extra_rot,
                                            pca_number=self.m_pca_number)

            stack = combine_residuals(method=self.m_residuals, res_rot=im_res)

            self.m_res_out_port.append(stack, data_dim=3)

            merit = merit_function(residuals=stack,
                                   function=self.m_merit,
                                   variance="poisson",
                                   aperture=self.m_aperture,
                                   sigma=self.m_sigma)

            position = rotate_coordinates(center, (pos_y, pos_x),
                                          -self.m_extra_rot)

            res = np.asarray((position[1], position[0], sep * pixscale,
                              (ang - self.m_extra_rot) % 360., mag, merit))

            self.m_flux_position_port.append(res, data_dim=2)

            return merit
Esempio n. 7
0
def contrast_limit(path_images, path_psf, noise, mask, parang, psf_scaling,
                   extra_rot, pca_number, threshold, aperture, residuals,
                   snr_inject, position):
    """
    Function for calculating the contrast limit at a specified position for a given sigma level or
    false positive fraction, both corrected for small sample statistics.

    Parameters
    ----------
    path_images : str
        System location of the stack of images (3D).
    path_psf : str
        System location of the PSF template for the fake planet (3D). Either a single image or a
        stack of images equal in size to science data.
    noise : numpy.ndarray
        Residuals of the PSF subtraction (3D) without injection of fake planets. Used to measure
        the noise level with a correction for small sample statistics.
    mask : numpy.ndarray
        Mask (2D).
    parang : numpy.ndarray
        Derotation angles (deg).
    psf_scaling : float
        Additional scaling factor of the planet flux (e.g., to correct for a neutral density
        filter). Should have a positive value.
    extra_rot : float
        Additional rotation angle of the images in clockwise direction (deg).
    pca_number : int
        Number of principal components used for the PSF subtraction.
    threshold : tuple(str, float)
        Detection threshold for the contrast curve, either in terms of "sigma" or the false
        positive fraction (FPF). The value is a tuple, for example provided as ("sigma", 5.) or
        ("fpf", 1e-6). Note that when sigma is fixed, the false positive fraction will change with
        separation. Also, sigma only corresponds to the standard deviation of a normal distribution
        at large separations (i.e., large number of samples).
    aperture : float
        Aperture radius (pix) for the calculation of the false positive fraction.
    residuals : str
        Method used for combining the residuals ("mean", "median", "weighted", or "clipped").
    position : tuple(float, float)
        The separation (pix) and position angle (deg) of the fake planet.
    snr_inject : float
        Signal-to-noise ratio of the injected planet signal that is used to measure the amount
        of self-subtraction.

    Returns
    -------
    NoneType
        None
    """

    images = np.load(path_images)
    psf = np.load(path_psf)

    if threshold[0] == "sigma":
        sigma = threshold[1]

        # Calculate the FPF for a given sigma level
        fpf = student_t(t_input=threshold,
                        radius=position[0],
                        size=aperture,
                        ignore=False)

    elif threshold[0] == "fpf":
        fpf = threshold[1]

        # Calculate the sigma level for a given FPF
        sigma = student_t(t_input=threshold,
                          radius=position[0],
                          size=aperture,
                          ignore=False)

    else:
        raise ValueError("Threshold type not recognized.")

    # Cartesian coordinates of the fake planet
    xy_fake = polar_to_cartesian(images, position[0], position[1] - extra_rot)

    # Determine the noise level
    _, t_noise, _, _ = false_alarm(image=noise[0, ],
                                   x_pos=xy_fake[0],
                                   y_pos=xy_fake[1],
                                   size=aperture,
                                   ignore=False)

    # Aperture properties
    im_center = center_subpixel(images)
    ap_dict = {
        'type': 'circular',
        'pos_x': im_center[1],
        'pos_y': im_center[0],
        'radius': aperture
    }

    # Measure the flux of the star
    phot_table = aperture_photometry(psf_scaling * psf[0, ],
                                     create_aperture(ap_dict),
                                     method='exact')
    star = phot_table['aperture_sum'][0]

    # Magnitude of the injected planet
    flux_in = snr_inject * t_noise
    mag = -2.5 * math.log10(flux_in / star)

    # Inject the fake planet
    fake = fake_planet(images=images,
                       psf=psf,
                       parang=parang,
                       position=(position[0], position[1]),
                       magnitude=mag,
                       psf_scaling=psf_scaling)

    # Run the PSF subtraction
    _, im_res = pca_psf_subtraction(images=fake * mask,
                                    angles=-1. * parang + extra_rot,
                                    pca_number=pca_number)

    # Stack the residuals
    im_res = combine_residuals(method=residuals, res_rot=im_res)

    # Measure the flux of the fake planet
    flux_out, _, _, _ = false_alarm(image=im_res[0, ],
                                    x_pos=xy_fake[0],
                                    y_pos=xy_fake[1],
                                    size=aperture,
                                    ignore=False)

    # Calculate the amount of self-subtraction
    attenuation = flux_out / flux_in

    # Calculate the detection limit
    contrast = sigma * t_noise / (attenuation * star)

    # The flux_out can be negative, for example if the aperture includes self-subtraction regions
    if contrast > 0.:
        contrast = -2.5 * math.log10(contrast)
    else:
        contrast = np.nan

    # Separation [pix], position antle [deg], contrast [mag], FPF
    return position[0], position[1], contrast, fpf
Esempio n. 8
0
def contrast_limit(
        path_images: str, path_psf: str, noise: np.ndarray, mask: np.ndarray,
        parang: np.ndarray, psf_scaling: float, extra_rot: float,
        pca_number: int, threshold: Tuple[str, float], aperture: float,
        residuals: str, snr_inject: float,
        position: Tuple[float, float]) -> Tuple[float, float, float, float]:
    """
    Function for calculating the contrast limit at a specified position for a given sigma level or
    false positive fraction, both corrected for small sample statistics.

    Parameters
    ----------
    path_images : str
        System location of the stack of images (3D).
    path_psf : str
        System location of the PSF template for the fake planet (3D). Either a single image or a
        stack of images equal in size to science data.
    noise : numpy.ndarray
        Residuals of the PSF subtraction (3D) without injection of fake planets. Used to measure
        the noise level with a correction for small sample statistics.
    mask : numpy.ndarray
        Mask (2D).
    parang : numpy.ndarray
        Derotation angles (deg).
    psf_scaling : float
        Additional scaling factor of the planet flux (e.g., to correct for a neutral density
        filter). Should have a positive value.
    extra_rot : float
        Additional rotation angle of the images in clockwise direction (deg).
    pca_number : int
        Number of principal components used for the PSF subtraction.
    threshold : tuple(str, float)
        Detection threshold for the contrast curve, either in terms of 'sigma' or the false
        positive fraction (FPF). The value is a tuple, for example provided as ('sigma', 5.) or
        ('fpf', 1e-6). Note that when sigma is fixed, the false positive fraction will change with
        separation. Also, sigma only corresponds to the standard deviation of a normal distribution
        at large separations (i.e., large number of samples).
    aperture : float
        Aperture radius (pix) for the calculation of the false positive fraction.
    residuals : str
        Method used for combining the residuals ('mean', 'median', 'weighted', or 'clipped').
    snr_inject : float
        Signal-to-noise ratio of the injected planet signal that is used to measure the amount
        of self-subtraction.
    position : tuple(float, float)
        The separation (pix) and position angle (deg) of the fake planet.

    Returns
    -------
    float
        Separation (pix).
    float
        Position angle (deg).
    float
        Contrast (mag).
    float
        False positive fraction.
    """

    images = np.load(path_images)
    psf = np.load(path_psf)

    # Cartesian coordinates of the fake planet
    yx_fake = polar_to_cartesian(images, position[0], position[1] - extra_rot)

    # Determine the noise level
    noise_apertures = compute_aperture_flux_elements(image=noise[0, ],
                                                     x_pos=yx_fake[1],
                                                     y_pos=yx_fake[0],
                                                     size=aperture,
                                                     ignore=False)

    t_noise = np.std(noise_apertures, ddof=1) * \
              math.sqrt(1 + 1 / (noise_apertures.shape[0]))

    # get sigma from fpf or fpf from sigma
    # Note that the number of degrees of freedom is given by nu = n-1 with n the number of samples.
    # See Section 3 of Mawet et al. (2014) for more details on the Student's t distribution.

    if threshold[0] == 'sigma':
        sigma = threshold[1]

        # Calculate the FPF for a given sigma level

        fpf = t.sf(sigma, noise_apertures.shape[0] - 1, loc=0., scale=1.)

    elif threshold[0] == 'fpf':
        fpf = threshold[1]

        # Calculate the sigma level for a given FPF
        sigma = t.isf(fpf, noise_apertures.shape[0] - 1, loc=0., scale=1.)

    else:
        raise ValueError('Threshold type not recognized.')

    # Aperture properties
    im_center = center_subpixel(images)

    # Measure the flux of the star
    ap_phot = CircularAperture((im_center[1], im_center[0]), aperture)
    phot_table = aperture_photometry(psf_scaling * psf[0, ],
                                     ap_phot,
                                     method='exact')
    star = phot_table['aperture_sum'][0]

    # Magnitude of the injected planet
    flux_in = snr_inject * t_noise
    mag = -2.5 * math.log10(flux_in / star)

    # Inject the fake planet
    fake = fake_planet(images=images,
                       psf=psf,
                       parang=parang,
                       position=(position[0], position[1]),
                       magnitude=mag,
                       psf_scaling=psf_scaling)

    # Run the PSF subtraction
    _, im_res = pca_psf_subtraction(images=fake * mask,
                                    angles=-1. * parang + extra_rot,
                                    pca_number=pca_number)

    # Stack the residuals
    im_res = combine_residuals(method=residuals, res_rot=im_res)
    flux_out_frame = im_res[0, ] - noise[0, ]

    # Measure the flux of the fake planet after PCA
    # the first element is the planet
    flux_out = compute_aperture_flux_elements(image=flux_out_frame,
                                              x_pos=yx_fake[1],
                                              y_pos=yx_fake[0],
                                              size=aperture,
                                              ignore=False)[0]

    # Calculate the amount of self-subtraction
    attenuation = flux_out / flux_in
    # the throughput can not be negative. However, this can happen due to numerical inaccuracies
    if attenuation < 0:
        attenuation = 0

    # Calculate the detection limit
    contrast = (sigma * t_noise + np.mean(noise_apertures)) / (attenuation *
                                                               star)

    # The flux_out can be negative, for example if the aperture includes self-subtraction regions
    if contrast > 0.:
        contrast = -2.5 * math.log10(contrast)
    else:
        contrast = np.nan

    # Separation [pix], position angle [deg], contrast [mag], FPF
    return position[0], position[1], contrast, fpf
Esempio n. 9
0
    def run(self) -> None:
        """
        Run method of the module. Shifts the PSF template to the location of the fake planet
        with an additional correction for the parallactic angle and an optional flux scaling.
        The stack of images with the injected planet signal is stored.

        Returns
        -------
        NoneType
            None
        """

        self.m_image_out_port.del_all_data()
        self.m_image_out_port.del_all_attributes()

        memory = self._m_config_port.get_attribute('MEMORY')
        parang = self.m_image_in_port.get_attribute('PARANG')
        pixscale = self.m_image_in_port.get_attribute('PIXSCALE')

        self.m_position = (self.m_position[0]/pixscale, self.m_position[1])

        im_shape = self.m_image_in_port.get_shape()
        psf_shape = self.m_psf_in_port.get_shape()

        if psf_shape[0] != 1 and psf_shape[0] != im_shape[0]:
            raise ValueError('The number of frames in psf_in_tag does not match with the number '
                             'of frames in image_in_tag. The DerotateAndStackModule can be '
                             'used to average the PSF frames (without derotating) before applying '
                             'the FakePlanetModule.')

        if psf_shape[-2:] != im_shape[-2:]:
            raise ValueError(f'The images in \'{self.m_image_in_port.tag}\' should have the same '
                             f'dimensions as the images images in \'{self.m_psf_in_port.tag}\'.')

        frames = memory_frames(memory, im_shape[0])

        start_time = time.time()
        for j, _ in enumerate(frames[:-1]):
            progress(j, len(frames[:-1]), 'Injecting artificial planets...', start_time)

            images = self.m_image_in_port[frames[j]:frames[j+1]]
            angles = parang[frames[j]:frames[j+1]]

            if psf_shape[0] == 1:
                psf = self.m_psf_in_port.get_all()
            else:
                psf = self.m_psf_in_port[frames[j]:frames[j+1]]

            im_fake = fake_planet(images=images,
                                  psf=psf,
                                  parang=angles,
                                  position=self.m_position,
                                  magnitude=self.m_magnitude,
                                  psf_scaling=self.m_psf_scaling,
                                  interpolation='spline')

            self.m_image_out_port.append(im_fake, data_dim=3)

        history = f'(sep, angle, mag) = ({self.m_position[0]*pixscale:.2f}, ' \
                  f'{self.m_position[1]:.2f}, {self.m_magnitude:.2f})'

        self.m_image_out_port.copy_attributes(self.m_image_in_port)
        self.m_image_out_port.add_history('FakePlanetModule', history)
        self.m_image_out_port.close_port()
Esempio n. 10
0
def paco_contrast_limit(path_images, path_psf, noise, parang, psf_rad,
                        psf_scaling, res_scaling, pixscale, extra_rot,
                        threshold, aperture, snr_inject, position, algorithm):
    """
    Function for calculating the contrast limit at a specified position for a given sigma level or
    false positive fraction, both corrected for small sample statistics.

    Parameters
    ----------
    path_images : str
        System location of the stack of images (3D).
    path_psf : str
        System location of the PSF template for the fake planet (3D). Either a single image or a
        stack of images equal in size to science data.
    noise : numpy.ndarray
        Residuals of the PSF subtraction (3D) without injection of fake planets. Used to measure
        the noise level with a correction for small sample statistics.
    parang : numpy.ndarray
        Derotation angles (deg).
    psf_scaling : float
        Additional scaling factor of the planet flux (e.g., to correct for a neutral density
        filter). Should have a positive value.
    extra_rot : float
        Additional rotation angle of the images in clockwise direction (deg).
    threshold : tuple(str, float)
        Detection threshold for the contrast curve, either in terms of "sigma" or the false
        positive fraction (FPF). The value is a tuple, for example provided as ("sigma", 5.) or
        ("fpf", 1e-6). Note that when sigma is fixed, the false positive fraction will change with
        separation. Also, sigma only corresponds to the standard deviation of a normal distribution
        at large separations (i.e., large number of samples).
    aperture : float
        Aperture radius (pix) for the calculation of the false positive fraction.
    position : tuple(float, float)
        The separation (pix) and position angle (deg) of the fake planet.
    snr_inject : float
        Signal-to-noise ratio of the injected planet signal that is used to measure the amount
        of self-subtraction.

    Returns
    -------
    NoneType
        None
    """
    images = np.load(path_images)
    psf = np.load(path_psf)

    if threshold[0] == "sigma":
        sigma = threshold[1]

        # Calculate the FPF for a given sigma level
        fpf = student_t(t_input=threshold,
                        radius=position[0],
                        size=aperture,
                        ignore=False)

    elif threshold[0] == "fpf":
        fpf = threshold[1]

        # Calculate the sigma level for a given FPF
        sigma = student_t(t_input=threshold,
                          radius=position[0],
                          size=aperture,
                          ignore=False)

    else:
        raise ValueError("Threshold type not recognized.")

    # Cartesian coordinates of the fake planet
    xy_fake = polar_to_cartesian(images, position[0], position[1] - extra_rot)

    # Determine the noise level
    _, t_noise, _, _ = false_alarm(image=noise,
                                   x_pos=xy_fake[0],
                                   y_pos=xy_fake[1],
                                   size=aperture,
                                   ignore=False)

    # Aperture properties
    im_center = center_subpixel(images)

    # Measure the flux of the star
    ap_phot = CircularAperture((im_center[1], im_center[0]), aperture)
    phot_table = aperture_photometry(psf_scaling * psf[0, ],
                                     ap_phot,
                                     method='exact')
    star = phot_table['aperture_sum'][0]

    # Magnitude of the injected planet
    flux_in = snr_inject * t_noise
    mag = -2.5 * math.log10(flux_in / star)

    # Inject the fake planet
    fake = fake_planet(images=images,
                       psf=psf,
                       parang=parang,
                       position=(position[0], position[1]),
                       magnitude=mag,
                       psf_scaling=psf_scaling)
    path_fake_planet = os.path.split(path_images)[0] = "/"
    np.save(path_fake_planet + "injected.npy", fake)
    # Run the PSF subtraction
    #_, im_res = pca_psf_subtraction(images=fake*mask,
    #                                angles=-1.*parang+extra_rot,
    #                                pca_number=pca_number)

    # Stack the residuals
    #im_res = combine_residuals(method=residuals, res_rot=im_res)

    # Measure the flux of the fake planet
    #flux_out, _, _, _ = false_alarm(image=im_res[0, ],
    #                                x_pos=xy_fake[0],
    #                                y_pos=xy_fake[1],
    #                                size=aperture,
    #                                ignore=False)
    # Setup PACO
    if algorithm == "fastpaco":
        fp = FastPACO(image_file=path_fake_planet + "injected.npy",
                      angles=parang,
                      psf=psf,
                      psf_rad=psf_rad,
                      px_scale=pixscale,
                      res_scale=res_scaling,
                      verbose=False)
    elif algorithm == "fullpaco":
        fp = FullPACO(image_file=path_fake_planet + "injected.npy",
                      angles=parang,
                      psf=psf,
                      psf_rad=psf_rad,
                      px_scale=pixscale,
                      res_scale=res_scaling,
                      verbose=False)

    # Run PACO
    # Restrict to 1 processor since this module is called from a child process
    a, b = fp.PACO(cpu=1)

    # Should do something with these?
    snr = b / np.sqrt(a)
    flux_residual = b / a
    flux_out, _, _, _ = false_alarm(image=flux_residual,
                                    x_pos=xy_fake[0],
                                    y_pos=xy_fake[1],
                                    size=aperture,
                                    ignore=False)

    # Iterative, unbiased flux estimation
    # This doesn't seem to give the correct results yet?
    #if self.m_flux_calc:
    #    phi0s = fp.thresholdDetection(snr,self.m_threshold)
    #    init = np.array([flux[int(phi0[0]),int(phi0[1])] for phi0 in phi0s])
    #    ests =  np.array(fp.fluxEstimate(phi0s,self.m_eps,init))

    # Calculate the amount of self-subtraction
    attenuation = flux_out / flux_in

    # Calculate the detection limit
    contrast = sigma * t_noise / (attenuation * star)

    # The flux_out can be negative, for example if the aperture includes self-subtraction regions
    if contrast > 0.:
        contrast = -2.5 * math.log10(contrast)
    else:
        contrast = np.nan

    # Separation [pix], position antle [deg], contrast [mag], FPF
    return (position[0], position[1], contrast, fpf)
Esempio n. 11
0
    def run(self):
        """
        Run method of the module. Shifts the PSF template to the location of the fake planet
        with an additional correction for the parallactic angle and an optional flux scaling.
        The stack of images with the injected planet signal is stored.

        Returns
        -------
        NoneType
            None
        """

        self.m_image_out_port.del_all_data()
        self.m_image_out_port.del_all_attributes()

        memory = self._m_config_port.get_attribute("MEMORY")
        parang = self.m_image_in_port.get_attribute("PARANG")
        pixscale = self.m_image_in_port.get_attribute("PIXSCALE")

        self.m_position = (self.m_position[0]/pixscale, self.m_position[1])

        im_shape = self.m_image_in_port.get_shape()
        psf_shape = self.m_psf_in_port.get_shape()

        if psf_shape[0] != 1 and psf_shape[0] != im_shape[0]:
            raise ValueError('The number of frames in psf_in_tag does not match with the number '
                             'of frames in image_in_tag. The DerotateAndStackModule can be '
                             'used to average the PSF frames (without derotating) before applying '
                             'the FakePlanetModule.')

        if psf_shape[-2:] != im_shape[-2:]:
            raise ValueError("The images in '"+self.m_image_in_port.tag+"' should have the same "
                             "dimensions as the images images in '"+self.m_psf_in_port.tag+"'.")

        frames = memory_frames(memory, im_shape[0])

        for j, _ in enumerate(frames[:-1]):
            progress(j, len(frames[:-1]), "Running FakePlanetModule...")

            images = self.m_image_in_port[frames[j]:frames[j+1]]
            angles = parang[frames[j]:frames[j+1]]

            if psf_shape[0] == 1:
                psf = self.m_psf_in_port.get_all()
            else:
                psf = self.m_psf_in_port[frames[j]:frames[j+1]]

            im_fake = fake_planet(images=images,
                                  psf=psf,
                                  parang=angles,
                                  position=self.m_position,
                                  magnitude=self.m_magnitude,
                                  psf_scaling=self.m_psf_scaling,
                                  interpolation="spline")

            if j == 0:
                self.m_image_out_port.set_all(im_fake)
            else:
                self.m_image_out_port.append(im_fake, data_dim=3)

        sys.stdout.write("Running FakePlanetModule... [DONE]\n")
        sys.stdout.flush()

        history = "(sep, angle, mag) = ("+"{0:.2f}".format(self.m_position[0]*pixscale)+", "+ \
                  "{0:.2f}".format(self.m_position[1])+", "+"{0:.2f}".format(self.m_magnitude)+")"

        self.m_image_out_port.copy_attributes(self.m_image_in_port)
        self.m_image_out_port.add_history("FakePlanetModule", history)
        self.m_image_out_port.close_port()