Utils#

Positions#

Util functions needed to estimate noise positions in residuals and raw data.

applefy.utils.positions.get_number_of_apertures(separation, psf_fwhm_radius)#

Estimates the number of available aperture or independent pixel positions for a given separation.

Parameters
  • separation (float) – the separation from the star [pixel]

  • psf_fwhm_radius (float) – Radius [pixel]. Aperture positions are placed such that at least two radii are between them.

Return type

int

Returns

The number of apertures at the given separation.

applefy.utils.positions.estimate_noise_positions(separation, center, psf_fwhm_radius, angle_offset=0.0)#

Calculation of aperture or independent pixel positions ordered on a ring around the center.

Parameters
  • separation (float) – Separation of the ring from the center [pixel]

  • center (Tuple[float, float]) – Position of the center [tuple - (x, y) pixel]

  • psf_fwhm_radius (float) – Radius [pixel]. positions are placed such that at least two radii are between them.

  • angle_offset (float) – offset angle [rad] which is applied to rotate the aperture positions around the center.

Return type

List[Tuple[float, float, float, float]]

Returns

A list of tuples (x_pos, y_pos, separation, angle) containing the positions of the apertures

applefy.utils.positions.estimate_reference_positions(planet_position, center, psf_fwhm_radius, angle_offset=0.0, safety_margin=0.0)#

Calculation of aperture positions or independent pixels ordered on a ring around the center. The separation of the ring is given by the distance of the planet_position to the center. Apertures which are closer than safety_margin to the planet are ignored.

Parameters
  • planet_position (Tuple[float, float]) – The position of the planet. Is used to determine the separation and exclusion region. [pixel]

  • center (Tuple[float, float]) – Position of the center [pixel]

  • psf_fwhm_radius (float) – Radius [pixel]. positions are placed such that at least two radii are between them.

  • angle_offset (float) – offset angle [rad] which is applied to rotate the aperture positions around the center.

  • safety_margin (float) – separation from the planet_position in which apertures are ignored.

Return type

List[Tuple[float, float, float, float]]

Returns

A list of tuples (x_pos, y_pos, separation, angle) containing the positions of the apertures

applefy.utils.positions.center_subpixel(image)#

Code copied from PynPoint.

Function to get the precise position of the image center. The center of the pixel in the bottom left corner of the image is defined as (0, 0), so the bottom left corner of the image is located at (-0.5, -0.5).

Parameters

image (ndarray) – np.ndarray Input image (2D or 3D).

Return type

Tuple[float, float]

Returns

Subpixel position (y, x) of the image center.

Photometry#

All util functions needed to estimate flux and do analysis with apertures and pixel values.

applefy.utils.photometry.flux_ratio2mag(flux_ratios)#

Convert a contrast given as a flux ratio to magnitudes.

Parameters

flux_ratios (Union[float, ndarray]) – The contrast as a flux ratio; either as a single float or as a numpy array of floats.

Return type

Union[float, ndarray]

Returns

The contrast(s) in magnitudes.

applefy.utils.photometry.mag2flux_ratio(magnitudes)#

Convert a contrast in magnitudes back to a flux ratio.

Parameters

magnitudes (Union[float, ndarray]) – The contrast in magnitudes; either as a single float or as a numpy array of floats.

Return type

Union[float, ndarray]

Returns

The contrast(s) as a flux ratio.

class applefy.utils.photometry.AperturePhotometryMode(flux_mode, psf_fwhm_radius=None, search_area=None)#

Bases: object

A capsule to manage the parameters of how photometry is calculated on residuals frames. The function is a wrapper of the parameters needed by the function get_flux() which is the foundation of many other functions.

__init__(flux_mode, psf_fwhm_radius=None, search_area=None)#

Constructor of the class. Takes the parameters needed by get_flux() and checks them for completeness.

Parameters
  • flux_mode (str) –

    The mode how photometry is measured. 5 different modes are supported:

    1. “AS” (Aperture sum) - The aperture sum around the given position inside one psf_fwhm_radius is calculated. Raises an error if psf_fwhm_radius is not given.

    2. “ASS” (Aperture sum + search) - The aperture sum within a radius of psf_fwhm_radius is calculated. The function searches for the highest flux within one search_area. Raises an error if psf_fwhm_radius or search_area are not given.

    3. “P” (Pixel) - The flux at the given pixel is calculated. Interpolation is used to get sub-pixel values. P is equivalent to “AS” with an aperture diameter of one pixel (i.e. Circular Aperture).

    4. “F” (Fit) - A 2D gaussian is fit at the given position. The function returns the same as “P” but based on the fit.

    5. “FS” (Fit + search) - A 2D gaussian is fit around the given position within one search_area. The function returns the same as “P” but based on the fit.

    6. “PG” (Pixel on Grid) - Returns value of the pixel with the closest position. Not compatible with mode “P” since the pixel grid is not circular. The mode “PG” should only be used to test temporal similarities.

  • psf_fwhm_radius (Optional[float]) – Needed for modes “AS” and “ASS”. Gives the aperture radius for the circular aperture used to calculate the summed flux. [pixel]

  • search_area (Optional[float]) – Needed for modes “ASS” and “FS”. Gives the search are which is considered to find the highest flux. [pixel]

check_compatible(other_aperture_mode)#

Check if the mode is compatible with a second given mode. Returns False if the modes are not compatible.

Parameters

other_aperture_mode (AperturePhotometryMode) – A second instance of AperturePhotometryMode.

Return type

bool

Returns

Returns False if the modes are not compatible, True if they are.

applefy.utils.photometry.get_flux(frame, position, photometry_mode)#

Function to estimate the flux at / or around a given position in the frame.

Parameters
  • frame (ndarray) – A 2D numpy array of shape (width, height) containing the data on which to run the photometry.

  • position (Tuple[float, float]) – A tuple (x, y) specifying the position at which we estimate the photometry.

  • photometry_mode (AperturePhotometryMode) – An instance of AperturePhotometryMode which defines how the flux is measured at the given position.

Return type

Tuple[Tuple[float, float], float]

Returns

A tuple with ((final_pos_x, final_pos_y), estimated_flux). final_pos contain the position of maximum flux in case the photometry_mode uses search.

class applefy.utils.photometry.IterNoise(residual, separation, psf_fwhm_radius, num_rot_iter, photometry_mode, max_rotation)#

Bases: ABC

Abstract interface for IterNoiseBySeparation() and IterNoiseForPlanet().

__init__(residual, separation, psf_fwhm_radius, num_rot_iter, photometry_mode, max_rotation)#

Constructor of IterNoise.

Parameters
  • residual (ndarray) – A 2D numpy array of shape (width, height) containing the data on which to run the photometry estimation.

  • separation (float) – Separation from the center [pixel].

  • psf_fwhm_radius (float) – The separation radius between noise elements [pixel].

  • num_rot_iter (int) – Number of tests performed with different positions of the noise values. See Figure 10 for more information.

  • photometry_mode (AperturePhotometryMode) – An instance of AperturePhotometryMode which defines how the flux is measured at the calculated position.

  • max_rotation (Optional[float]) – The maximum amount of rotation considered (deg). If None the maximum amount of rotation is computed based on the separation.

__iter__()#

Allows to iterate over different noise positions and extract their flux.

Return type

List[float]

Returns

A list of flux values extracted at the current positions.

class applefy.utils.photometry.IterNoiseBySeparation(residual, separation, psf_fwhm_radius, num_rot_iter, photometry_mode, max_rotation=360)#

Bases: IterNoise

An iterator that allows to sample noise photometry for different reference positions (angle_offsets). This is needed to average out the effect of rotation on the contrast. See Figure 10 for more information.

__init__(residual, separation, psf_fwhm_radius, num_rot_iter, photometry_mode, max_rotation=360)#

Constructor of the IterNoiseBySeparation.

Parameters
  • residual (ndarray) – A 2D numpy array of shape (width, height) containing the data on which to run the photometry estimation.

  • separation (float) – Separation from the center [pixel].

  • psf_fwhm_radius (float) – The separation radius between noise elements [pixel].

  • num_rot_iter (int) – Number of tests performed with different positions of the noise values.

  • photometry_mode (AperturePhotometryMode) – An instance of AperturePhotometryMode which defines how the flux is measured at the calculated position.

  • max_rotation (float) – The maximum amount of rotation considered (deg). If None the maximum amount of rotation is computed based on the separation.

class applefy.utils.photometry.IterNoiseForPlanet(residual, planet_position, safety_margin, psf_fwhm_radius, num_rot_iter, photometry_mode, max_rotation=None)#

Bases: IterNoise

An iterator that allows to sample noise photometry for different reference positions relative to a given planet position. This is needed to average out the effect of rotation on the detection uncertainty. See Figure 10 for more information.

__init__(residual, planet_position, safety_margin, psf_fwhm_radius, num_rot_iter, photometry_mode, max_rotation=None)#

Constructor of the IterNoiseForPlanet

Parameters
  • residual (ndarray) – A 2D numpy array of shape (width, height) containing the data on which to run the photometry estimation.

  • planet_position (Tuple[float, float]) – The position of the planet. Is used to determine the separation and exclusion region. [pixel]

  • safety_margin (float) – separation from the planet_position in which apertures are ignored. If None positions within two psf_fwhm_radius are ignored

  • psf_fwhm_radius (float) – The separation radius between noise elements. [pixel]

  • num_rot_iter (int) – Number of tests performed with different positions of the noise values.

  • photometry_mode (AperturePhotometryMode) – An instance of AperturePhotometryMode which defines how the flux is measured at the calculated position.

  • max_rotation (Optional[float]) – The maximum amount of rotation considered (deg). If None the maximum amount of rotation is computed based on the separation.

applefy.utils.photometry.estimate_stellar_flux(psf_template, dit_science, dit_psf_template, photometry_mode, scaling_factor=1.0)#

Function to estimate the normalized flux of the star given an unsaturated PSF image.

Parameters
  • psf_template (ndarray) – 2D array of the unsaturated PSF

  • dit_science (float) – Integration time of the science frames

  • dit_psf_template (float) – Integration time of unsaturated PSF

  • scaling_factor (float) – A scaling factor to account for ND filters.

  • photometry_mode (AperturePhotometryMode) – An instance of AperturePhotometryMode which defines how the stellar flux is measured.

Return type

float

Returns

The stellar flux

File Handling#

Simple helper functions to handle files.

applefy.utils.file_handling.read_apples_with_apples_root()#

A simple function which reads in the APPLES_ROOT_DIR specified by the user. This function is needed to reproduce the results of the Apples with Apples paper. Raises an error if the directory does not exist.

Return type

str

Returns

The path to the root directory

applefy.utils.file_handling.create_checkpoint_folders(checkpoint_dir)#

This function create the classical checkpoint folder structure as used by Contrast(). It creates three sub-folders. configs_cgrid, residuals, scratch. Returns None if checkpoint_dir is None.

Parameters

checkpoint_dir (Union[str, Path]) – The root directory in which the sub-folders are created.

Return type

Optional[Tuple[Path, Path, Path]]

Returns

  1. Path to the configs_cgrid folder.

  2. Path to the residuals folder.

  3. Path to the scratch folder.

applefy.utils.file_handling.search_for_config_and_residual_files(config_dir, method_dir)#

Searches for tuples of existing contrast grid config files and corresponding residuals. Raises an Error if the .json files and residual files in config_dir and method_dir do not match.

Parameters
  • config_dir (Union[str, Path]) – Directory where the contrast grid config files are stored.

  • method_dir (Path) – Directory where the residuals are stored.

Return type

List[Tuple[str, str]]

Returns

A list with paired paths (config path, residual path)

applefy.utils.file_handling.collect_all_contrast_grid_configs(contrast_grid_configs)#

Simple function which looks for all auto generated contrast grid config files in one directory.

Parameters

contrast_grid_configs (str) – The directory which contains the config files.

Return type

List[Tuple[str, str]]

Returns

A list of tuples (job_id, file path)

applefy.utils.file_handling.save_experiment_configs(experimental_setups, experiment_config_dir, overwrite=False)#

Saves all contrast grid config files in experimental_setups as .json files into the experiment_config_dir. Overwrites existing files is requested.

Parameters
  • experimental_setups (Dict[str, Dict]) – The contrast grid config files as created by generate_fake_planet_experiments()

  • experiment_config_dir (Path) – The directory where the .json files are saved.

  • overwrite (bool) – Whether to overwrite existing config files.

Return type

None

applefy.utils.file_handling.read_fake_planet_results(result_files)#

Read all contrast grid config files and .fits residuals as listed in result_files.

Parameters

result_files (List[Tuple[str, str]]) – A list of tuples (path to config file, path to residual)

Return type

List[Tuple[dict, ndarray]]

Returns

The load results as a list of

(config, residual)

applefy.utils.file_handling.cut_around_center(psf_template, science_data, cut_off_psf, cut_off_data)#

Function which cuts the psf_template and science_data around the center of the image. Can be useful to reduce the dimensionality of the data in order to save time during the calculation of contrast grids and contrast curves.

Parameters
  • psf_template (array) – 2D numpy array with the pst template.

  • science_data (array) – 2D numpy array with the science data. Shape (time, x, y)

  • cut_off_psf (int) – The number of pixel to be cut off on each side of the pst template.

  • cut_off_data (int) – The number of pixel to be cut off on each side of the science data.

Return type

Tuple[ndarray, ndarray]

Returns

  1. The cut science data.

  2. The cut pst template.

applefy.utils.file_handling.load_adi_data(hdf5_dataset, data_tag, psf_template_tag, para_tag='PARANG')#

Loads ADI data stored as a hdf5 file. This function is needed to read the data and reproduce the results of the Apples with Apples paper.

Parameters
  • hdf5_dataset (str) – The path to the hdf5 file.

  • data_tag (str) – Tag of the science data in the hdf5 database.

  • psf_template_tag (str) – Tag of the PSF template in the hdf5 database.

  • para_tag – Tag of the parallactic angles in the hdf5 database.

Return type

Tuple[ndarray, ndarray, ndarray]

Returns

  1. The science data as a 3d numpy array.

  2. The parallactic angles as a 1d numpy array

  3. The PSF template as a 3d numpy array.

applefy.utils.file_handling.save_as_fits(data, file_name)#

Saves data as .fits file.

Parameters
  • data (ndarray) – The data to be saved.

  • file_name (str) – The filename of the fits file.

Return type

None

applefy.utils.file_handling.open_fits(file_name)#

Opens a fits file as a numpy array.

Parameters

file_name – Path to the fits file.

Returns

Load data as numpy array.

Fake Planets#

Functions needed to insert and manage the positions of fake planets. These utils are needed to calculate a contrast grid das well as contrast curves.

applefy.utils.fake_planets.calculate_fake_planet_positions(test_img, psf_fwhm_radius, num_planets=6, separations=None)#

Function which estimates the positions for fake planets to be inserted during the computation of a contrast grid.

Parameters
  • test_img (ndarray) – A 2D test image needed to estimate the size and center of the raw data.

  • psf_fwhm_radius (float) – The FWHM (radius) of the stellar PSF. It is needed to determine the spacing such that noise values are approximately independent.

  • num_planets (int) – The number of planets to be inserted. Has to be between 1 (minimum) and 6 (maximum). More planets result in more accurate results but also longer computation time.

  • separations (Optional[ndarray]) – Separations at which fake planets are inserted [pixel]. By default, (If set to None) separations are selected in steps of 1 FWHM form the central star to the edge of the image.

Return type

Dict[int, List[Tuple[int, int, float, float]]]

Returns

A dict which maps all separations (pixel) to a list of planet positions given as (x_pos, y_pos, separation, angle)

applefy.utils.fake_planets.generate_fake_planet_experiments(flux_ratios, planet_positions)#

Function which creates config files for the contrast grid. Each file corresponds to one experiment / data reduction. The experiment with idx 0000 is the experiment with no fake planets.

Parameters
  • flux_ratios (List[float]) – A list of the planet-to-star flux_ratios used for the fake planets. If you want to calculate a simple contrast curve the list should contain a single value smaller than the expected detection limit. For the computation of a contrast grid several flux_ratios are needed.

  • planet_positions (Dict[int, List[Tuple[int, int, float, float]]]) – The planet positions as given by calculate_fake_planet_positions()

Return type

Dict[str, dict]

Returns

List of config files as dicts.

applefy.utils.fake_planets.sort_fake_planet_results(results)#

Function needed to sort tuples of residuals with associated config files.

Parameters

results (List[Tuple[Dict[str, Any], ndarray]]) –

List which contains tuples of config files (as dict) and the corresponding residuals.

(config file, residual)

Return type

Tuple[ndarray, Dict[int, List[Tuple[ndarray, List[float]]]], DataFrame]

Returns

  1. fp_residual - residual without any fake planets as 2D numpy array.

  2. planet_dict - A dictionary with keys = Experiment ID. For every ID a list is given which contains tuples of the residual and the position of the corresponding fake planet. E.g.:

    planet_dict["0001"] = [
        (res_planet_a, pos_planet_a),
        (res_planet_b, pos_planet_b),
        (res_planet_c, pos_planet_c),
        (res_planet_d, pos_planet_d),
        (res_planet_e, pos_planet_e),
        (res_planet_f, pos_planet_f)]
    

3. idx_table - Pandas table which links separation and flux_ratio to its experiment ID used by planet_dict.

applefy.utils.fake_planets.add_fake_planets(input_stack, psf_template, parang, dit_science, dit_psf_template, experiment_config, scaling_factor=1.0)#

Function which adds fake planets to an ADI data set based on a contrast grid config file.

Parameters
  • input_stack (array) – 3D numpy input stack (time, x, y) before normalization. Temporal-binning has to be done by mean not sum!

  • psf_template (array) – 2D numpy array of the unsaturated PSF used to create the fake planets. The template has to be in accordance to the integration time used for it. No normalization!

  • parang (array) – Parallactic angles as a 1D numpy array (rad)

  • dit_science (float) – Integration time of the science frames.

  • dit_psf_template (float) – Integration time of the psf_template.

  • experiment_config (Dict[str, Any]) – Configuration dict containing the information about where and how to add the fake planet.

  • scaling_factor (float) – A scaling factor to account for e.g. ND filters.

Return type

ndarray

Returns

The input_stack with the added fake planet (3D numpy array).

applefy.utils.fake_planets.merge_fake_planet_residuals(planet_dict, idx_table)#

Function needed to merge residual frames collected with sort_results into one numpy array with dimensions:

(num_separations, num_flux_ratios, num_planets, x, y)

Parameters
  • planet_dict (Dict[int, List[Tuple[ndarray, List[float]]]]) –

    A dictionary with keys = Experiment ID. For every ID a list is given which contains tuples of the residual and the position of the corresponding fake planet. E.g.:

    planet_dict["0001"] = [
        (res_planet_a, pos_planet_a),
        (res_planet_b, pos_planet_b),
        (res_planet_c, pos_planet_c),
        (res_planet_d, pos_planet_d),
        (res_planet_e, pos_planet_e),
        (res_planet_f, pos_planet_f)]
    

  • idx_table (DataFrame) – Pandas table which links separation and flux_ratio to its experiment ID as used by planet_dict.

Return type

ndarray

Returns

The merged residuals as one np.array.

Throughput#

Functions to compute throughput.

applefy.utils.throughput.compute_throughput_table(planet_dict, fp_residual, idx_table, stellar_flux, photometry_mode_planet)#

Computes the throughput for a series of experiments as generated by function sort_results.

Parameters
  • planet_dict (Dict[int, List[Tuple[ndarray, List[float]]]]) –

    A dictionary with keys = Experiment ID. For every ID a list is given which contains tuples of the residual and the position of the corresponding fake planet. E.g.:

    planet_dict["0001"] = [
        (res_planet_a, pos_planet_a),
        (res_planet_b, pos_planet_b),
        (res_planet_c, pos_planet_c),
        (res_planet_d, pos_planet_d),
        (res_planet_e, pos_planet_e),
        (res_planet_f, pos_planet_f)]
    

  • fp_residual (ndarray) – A 2D numpy array of shape (width, height) containing the data on which to run the noise statistics. This is usually the residual without fake planets.

  • idx_table (DataFrame) – Pandas table which links separation and flux_ratio to its experiment ID as used by planet_dict.

  • stellar_flux (float) – The stellar flux measured with estimate_stellar_flux(). The mode used to estimate the stellar_flux has to be compatible with the photometry_mode_noise used here.

  • photometry_mode_planet (AperturePhotometryMode) – An instance of AperturePhotometryMode which defines how the flux is measured at the planet positions.

Return type

Tuple[Dict[str, List[float]], DataFrame]

Returns

1. throughput_dict - A dictionary with keys = Experiment ID. For every ID a list is given which contains the throughput for every residual.

2. throughput_table - Pandas table which contains the median throughput as a function of separation and inserted flux_ratio

Contrast Curves#

Util functions needed to compute contrast curves. The recommended way to compute contrast curves is to use the class Contrast() and not the util functions.

applefy.utils.contrast_curve.compute_contrast_curve(throughput_list, stellar_flux, fp_residual, confidence_level_fpf, statistical_test, psf_fwhm_radius, photometry_mode_noise, num_rot_iter=100)#

Computes an analytic contrast curve given a confidence level and a statistical test. Analytic contrast curves are only applicable if used with linear post-processing techniques such as PCA. They can further lead to inaccurate results close to the star. For more advanced post-processing techniques use a contrast grid instead.

Supports all statistical tests implemented in Statistics.

Parameters
  • throughput_list (DataFrame) – 1D pandas array of throughput values for every separation. (floats in range [0, 1]).

  • stellar_flux (float) – The stellar flux measured with estimate_stellar_flux(). The mode used to estimate the stellar_flux has to be compatible with the photometry_mode_noise used here.

  • fp_residual (ndarray) – A 2D numpy array of shape (width, height) containing the data on which to run the noise statistics. This is usually the residual without fake planets.

  • confidence_level_fpf (float) – The confidence level associated with the contrast curve as false-positive fraction (FPF). Can also be a list of fpf values. In case a list is given the number of fpf values has to match the number of values in the throughput_list.

  • statistical_test (TestInterface) – The test used to constrain the planet flux needed to be counted as a detection. For the classical TTest (Gaussian noise) use an instance of TTest(). For Laplacian noise use LaplaceBootstrapTest().

  • psf_fwhm_radius (float) – The FWHM (radius) of the PSF. It is needed to sample independent noise values i.e. it determines the spacing between the noise observations which are extracted from the fp_residual.

  • photometry_mode_noise (AperturePhotometryMode) – An instance of AperturePhotometryMode which defines how the noise photometry is measured.

  • num_rot_iter (int) – Number of tests performed with different positions of the noise values. See Figure 02 for more information.

Return type

Tuple[ndarray, ndarray, DataFrame]

Returns

1. median_contrast_curve - The median of all num_rot_iter contrast curves.

2. mad_contrast_curve_error - The median absolute deviation of all num_rot_iter contrast curves.

3. contrast_curves - A pandas DataFrame containing all individual num_rot_iter contrast curves calculated.

Contrast Grids#

Util functions needed to compute contrast grids. The recommended way to compute contrast grids is to use the class Contrast() and not the util functions.

applefy.utils.contrast_grid.compute_contrast_grid(planet_dict, idx_table, statistical_test, psf_fwhm_radius, photometry_mode_planet, photometry_mode_noise, num_cores=1, num_rot_iter=20, safety_margin=1.0)#

Computes a contrast grid for a given set of fake planet residuals. Supports all statistical tests implemented in Statistics. Compared to the function compute_contrast_curve() this function is applicable not only to residuals of linear PSF-subtraction methods like PCA, but in general. This allows to compare results of different methods.

Parameters
  • planet_dict (Dict[int, List[Tuple[ndarray, List[float]]]]) –

    A dictionary with keys = Experiment ID. For every ID a list is given which contains tuples of the residual and the position of the corresponding fake planet. E.g.:

    planet_dict["0001"] = [
        (res_planet_a, pos_planet_a),
        (res_planet_b, pos_planet_b),
        (res_planet_c, pos_planet_c),
        (res_planet_d, pos_planet_d),
        (res_planet_e, pos_planet_e),
        (res_planet_f, pos_planet_f)]
    

  • idx_table (DataFrame) – Pandas table which links separation and flux_ratio to its experiment ID as used by planet_dict.

  • statistical_test (TestInterface) – The test used to constrain the planet flux needed to be counted as a detection. For the classical TTest (Gaussian noise) use an instance of TTest(). For Laplacian noise use LaplaceBootstrapTest().

  • psf_fwhm_radius (float) – The FWHM (radius) of the PSF. It is needed to sample independent noise values i.e. it determines the spacing between the noise observations which are extracted from the fp_residual.

  • photometry_mode_planet (AperturePhotometryMode) – An instance of AperturePhotometryMode which defines how the flux is measured at the planet positions.

  • photometry_mode_noise (AperturePhotometryMode) – An instance of AperturePhotometryMode which defines how the noise photometry is measured.

  • num_cores (int) – Number of CPU cores used for a parallel computation of the grid values.

  • num_rot_iter (int) –

    Number of tests performed with different positions of the noise values. See Figure 02 for more information.

  • safety_margin (float) – Area around the planet [pixel] which is excluded from the noise. This can be useful in case the planet has negative wings.

Return type

DataFrame

Returns

The contrast grid containing p-values / fpf values as a pandas DataFrame.

applefy.utils.contrast_grid.compute_contrast_from_grid(contrast_grid_fpf, fpf_threshold)#

This function allows to obtain a contrast curve from a contrast grid by interpolation and thresholding. Contains np.inf values in case the contrast can not be reached within the contrast grid.

Parameters
  • contrast_grid_fpf (DataFrame) – The contrast grid as 2D pandas Table as returned by compute_contrast_grid(). The flux ratios have to be in fraction not mag!

  • fpf_threshold (float) – The desired detection threshold as fpf.

Return type

DataFrame

Returns

A 1D pandas array containing the contrast curve.

Monte Carlo Simulations#

Tools used to run the Monte Carlo simulations of the Apples with Apples paper. This code is only needed to reproduce the results of the paper.

applefy.utils.mc_simulations.draw_noise(distribution, num_draws, num_noise_observations, loc_noise, scale_noise)#

Simple function to draw noise for the MC simulation.

Parameters
  • distribution (str) – Type of the noise: gaussian / laplace

  • num_draws (int) – Number of noise samples.

  • num_noise_observations (int) – sample size i.e. number of noise values at a given separation from the star.

  • loc_noise (float) – The location of the noise i.e. the center of the pdf.

  • scale_noise (float) – The width of the distribution. In case of gaussian noise this is the std. For the laplace this is b.

Return type

ndarray

Returns

numpy array with noise. Shape (num_draws, num_noise_observations)

applefy.utils.mc_simulations.draw_mp(shared_memory_parameters, num_sub_draws, distribution, num_noise_observations, idx, loc_noise, scale_noise)#

Function to sample noise using multiprocessing and shared_memory.

Parameters
  • shared_memory_parameters (Tuple[str, Tuple[int]]) – tuple containing: (the name of the shared memory, the shared memory size)

  • num_sub_draws (int) – number of samples to draw.

  • distribution (str) – Type of the noise: gaussian / laplace.

  • num_noise_observations (int) – Sample size i.e. number of noise values at a given separation.

  • idx (int) – index of the multiprocessing experiment. Needed to tell the subprocess where to store the results within the shared memory.

  • loc_noise (float) – The location of the noise i.e. the center of the pdf.

  • scale_noise (float) – The width of the distribution. In case of gaussian noise this is the std. For the laplace this is b.

Return type

None

applefy.utils.mc_simulations.draw_mc_sample(num_noise_observations, num_draws=1, noise_distribution='gaussian', loc_noise=0.0, scale_noise=1.0, num_cores=1)#

Function for efficient noise sampling in the MC simulation. If more than 10e6 noise values are requested multiprocessing will be used.

Parameters
  • num_noise_observations (int) – sample size i.e. number of noise values at a given separation

  • num_draws (int) – Number of monte carlo experiments to run.

  • noise_distribution (str) – type of the noise: gaussian / laplace

  • loc_noise (float) – The location of the noise i.e. the center of the pdf.

  • scale_noise (float) – The width of the distribution. In case of gaussian noise this is the std. For the laplace this is b.

  • num_cores (int) – number of CPU cores to use i.e. parallel processes.

Return type

Tuple[ndarray, ndarray, Optional[SharedMemory]]

Returns

  1. planet_observation - np.array containing (num_draws) noise values

2. noise_observation - np.array containing (num_draws, num_noise_observations) noise values

3. shared_np_array- if num_draws greater 10e6 instance of the shared memory used during multiprocessing. Else None.