The Code (API)

S1_detector_processing

S1_detector_processing.ramp_fitting

class eureka.S1_detector_processing.ramp_fitting.Eureka_RampFitStep(name=None, parent=None, config_file=None, _validate_kwds=True, **kws)[source]

Bases: JwstStep

This step is an alternative to the pipeline rampfitstep to determine the count rate for each pixel.

Attributes
class_alias
correction_pars
input_dir
log_records

Retrieve logs from the most recent run of this step.

make_output_path

Return function that creates the output path

name_format

Methods

__call__(*args)

Run handles the generic setup and teardown that happens with the running of each step.

build_config(input, **kwargs)

Build the ConfigObj to initialize a Step

call(*args, **kwargs)

Creates and runs a new instance of the class.

closeout([to_close, to_del])

Close out step processing

default_output_file([input_file])

Create a default filename based on the input name

default_suffix()

Return a default suffix based on the step

export_config(filename[, include_metadata])

Export this step's parameters to an ASDF config file.

finalize_config(config[, name, config_file, ...])

Load default config, merge with config_file if present, then validate.

finalize_result(result, reference_files_used)

Hook that allows subclasses to set mission-specific metadata on each step result before that result is saved.

from_cmdline(args)

Create a step from a configuration file.

from_config_file(config_file[, parent, name])

Create a step from a configuration file.

from_config_section(config[, parent, name, ...])

Create a step from a configuration file fragment.

get_config_from_reference(dataset[, ...])

Retrieve step parameters from reference database

get_config_reftype()

Get the CRDS reftype for this step's config reference.

get_pars([full_spec])

Retrieve the configuration parameters of a step

get_ref_override(reference_file_type)

Determine and return any override for reference_file_type.

get_reference_file(input_file, ...)

Get a reference file from CRDS.

load_as_level2_asn(obj)

Load object as an association

load_as_level3_asn(obj)

Load object as an association

make_input_path(file_path)

Create an input path for a given file path

open_model(init, **kwargs)

Open a datamodel

prefetch(*args)

Prefetch reference files, nominally called when self.prefetch_references is True.

process(input)

Process a Stage 0 *_uncal.fits file to Stage 1 *_rate.fits and *_rateints.fits files.

record_step_status(datamodel, cal_step[, ...])

Record whether or not a step completed in meta.cal_step

reference_uri_to_cache_path(reference_uri, ...)

Convert an abstract CRDS reference URI to an absolute file path in the CRDS cache.

remove_suffix(name)

Remove a known Step filename suffix from a filename (if present).

resolve_file_name(file_name)

Resolve a file name expressed relative to this Step's configuration file.

run(*args)

Run handles the generic setup and teardown that happens with the running of each step.

save_model(model[, suffix, idx, ...])

Saves the given model using the step/pipeline's naming scheme

search_attr(attribute[, default, parent_first])

Return first non-None attribute in step heirarchy

set_primary_input(obj[, exclusive])

Sets the name of the master input file and input directory.

update_pars(parameters)

Update step parameters

load_spec_file

merge_config

print_configspec

algorithm = 'differenced'
maximum_cores = 1
process(input)[source]

Process a Stage 0 *_uncal.fits file to Stage 1 *_rate.fits and *_rateints.fits files.

Steps taken to perform this processing can follow the default JWST pipeline, or alternative methods.

Parameters
inputstr, tuple, ~astropy.io.fits.HDUList, ndarray, dict, None
  • None: Create a default data model with no shape.

  • tuple: Shape of the data array. Initialize with empty data array with shape specified by the.

  • file path: Initialize from the given file (FITS or ASDF)

  • readable file object: Initialize from the given file object

  • ~astropy.io.fits.HDUList: Initialize from the given ~astropy.io.fits.HDUList.

  • A numpy array: Used to initialize the data array

Returns
out_modeljwst.datamodels.ImageModel

The output ImageModel to be returned from the ramp fit step.

int_modeljwst.datamodels.CubeModel

The output CubeModel to be returned from the ramp fit step.

Notes

History:

  • October 2021 Aarynn Carter and Eva-Maria Ahrer

    Initial version

  • February 2022 Aarynn Carter and Eva-Maria Ahrer

    Updated for JWST version 1.3.3, code restructure

reference_file_types = ['readnoise', 'gain']
spec = "\n        int_name = string(default='')\n        save_opt = boolean(default=False) # Save optional output\n        opt_name = string(default='')\n        maximum_cores = option('none', 'quarter', 'half', 'all', default='none') # max number of processes to create\n    "
weighting = 'optimal'

S1_detector_processing.s1_process

class eureka.S1_detector_processing.s1_process.EurekaS1Pipeline(*args, **kwargs)[source]

Bases: Detector1Pipeline

A wrapper class for the jwst.pipeline.calwebb_detector1.Detector1Pipeline

This wrapper class allows non-standard changes to Stage 1 for Eureka!.

Notes

History:

  • October 2021 Aarynn Carter / Eva-Maria Ahrer

    Initial version

  • February 2022 Aarynn Carter / Eva-Maria Ahrer

    Updated for JWST version 1.3.3, code restructure

Attributes
correction_pars
input_dir
log_records

Retrieve logs from the most recent run of this step.

make_output_path

Return function that creates the output path

name_format
reference_file_types

Collect the list of all reftypes for child Steps that are not skipped.

Methods

__call__(*args)

Run handles the generic setup and teardown that happens with the running of each step.

build_config(input, **kwargs)

Build the ConfigObj to initialize a Step

call(*args, **kwargs)

Creates and runs a new instance of the class.

closeout([to_close, to_del])

Close out step processing

default_output_file([input_file])

Create a default filename based on the input name

default_suffix()

Return a default suffix based on the step

export_config(filename[, include_metadata])

Export this step's parameters to an ASDF config file.

finalize_config(config[, name, config_file, ...])

Load default config, merge with config_file if present, then validate.

finalize_result(result, reference_files_used)

Hook that allows subclasses to set mission-specific metadata on each step result before that result is saved.

from_cmdline(args)

Create a step from a configuration file.

from_config_file(config_file[, parent, name])

Create a step from a configuration file.

from_config_section(config[, parent, name, ...])

Create a step from a configuration file fragment.

get_config_from_reference(dataset[, ...])

Retrieve step parameters from reference database

get_config_reftype()

Get the CRDS reftype for this step's config reference.

get_pars([full_spec])

Retrieve the configuration parameters of a pipeline

get_ref_override(reference_file_type)

Return any override for reference_file_type for any of the steps in Pipeline self.

get_reference_file(input_file, ...)

Get a reference file from CRDS.

load_as_level2_asn(obj)

Load object as an association

load_as_level3_asn(obj)

Load object as an association

make_input_path(file_path)

Create an input path for a given file path

merge_pipeline_config(refcfg, ref_file)

Merge the config parameters from a pipeline config reference file into the config obtained from each step

open_model(init, **kwargs)

Open a datamodel

prefetch(*args)

Prefetch reference files, nominally called when self.prefetch_references is True.

process(input)

This is where real work happens.

record_step_status(datamodel, cal_step[, ...])

Record whether or not a step completed in meta.cal_step

reference_uri_to_cache_path(reference_uri, ...)

Convert an abstract CRDS reference URI to an absolute file path in the CRDS cache.

remove_suffix(name)

Remove a known Step filename suffix from a filename (if present).

resolve_file_name(file_name)

Resolve a file name expressed relative to this Step's configuration file.

run(*args)

Run handles the generic setup and teardown that happens with the running of each step.

run_eurekaS1(filename, meta, log)

Reduces uncal files from STScI into rateints files.

save_model(model[, suffix, idx, ...])

Saves the given model using the step/pipeline's naming scheme

search_attr(attribute[, default, parent_first])

Return first non-None attribute in step heirarchy

set_primary_input(obj[, exclusive])

Sets the name of the master input file and input directory.

update_pars(parameters)

Update step parameters

load_spec_file

merge_config

print_configspec

set_input_filename

setup_output

run_eurekaS1(filename, meta, log)[source]

Reduces uncal files from STScI into rateints files.

Parameters
filenamestr

A string pointing to the uncal file to be operated on.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

Notes

History:

  • October 2021 Aarynn Carter / Eva-Maria Ahrer

    Initial version

  • February 2022 Aarynn Carter / Eva-Maria Ahrer

    Updated for JWST version 1.3.3, code restructure

eureka.S1_detector_processing.s1_process.rampfitJWST(eventlabel, ecf_path=None)[source]

Process a Stage 0, _uncal.fits file to Stage 1 _rate.fits and _rateints.fits files.

Steps taken to perform this processing can follow the default JWST pipeline, or alternative methods.

Parameters
eventlabelstr

The unique identifier for these data.

ecf_pathstr; optional

The absolute or relative path to where ecfs are stored. Defaults to None which resolves to ‘./’.

Returns
metaeureka.lib.readECF.MetaClass

The metadata object.

Notes

History:

  • October 2021 Taylor Bell

    Code fragments

  • October 2021 Aarynn Carter and Eva-Maria Ahrer

    Initial version

  • February 2022 Aarynn Carter and Eva-Maria Ahrer

    Updated for JWST version 1.3.3, code restructure

S2_calibrations

S2_calibrations.s2_calibrate

class eureka.S2_calibrations.s2_calibrate.EurekaImage2Pipeline(*args, **kwargs)[source]

Bases: Image2Pipeline

A wrapper class for the jwst.pipeline.calwebb_image2.Image2Pipeline.

This wrapper class allows non-standard changes to Stage 2 for Eureka!.

Notes

History:

  • October 2021 Taylor Bell

    Initial version

Attributes
correction_pars
input_dir
log_records

Retrieve logs from the most recent run of this step.

make_output_path

Return function that creates the output path

name_format
reference_file_types

Collect the list of all reftypes for child Steps that are not skipped.

Methods

__call__(*args)

Run handles the generic setup and teardown that happens with the running of each step.

build_config(input, **kwargs)

Build the ConfigObj to initialize a Step

call(*args, **kwargs)

Creates and runs a new instance of the class.

closeout([to_close, to_del])

Close out step processing

default_output_file([input_file])

Create a default filename based on the input name

default_suffix()

Return a default suffix based on the step

export_config(filename[, include_metadata])

Export this step's parameters to an ASDF config file.

finalize_config(config[, name, config_file, ...])

Load default config, merge with config_file if present, then validate.

finalize_result(result, reference_files_used)

Hook that allows subclasses to set mission-specific metadata on each step result before that result is saved.

from_cmdline(args)

Create a step from a configuration file.

from_config_file(config_file[, parent, name])

Create a step from a configuration file.

from_config_section(config[, parent, name, ...])

Create a step from a configuration file fragment.

get_config_from_reference(dataset[, ...])

Retrieve step parameters from reference database

get_config_reftype()

Get the CRDS reftype for this step's config reference.

get_pars([full_spec])

Retrieve the configuration parameters of a pipeline

get_ref_override(reference_file_type)

Return any override for reference_file_type for any of the steps in Pipeline self.

get_reference_file(input_file, ...)

Get a reference file from CRDS.

load_as_level2_asn(obj)

Load object as an association

load_as_level3_asn(obj)

Load object as an association

make_input_path(file_path)

Create an input path for a given file path

merge_pipeline_config(refcfg, ref_file)

Merge the config parameters from a pipeline config reference file into the config obtained from each step

open_model(init, **kwargs)

Open a datamodel

prefetch(*args)

Prefetch reference files, nominally called when self.prefetch_references is True.

process(input)

This is where real work happens.

process_exposure_product(exp_product[, ...])

Process an exposure found in the association product

record_step_status(datamodel, cal_step[, ...])

Record whether or not a step completed in meta.cal_step

reference_uri_to_cache_path(reference_uri, ...)

Convert an abstract CRDS reference URI to an absolute file path in the CRDS cache.

remove_suffix(name)

Remove a known Step filename suffix from a filename (if present).

resolve_file_name(file_name)

Resolve a file name expressed relative to this Step's configuration file.

run(*args)

Run handles the generic setup and teardown that happens with the running of each step.

run_eurekaS2(filename, meta, log)

Reduces rateints image files ouput from Stage 1 of the JWST pipeline into calints.

save_model(model[, suffix, idx, ...])

Saves the given model using the step/pipeline's naming scheme

search_attr(attribute[, default, parent_first])

Return first non-None attribute in step heirarchy

set_primary_input(obj[, exclusive])

Sets the name of the master input file and input directory.

update_pars(parameters)

Update step parameters

load_spec_file

merge_config

print_configspec

set_input_filename

run_eurekaS2(filename, meta, log)[source]

Reduces rateints image files ouput from Stage 1 of the JWST pipeline into calints.

Parameters
filenamestr

A string pointing to the rateint or rateints file to process.

metaMetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

Notes

History:

  • 03 Nov 2021 Taylor Bell

    Initial version

class eureka.S2_calibrations.s2_calibrate.EurekaSpec2Pipeline(*args, **kwargs)[source]

Bases: Spec2Pipeline

A wrapper class for the jwst.pipeline.calwebb_spec2.Spec2Pipeline.

This wrapper class allows non-standard changes to Stage 2 for Eureka!.

Notes

History:

  • October 2021 Taylor Bell

    Initial version

Attributes
correction_pars
input_dir
log_records

Retrieve logs from the most recent run of this step.

make_output_path

Return function that creates the output path

name_format
reference_file_types

Collect the list of all reftypes for child Steps that are not skipped.

Methods

__call__(*args)

Run handles the generic setup and teardown that happens with the running of each step.

build_config(input, **kwargs)

Build the ConfigObj to initialize a Step

call(*args, **kwargs)

Creates and runs a new instance of the class.

closeout([to_close, to_del])

Close out step processing

default_output_file([input_file])

Create a default filename based on the input name

default_suffix()

Return a default suffix based on the step

export_config(filename[, include_metadata])

Export this step's parameters to an ASDF config file.

finalize_config(config[, name, config_file, ...])

Load default config, merge with config_file if present, then validate.

finalize_result(result, reference_files_used)

Hook that allows subclasses to set mission-specific metadata on each step result before that result is saved.

from_cmdline(args)

Create a step from a configuration file.

from_config_file(config_file[, parent, name])

Create a step from a configuration file.

from_config_section(config[, parent, name, ...])

Create a step from a configuration file fragment.

get_config_from_reference(dataset[, ...])

Retrieve step parameters from reference database

get_config_reftype()

Get the CRDS reftype for this step's config reference.

get_pars([full_spec])

Retrieve the configuration parameters of a pipeline

get_ref_override(reference_file_type)

Return any override for reference_file_type for any of the steps in Pipeline self.

get_reference_file(input_file, ...)

Get a reference file from CRDS.

load_as_level2_asn(obj)

Load object as an association

load_as_level3_asn(obj)

Load object as an association

make_input_path(file_path)

Create an input path for a given file path

merge_pipeline_config(refcfg, ref_file)

Merge the config parameters from a pipeline config reference file into the config obtained from each step

open_model(init, **kwargs)

Open a datamodel

prefetch(*args)

Prefetch reference files, nominally called when self.prefetch_references is True.

process(data)

Entrypoint for this pipeline

process_exposure_product(exp_product[, ...])

Process an exposure found in the association product

record_step_status(datamodel, cal_step[, ...])

Record whether or not a step completed in meta.cal_step

reference_uri_to_cache_path(reference_uri, ...)

Convert an abstract CRDS reference URI to an absolute file path in the CRDS cache.

remove_suffix(name)

Remove a known Step filename suffix from a filename (if present).

resolve_file_name(file_name)

Resolve a file name expressed relative to this Step's configuration file.

run(*args)

Run handles the generic setup and teardown that happens with the running of each step.

run_eurekaS2(filename, meta, log)

Reduces rateints spectrum files ouput from Stage 1 of the JWST pipeline into calints and x1dints.

save_model(model[, suffix, idx, ...])

Saves the given model using the step/pipeline's naming scheme

search_attr(attribute[, default, parent_first])

Return first non-None attribute in step heirarchy

set_primary_input(obj[, exclusive])

Sets the name of the master input file and input directory.

update_pars(parameters)

Update step parameters

load_spec_file

merge_config

print_configspec

set_input_filename

run_eurekaS2(filename, meta, log)[source]

Reduces rateints spectrum files ouput from Stage 1 of the JWST pipeline into calints and x1dints.

Parameters
filenamestr

A string pointing to the rateint or rateints file to process.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

Notes

History:

  • June 2021 Eva-Maria Ahrer and Aarynn Carter

    Code fragments written

  • October 2021 Taylor Bell

    Significantly overhauled code formatting

  • 03 Nov 2021 Taylor Bell

    Fragmented code to allow reuse of code between spectral and image analysis.

eureka.S2_calibrations.s2_calibrate.calibrateJWST(eventlabel, ecf_path=None, s1_meta=None)[source]

Reduces rateints spectrum or image files ouput from Stage 1 of the JWST pipeline into calints and x1dints.

This function does the preparation for running the STScI’s JWST pipeline and decides whether to run the Spec2Pipeline or Image2Pipeline.

Parameters
eventlabelstr

Unique label for this dataset.

ecf_pathstr; optional

The absolute or relative path to where ecfs are stored. Defaults to None which resolves to ‘./’.

s1_metaeureka.lib.readECF.MetaClass; optional

The metadata object from Eureka!’s S1 step (if running S1 and S2 sequentially). Defaults to None.

Returns
metaeureka.lib.readECF.MetaClass

The metadata object.

Notes

History:

  • 03 Nov 2021 Taylor Bell

    Initial version

S3_data_reduction

S3_data_reduction.background

eureka.S3_data_reduction.background.BGsubtraction(data, meta, log, m)[source]

Does background subtraction using inst.fit_bg & background.fitbg

Parameters
dataXarray Dataset

Dataset object containing data, uncertainty, and variance arrays in units of MJy/sr or electrons.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

mint

The current file/batch number.

Returns
dataXarray Dataset

Dataset object containing background subtracted data.

Notes

History:

  • Dec 10, 2021 Taylor Bell

    Edited to pass the full DataClass object into inst.fit_bg

  • Apr 20, 2022 Kevin Stevenson

    Convert to using Xarray Dataset

eureka.S3_data_reduction.background.fitbg(dataim, meta, mask, x1, x2, deg=1, threshold=5, isrotate=False, isplots=0)[source]

Fit sky background with out-of-spectra data.

Parameters
dataimndarray

The data array.

metaeureka.lib.readECF.MetaClass

The metadata object.

maskndarray

A mask array.

x1ndarray
x2ndarray
degint; optional

Polynomial order for column-by-column background subtraction Default is 1.

thresholdint; optional

Sigma threshold for outlier rejection during background subtraction. Defaullt is 5.

isrotatebool; optional

Default is False.

isplotsint; optional

The amount of plots saved; set in ecf. Default is 0.

Notes

History:

  • May 2013

    Removed [::-1] for LDSS3

  • Feb 2014

    Modified x1 and x2 to allow for arrays

eureka.S3_data_reduction.background.fitbg2(dataim, meta, mask, bgmask, deg=1, threshold=5, isrotate=False, isplots=0)[source]

Fit sky background with out-of-spectra data.

fitbg2 uses bgmask, a mask for the background region which enables fitting more complex background regions than simply above or below a given distance from the trace. This will help mask the 2nd and 3rd orders of NIRISS.

Parameters
dataimndarray

The data array.

metaeureka.lib.readECF.MetaClass

The metadata object.

maskndarray

A mask array.

bgmaskndarray

A background mask array.

degint; optional

Polynomial order for column-by-column background subtraction. Default is 1.

thresholdint; optional

Sigma threshold for outlier rejection during background subtraction. Default is 5.

isrotatebool; optional

Default is False.

isplotsint; optional

The amount of plots saved; set in ecf. Default is 0.

Notes

History:

  • September 2016 Kevin Stevenson

    Initial version

eureka.S3_data_reduction.background.fitbg3(data, order_mask, readnoise=11, sigclip=[4, 2, 3], isplots=0)[source]

Fit sky background with out-of-spectra data. Optimized to remove the 1/f noise in the NIRISS spectra (works in the y-direction).

Parameters
isplotsbool; optional

Plots intermediate steps for the background fitting routine. Default is False.

Returns
dataobject

data object now contains new attribute bkg_removed.

S3_data_reduction.bright2flux

eureka.S3_data_reduction.bright2flux.bright2dn(data, meta, mjy=False)[source]

This function converts the data, uncertainty, and variance arrays from brightness units (MJy/sr) or (MJy) to raw units (DN).

Parameters
dataXarray Dataset

Dataset object containing data, uncertainty, and variance arrays in units of MJy/sr.

metaeureka.lib.readECF.MetaClass

The metadata object.

Returns
dataXarray Dataset

Dataset object containing data, uncertainty, and variance arrays in units of DN.

Notes

The photometry files can be downloaded from CRDS (https://jwst-crds.stsci.edu/browse_db/)

History:

  • 2021-05-28 kbs

    Initial version

  • 2021-07-21 sz

    Added functionality for MIRI

  • Apr 20, 2022 Kevin Stevenson

    Convert to using Xarray Dataset

eureka.S3_data_reduction.bright2flux.bright2flux(data, pixel_area)[source]

This function converts the data and uncertainty arrays from brightness units (MJy/sr) to flux units (Jy/pix).

Parameters
dataXarray Dataset

Dataset object containing data, uncertainty, and variance arrays in units of MJy/sr.

pixel_areandarray

Pixel area (arcsec/pix)

Returns
dataXarray Dataset

Dataset object containing data, uncertainty, and variance arrays in units of Jy/pix.

Notes

The input arrays Data and Uncd are changed in place.

History:

  • 2005-06-20 Statia Luszcz, Cornell (shl35@cornell.edu).

  • 2005-10-13 jh

    Renamed, modified doc, removed posmed, fixed nimpos default bug (was float rather than int).

  • 2005-10-28 jh

    Updated header to give units being converted from/to, made srperas value a calculation rather than a constant, added Allen reference.

  • 2005-11-24 jh

    Eliminated NIMPOS.

  • 2008-06-28 jh

    Allow npos=1 case.

  • 2010-01-29 patricio (pcubillos@fulbrightmail.org)

    Converted to python.

  • 2010-11-01 patricio

    Documented, and incorporated scipy.constants.

  • 2021-05-28 kbs

    Updated for JWST

  • 2021-12-09 TJB

    Updated to account for the new DataClass object

  • Apr 20, 2022 Kevin Stevenson

    Convert to using Xarray Dataset

eureka.S3_data_reduction.bright2flux.convert_to_e(data, meta, log)[source]

This function converts the data object to electrons from MJy/sr or DN/s.

Parameters
dataXarray Dataset

Dataset object containing data, uncertainty, and variance arrays in units of MJy/sr or DN/s.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

Returns
dataXarray Dataset

Dataset object containing data, uncertainty, and variance arrays in units of electrons.

metaeureka.lib.readECF.MetaClass

The metadata object.

eureka.S3_data_reduction.bright2flux.dn2electrons(data, meta)[source]

This function converts the data, uncertainty, and variance arrays from raw units (DN) to electrons.

Parameters
dataXarray Dataset

Dataset object containing data, uncertainty, and variance arrays in units of DN.

metaeureka.lib.readECF.MetaClass

The metadata object.

Returns
dataXarray Dataset

Dataset object containing data, uncertainty, and variance arrays in units of electrons.

Notes

The gain files can be downloaded from CRDS (https://jwst-crds.stsci.edu/browse_db/)

History:

  • Jun 2021 Kevin Stevenson

    Initial version

  • Jul 2021

    Added gainfile rotation

  • Apr 20, 2022 Kevin Stevenson

    Convert to using Xarray Dataset

eureka.S3_data_reduction.bright2flux.rate2count(data)[source]

This function converts the data, uncertainty, and variance arrays from rate units (#/s) to counts (#).

Parameters
dataXarray Dataset

Dataset object containing data, uncertainty, and variance arrays in rate units (#/s).

Returns
dataXarray Dataset

Dataset object containing data, uncertainty, and variance arrays in count units (#).

Notes

History:

  • Mar 7, 2022 Taylor J Bell

    Initial version

  • Apr 20, 2022 Kevin Stevenson

    Convert to using Xarray Dataset

eureka.S3_data_reduction.bright2flux.retrieve_ancil(fitsname)[source]

Use crds package to find/download the needed ancilliary files.

This code requires that the CRDS_PATH and CRDS_SERVER_URL environment variables be set in your .bashrc file (or equivalent, e.g. .bash_profile or .zshrc)

Parameters
fitsnamestr

The filename of the file currently being analyzed.

Returns
phot_filenamestr

The full path to the photom calibration file.

gain_filenamestr

The full path to the gain calibration file.

Notes

History:

  • 2022-03-04 Taylor J Bell

    Initial code version.

  • 2022-03-28 Taylor J Bell

    Removed jwst dependency, using crds package now instead.

S3_data_reduction.hst_scan

eureka.S3_data_reduction.hst_scan.calcDrift2D(im1, im2, n)[source]

Calculates 2D drift of im2 with respect to im1 for diagnostic use, to align the images, and/or for decorrelation.

Parameters
im1ndarray (2D)

The reference image.

im2ndarray (2D)

The current image.

nint

The current integration number.

Returns
drift2Dlist

The x and y offset of im2 with respect to im1.

nint

The current integration number.

Raises
ModuleNotFoundError

image_registration wasn’t installed with Eureka.

eureka.S3_data_reduction.hst_scan.calcTrace(x, centroid, grism)[source]

Calculates the WFC3 trace given the position of the direct image in physical pixels.

Parameters
xndarray

Physical pixel values along dispersion direction over which the trace is calculated

centroidlist

[y,x] pair describing the centroid of the direct image

grismstr

The grism being used.

Returns
yndarray

Computed trace.

Notes

History:

  • LK

    Initial version

  • November 2021, Kevin Stevenson

    Modified

eureka.S3_data_reduction.hst_scan.calibrateLambda(x, centroid, grism)[source]

Calculates the wavelength solution for WFC3 observations.

Parameters
xndarray

Physical pixel values along dispersion direction over which the trace is calculated

centroidlist

[y,x] pair describing the centroid of the direct image

grismstr

The grism being used.

Returns
yndarray

Computed wavelength values

Notes

History:

  • LK

    Initial version

  • November 2021, Kevin Stevenson

    Modified

eureka.S3_data_reduction.hst_scan.groupFrames(dates)[source]

Group frames by HST orbit and batch number.

Parameters
datesndarray (1D)

Time in days

Returns
framenumndarray (1D)

The frame numbers.

batchnumndarray (1D)

The batch numbers.

orbitnumndarray (1D)

The orbit numbers.

eureka.S3_data_reduction.hst_scan.imageCentroid(filenames, guess, trim, ny, CRPIX1, CRPIX2, POSTARG1, POSTARG2, meta, log)[source]

Calculate centroid for a list of direct images from HST.

Parameters
filenameslist

List of direct image filenames

guessarray_like

The initial guess of the position of the star. Has the form (x, y) of the guess center.

trimint

If trim!=0, trims the image in a box of 2*trim pixels around the guess center. Must be !=0 for ‘col’ method.

nyint

The value of NAXIS2

CRPIX1float

The value of CRPIX1 in the main FITS header

CRPIX2float

The value of CRPIX2 in the main FITS header

POSTARG1float

The value of POSTARG1 in the science FITS header

POSTARG2float

The value of POSTARG2 in the science FITS header

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
centerslist

Centroids

Notes

History:

  • November 2013, Kevin Stevenson

    Initial version

  • March 2016, Kevin Stevenson

    Added IRSUB256

  • December 8, 2021, Taylor J Bell

    Updated for Eureka

eureka.S3_data_reduction.hst_scan.makeBasicFlats(flatfile, xwindow, ywindow, flatoffset, ny, nx, sigma=5, isplots=0)[source]

Makes master flatfield image (with no wavelength correction) and new mask for WFC3 data.

Parameters
flatfilelist

List of files containing flatfiles images

xwindowndarray

Array containing image limits in wavelength direction

ywindowndarray

Array containing image limits in spatial direction

n_specint

Number of spectra

sigmafloat

Sigma rejection level

Returns
flat_masterlist

Single master flatfield image

mask_masterlist

Single bad-pixel mask image

Notes

History:

  • November 2012, Kevin Stevenson

    Initial version.

  • February 2018, Kevin Stevenson

    Removed wavelength dependence.

eureka.S3_data_reduction.hst_scan.makeflats(flatfile, wave, xwindow, ywindow, flatoffset, n_spec, ny, nx, sigma=5, isplots=0)[source]

Makes master flatfield image and new mask for WFC3 data.

Parameters
flatfilelist

List of files containing flatfiles images.

wavendarray

Wavelengths.

xwindowlist

Array containing image limits in wavelength direction.

ywindowlist

Array containing image limits in spatial direction.

n_specint

Number of spectra.

sigmafloat

Sigma rejection level.

Returns
flat_masterlist

Single master flatfield image.

mask_masterlist

Single bad-pixel mask image.

Notes

History:

  • November 2012, Kevin Stevenson

    Initial version.

S3_data_reduction.miri

eureka.S3_data_reduction.miri.cut_aperture(data, meta, log)[source]

Select the aperture region out of each trimmed image.

Uses the code written for NIRCam which works for MIRI as long as the MIRI data gets rotated.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
apdatandarray

The flux values over the aperture region.

aperrndarray

The noise values over the aperture region.

apmaskndarray

The mask values over the aperture region.

apbgndarray

The background flux values over the aperture region.

apv0ndarray

The v0 values over the aperture region.

Notes

History:

  • 2022-06-17, Taylor J Bell

    Initial version based on the code in s3_reduce.py

eureka.S3_data_reduction.miri.fit_bg(dataim, datamask, n, meta, isplots=0)[source]

Fit for a non-uniform background.

Uses the code written for NIRCam which works for MIRI as long as the MIRI data gets rotated.

Parameters
dataimndarray (2D)

The 2D image array.

datamaskndarray (2D)

An array of which data should be masked.

nint

The current integration.

metaeureka.lib.readECF.MetaClass

The metadata object.

isplotsint; optional

The plotting verbosity, by default 0.

Returns
bgndarray (2D)

The fitted background level.

maskndarray (2D)

The updated mask after background subtraction.

nint

The current integration number.

eureka.S3_data_reduction.miri.flag_bg(data, meta, log)[source]

Outlier rejection of sky background along time axis.

Uses the code written for NIRCam which works for MIRI as long as the MIRI data gets rotated.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with outlier background pixels flagged.

eureka.S3_data_reduction.miri.read(filename, data, meta, log)[source]

Reads single FITS file from JWST’s MIRI instrument.

Parameters
filenamestr

Single filename to read.

dataXarray Dataset

The Dataset object in which the fits data will stored.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with the fits data stored inside.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Notes

History:

  • Nov 2012 Kevin Stevenson

    Initial Version

  • May 2021 Kevin Stevenson

    Updated for NIRCam

  • Jun 2021 Taylor Bell

    Updated docs for MIRI

  • Jun 2021 Sebastian Zieba

    Updated for MIRI

  • Apr 2022 Sebastian Zieba

    Updated wavelength array

  • Apr 21, 2022 Kevin Stevenson

    Convert to using Xarray Dataset

eureka.S3_data_reduction.miri.wave_MIRI_jwst(filename, meta, log)[source]

Compute wavelengths for simulated MIRI observations.

This code uses the jwst package to get the wavelength information out of the WCS.

Parameters
filenamestr

The filename of the file being read in.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
lam_x_fulllist

A list of the wavelengths

Notes

History:

  • August 2022 Taylor J Bell

    Initial Version

S3_data_reduction.nircam

eureka.S3_data_reduction.nircam.cut_aperture(data, meta, log)[source]

Select the aperture region out of each trimmed image.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
apdatandarray

The flux values over the aperture region.

aperrndarray

The noise values over the aperture region.

apmaskndarray

The mask values over the aperture region.

apbgndarray

The background flux values over the aperture region.

apv0ndarray

The v0 values over the aperture region.

Notes

History:

  • 2022-06-17, Taylor J Bell

    Initial version based on the code in s3_reduce.py

eureka.S3_data_reduction.nircam.do_oneoverf_corr(data, meta, i, star_pos_x, log)[source]

Correcting for 1/f noise in each amplifier region by doing a row-by-row subtraction while avoiding pixels close to the star.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

iint

The current integration.

star_pos_xint

The star position in columns (x dimension).

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object after the 1/f correction has been completed.

eureka.S3_data_reduction.nircam.fit_bg(dataim, datamask, n, meta, isplots=0)[source]

Fit for a non-uniform background.

Parameters
dataimndarray (2D)

The 2D image array.

datamaskndarray (2D)

An array of which data should be masked.

nint

The current integration.

metaeureka.lib.readECF.MetaClass

The metadata object.

isplotsint; optional

The plotting verbosity, by default 0.

Returns
bgndarray (2D)

The fitted background level.

maskndarray (2D)

The updated mask after background subtraction.

nint

The current integration number.

eureka.S3_data_reduction.nircam.flag_bg(data, meta, log)[source]

Outlier rejection of sky background along time axis.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with outlier background pixels flagged.

eureka.S3_data_reduction.nircam.flag_bg_phot(data, meta, log)[source]

Outlier rejection of segment along time axis adjusted for the photometry reduction routine.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with outlier background pixels flagged.

eureka.S3_data_reduction.nircam.read(filename, data, meta, log)[source]

Reads single FITS file from JWST’s NIRCam instrument.

Parameters
filenamestr

Single filename to read.

dataXarray Dataset

The Dataset object in which the fits data will stored.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with the fits data stored inside.

metaeureka.lib.readECF.MetaClass

The updated metadata object.

loglogedit.Logedit

The current log.

Notes

History:

  • November 2012 Kevin Stevenson

    Initial version

  • May 2021 KBS

    Updated for NIRCam

  • July 2021

    Moved bjdtdb into here

  • Apr 20, 2022 Kevin Stevenson

    Convert to using Xarray Dataset

S3_data_reduction.niriss_profiles

A library of custom weighted profiles to fit to the NIRISS orders to complete the optimal extraction of the data.

eureka.S3_data_reduction.niriss_profiles.gaussian_1poly_piecewise(args, x)[source]

A piece-wise function consisting of 2 generalized normal distribution profiles connected with a 1D polynomial to mimic the bat-shaped profile of NIRISS.

Parameters
argsnp.ndarray

A list or array of parameters for the fits.

xnp.ndarray

X values to evaluate the shape over.

eureka.S3_data_reduction.niriss_profiles.gaussian_2poly_piecewise(args, x)[source]

A piece-wise function consisting of 2 generalized normal distribution profiles connected with a 2D polynomial to mimic the bat-shaped profile of NIRISS.

Parameters
argsnp.ndarray

A list or array of parameters for the fits.

xnp.ndarray

X values to evaluate the shape over.

eureka.S3_data_reduction.niriss_profiles.generalized_normal(x, mu, alpha, beta, scale)[source]

Generalized normal distribution.

Parameters
xnp.ndarray

X values to evaluate the distribution. over.

mufloat

Mean/center value of the distribution.

alphafloat

Sets the scale/standard deviation of the distribution.

betafloat

Sets the shape of the distribution. Beta > 2 becomes boxy. Beta < 2 becomes peaky. Beta = 2 is a normal Gaussian.

scalefloat

A value to scale the distribution by.

eureka.S3_data_reduction.niriss_profiles.moffat_1poly_piecewise(args, x)[source]

A piece-wise function consisting of 2 Moffat profiles connected with a 1D polynomial to mimic the bat-shaped profile of NIRISS.

Parameters
argsnp.ndarray

A list or array of parameters for the fits.

xnp.ndarray

X values to evaluate the shape over.

eureka.S3_data_reduction.niriss_profiles.moffat_2poly_piecewise(args, x)[source]

A piece-wise function consisting of 2 Moffat profiles connected with a 2D polynomial to mimic the bat-shaped profile of NIRISS.

Parameters
argsnp.ndarray

A list or array of parameters for the fits.

xnp.ndarray

X values to evaluate the shape over.

S3_data_reduction.niriss

eureka.S3_data_reduction.niriss.f277_mask(data, isplots=0)[source]

Marks the overlap region in the f277w filter image.

Parameters
dataobject
isplotsint; optional

Level of plots that should be created in the S3 stage. This is set in the .ecf control files. Default is 0. This stage will plot if isplots >= 5.

Returns
masknp.ndarray

2D mask for the f277w filter.

midnp.ndarray

(x,y) anchors for where the overlap region is located.

eureka.S3_data_reduction.niriss.fit_bg(data, meta, n_iters=3, readnoise=11, sigclip=[4, 4, 4], isplots=0)[source]

Subtracts background from non-spectral regions.

Parameters
dataobject
metaobject
n_itersint; optional

The number of iterations to go over and remove cosmic rays. Default is 3.

readnoisefloat; optional

An estimation of the readnoise of the detector. Default is 5.

sigcliplist, array; optional

A list or array of len(n_iiters) corresponding to the sigma-level which should be clipped in the cosmic ray removal routine. Default is [4,2,3].

isplotsint; optional

The level of output plots to display. Default is 0 (no plots).

Returns
dataobject
eureka.S3_data_reduction.niriss.fit_orders(data, meta, which_table=2)[source]

Creates a 2D image optimized to fit the data. Currently runs with a Gaussian profile, but will look into other more realistic profiles at some point. This routine is a bit slow, but fortunately, you only need to run it once per observations.

Parameters
dataobject
metaobject
which_tableint; optional

Sets with table of initial y-positions for the orders to use. Default is 2.

Returns
metaobject

Adds two new attributes: order1_mask and order2_mask.

eureka.S3_data_reduction.niriss.fit_orders_fast(data, meta, which_table=2)[source]

A faster method to fit a 2D mask to the NIRISS data. Very similar to fit_orders, but works with scipy.optimize.leastsq.

Parameters
dataobject
metaobject
which_tableint; optional

Sets with table of initial y-positions for the orders to use. Default is 2.

Returns
metaobject
eureka.S3_data_reduction.niriss.image_filtering(img, radius=1, gf=4)[source]

Does some simple image processing to isolate where the spectra are located on the detector. This routine is optimized for NIRISS S2 processed data and the F277W filter.

Parameters
imgnp.ndarray

2D image array.

radiusnp.float; optional

Default is 1.

gfnp.float; optional

The standard deviation by which to Gaussian smooth the image. Default is 4.

Returns
img_masknp.ndarray

A mask for the image that isolates where the spectral orders are.

eureka.S3_data_reduction.niriss.mask_method_one(data, meta, isplots=0, save=True)[source]

There are some hard-coded numbers in here right now. The idea is that once we know what the real data looks like, nobody will have to actually call this function and we’ll provide a CSV of a good initial guess for each order. This method uses some fun image processing to identify the boundaries of the orders and fits the edges of the first and second orders with a 4th degree polynomial.

Parameters
dataobject
metaobject
isplotsint; optional

Level of plots that should be created in the S3 stage. This is set in the .ecf control files. Default is 0. This stage will plot if isplots >= 5.

savebool; optional

An option to save the polynomial fits to a CSV. Default is True. Output table is saved under niriss_order_guesses.csv.

Returns
metaobject
eureka.S3_data_reduction.niriss.mask_method_two(data, meta, isplots=0, save=False)[source]

A second method to extract the masks for the first and second orders in NIRISS data. This method uses the vertical profile of a summed image to identify the borders of each order.

Parameters
dataobject
metaobject
isplotsint; optional

Level of plots that should be created in the S3 stage. This is set in the .ecf control files. Default is 0. This stage will plot if isplots >= 5.

savebool; optional

Has the option to save the initial guesses for the location of the NIRISS orders. This is set in the .ecf control files. Default is False.

Returns
metaobject
eureka.S3_data_reduction.niriss.read(filename, f277_filename, data, meta)[source]

Reads a single FITS file from JWST’s NIRISS instrument. This takes in the Stage 2 processed files.

Parameters
filenamestr

Single filename to read. Should be a .fits file.

dataobject

Data object in which the fits data will be stored.

Returns
dataobject

Data object now populated with all of the FITS file information.

metaastropy.table.Table

Metadata stored in the FITS file.

eureka.S3_data_reduction.niriss.simplify_niriss_img(data, meta, isplots=0)[source]

Creates an image to map out where the orders are in the NIRISS data.

Parameters
dataobject
metaobject
isplotsint; optional

Level of plots that should be created in the S3 stage. This is set in the .ecf control files. Default is 0.

Returns
gnp.ndarray

A 2D array that marks where the NIRISS first and second orders are.

eureka.S3_data_reduction.niriss.wave_NIRISS(wavefile, meta)[source]

Adds the 2D wavelength solutions to the meta object.

Parameters
wavefilestr

The name of the .FITS file with the wavelength solution.

metaobject
Returns
metaobject

S3_data_reduction.nirspec

eureka.S3_data_reduction.nirspec.cut_aperture(data, meta, log)[source]

Select the aperture region out of each trimmed image.

Uses the code written for NIRCam which works for NIRSpec.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
apdatandarray

The flux values over the aperture region.

aperrndarray

The noise values over the aperture region.

apmaskndarray

The mask values over the aperture region.

apbgndarray

The background flux values over the aperture region.

apv0ndarray

The v0 values over the aperture region.

Notes

History:

  • 2022-06-17, Taylor J Bell

    Initial version based on the code in s3_reduce.py

eureka.S3_data_reduction.nirspec.fit_bg(dataim, datamask, n, meta, isplots=0)[source]

Fit for a non-uniform background.

Uses the code written for NIRCam which works for NIRSpec.

Parameters
dataimndarray (2D)

The 2D image array.

datamaskndarray (2D)

An array of which data should be masked.

nint

The current integration.

metaeureka.lib.readECF.MetaClass

The metadata object.

isplotsint; optional

The plotting verbosity, by default 0.

Returns
bgndarray (2D)

The fitted background level.

maskndarray (2D)

The updated mask after background subtraction.

nint

The current integration number.

eureka.S3_data_reduction.nirspec.flag_bg(data, meta, log)[source]

Outlier rejection of sky background along time axis.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with outlier background pixels flagged.

eureka.S3_data_reduction.nirspec.read(filename, data, meta, log)[source]

Reads single FITS file from JWST’s NIRCam instrument.

Parameters
filenamestr

Single filename to read.

dataXarray Dataset

The Dataset object in which the fits data will stored.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with the fits data stored inside.

metaeureka.lib.readECF.MetaClass

The metadata object

loglogedit.Logedit

The current log.

Notes

History:

  • November 2012 Kevin Stevenson

    Initial version

  • June 2021 Aarynn Carter/Eva-Maria Ahrer

    Updated for NIRSpec

  • Apr 22, 2022 Kevin Stevenson

    Convert to using Xarray Dataset

S3_data_reduction.optspex

eureka.S3_data_reduction.optspex.clean_median_flux(data, meta, log, m)[source]

Computes a median flux frame that is free of bad pixels.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

mint

The file number.

Returns
dataXarray Dataset

The updated Dataset object.

Notes

History:

  • 2022-08-03, KBS

    Inital version

eureka.S3_data_reduction.optspex.optimize(meta, subdata, mask, bg, spectrum, Q, v0, p5thresh=10, p7thresh=10, fittype='smooth', window_len=21, deg=3, windowtype='hanning', n=0, m=0, meddata=None)[source]

Extract optimal spectrum with uncertainties for a single frame.

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

subdatandarray

Background subtracted data.

maskndarray

Outlier mask.

bgndarray

Background array.

spectrumndarray

Standard spectrum.

Qfloat

The gain factor.

v0ndarray

Variance array for data.

p5threshfloat; optional

Sigma threshold for outlier rejection while constructing spatial profile. Defaults to 10.

p7threshfloat; optional

Sigma threshold for outlier rejection during optimal spectral extraction. Defaukts to 10.

fittypestr; optional

One of {‘smooth’, ‘meddata’, ‘wavelet2D’, ‘wavelet’, ‘gauss’, ‘poly’}. The type of profile fitting you want to do. Defaults to ‘smooth’.

window_lenint; optional

The dimension of the smoothing window. Defaults to 21.

degint; optional

Polynomial degree. Defaults to 3.

windowtypestr; optional

UNUSED. One of {‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’}. The type of window. A flat window will produce a moving average smoothing. Defaults to ‘hanning’.

nint; optional

Integration number. Defaults to 0.

mint; optional

File number. Defaults to 0.

meddatandarray; optional

The median of all data frames. Defaults to None.

Returns
spectrumndarray

The optimally extracted spectrum.

specuncndarray

The standard deviation on the spectrum.

submaskndarray

The mask array.

eureka.S3_data_reduction.optspex.optimize_wrapper(data, meta, log, apdata, apmask, apbg, apv0, gain=1, windowtype='hanning', m=0)[source]

Extract optimal spectrum with uncertainties for many frames.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

apdatandarray

Background subtracted data.

apmaskndarray

Outlier mask.

apbgndarray

Background array.

apv0ndarray

Variance array for data.

gainfloat

The gain factor. Defaults to 1 as the flux should already be in electrons.

windowtypestr; optional

UNUSED. One of {‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’}. The type of window. A flat window will produce a moving average smoothing. Defaults to ‘hanning’.

mint; optional

File number. Defaults to 0.

Returns
dataXarray Dataset

The updated Dataset object.

metaeureka.lib.readECF.MetaClass

The updated metadata object.

loglogedit.Logedit

The updated log.

Notes

History:

  • 2022-07-18, Taylor J Bell

    Added optimize_wrapper to iterate over each frame.

eureka.S3_data_reduction.optspex.profile_gauss(subdata, mask, threshold=10, guess=None, isplots=0)[source]

Construct normalized spatial profile using a Gaussian smoothing function.

Parameters
subdatandarray

Background subtracted data.

maskndarray

Outlier mask.

thresholdfloat; optional

Sigma threshold for outlier rejection while constructing spatial profile. Defaults to 10.

guesslist; optional

UNUSED. The initial guess for the Gaussian parameters. Defaults to None.

isplotsint; optional

The plotting verbosity. Defaults to 0.

Returns
profilendarray

Fitted profile in the same shape as the input data array.

eureka.S3_data_reduction.optspex.profile_meddata(data, mask, meddata, threshold=10, isplots=0)[source]

Construct normalized spatial profile using median of all data frames.

Parameters
datandarray

Unused. Image data.

maskndarray

Unused. Outlier mask.

meddatandarray

The median of all data frames.

thresholdfloat; optional

Unused. Sigma threshold for outlier rejection while constructing spatial profile. Defaults to 10.

isplotsint; optional

Unused. The plotting verbosity. Defaults to 0.

Returns
profilendarray

Fitted profile in the same shape as the input data array.

eureka.S3_data_reduction.optspex.profile_poly(subdata, mask, deg=3, threshold=10, isplots=0)[source]

Construct normalized spatial profile using polynomial fits along the wavelength direction.

Parameters
subdatandarray

Background subtracted data.

maskndarray

Outlier mask.

degint; optional

Polynomial degree, defaults to 3.

thresholdfloat; optional

Sigma threshold for outlier rejection while constructing spatial profile, defaults to 10.

isplotsint; optional

The plotting verbosity. Defaults to 0.

Returns
profilendarray

Fitted profile in the same shape as the input data array.

eureka.S3_data_reduction.optspex.profile_smooth(subdata, mask, threshold=10, window_len=21, windowtype='hanning', isplots=0)[source]

Construct normalized spatial profile using a smoothing function.

Parameters
subdatandarray

Background subtracted data.

maskndarray

Outlier mask.

thresholdfloat; optional

Sigma threshold for outlier rejection while constructing spatial profile.

window_lenint; optional

The dimension of the smoothing window.

windowtypestr; optional

UNUSED. One of {‘flat’, ‘hanning’, ‘hamming’, ‘bartlett’, ‘blackman’}. The type of window. A flat window will produce a moving average smoothing. Defaults to ‘hanning’.

isplotsint; optional

The plotting verbosity. Defaults to 0.

Returns
profilendarray

Fitted profile in the same shape as the input data array.

eureka.S3_data_reduction.optspex.profile_wavelet(subdata, mask, wavelet, numlvls, isplots=0)[source]

This function performs 1D image denoising using BayesShrink soft thresholding.

Parameters
subdatandarray

Background subtracted data.

maskndarray

Outlier mask.

waveletWavelet object or name string

qWavelet to use

numlvlsint

Decomposition levels to consider (must be >= 0).

isplotsint; optional

The plotting verbosity. Defaults to 0.

Returns
profilendarray

Fitted profile in the same shape as the input data array.

References

Chang et al. “Adaptive Wavelet Thresholding for Image Denoising and Compression”, 2000

eureka.S3_data_reduction.optspex.profile_wavelet2D(subdata, mask, wavelet, numlvls, isplots=0)[source]

Construct normalized spatial profile using wavelets

This function performs 2D image denoising using BayesShrink soft thresholding.

Parameters
subdatandarray

Background subtracted data.

maskndarray

Outlier mask.

waveletWavelet object or name string

qWavelet to use

numlvlsint

Decomposition levels to consider (must be >= 0).

isplotsint; optional

The plotting verbosity. Defaults to 0.

Returns
profilendarray

Fitted profile in the same shape as the input data array.

References

Chang et al. “Adaptive Wavelet Thresholding for Image Denoising and Compression”, 2000

eureka.S3_data_reduction.optspex.standard_spectrum(data, apdata, aperr)[source]

Compute the standard box spectrum.

Parameters
dataXarray Dataset

The Dataset object.

apdatandarray

The pixel values in the aperture region.

aperrndarray

The noise values in the aperture region.

Returns
dataXarray Dataset

The updated Dataset object in which the spectrum data will stored.

S3_data_reduction.plots_s3

eureka.S3_data_reduction.plots_s3.add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs)[source]

Add a vertical color bar to an image plot. Taken from: https://stackoverflow.com/ questions/18195758/set-matplotlib-colorbar-size-to-match-graph

eureka.S3_data_reduction.plots_s3.curvature(meta, column_coms, smooth_coms, int_coms, m)[source]

Plot the measured, smoothed, and integer correction from the measured curvature. (Fig 3107)

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

column_coms1D array

Measured center of mass (light) for each pixel column

smooth_coms1D array

Smoothed center of mass (light) for each pixel column

int_coms1D array

Integer-rounded center of mass (light) for each pixel column

mint

The file number.

Notes

History:

  • 2022-07-31 KBS

    Initial version

eureka.S3_data_reduction.plots_s3.drift_2D(data, meta)[source]

Plot the fitted 2D drift. (Fig 3106)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

eureka.S3_data_reduction.plots_s3.driftypos(data, meta)[source]

Plot the spatial jitter. (Fig 3104)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

Notes

History:

  • 2022-07-11 Caroline Piaulet

    First version of this function

eureka.S3_data_reduction.plots_s3.driftywidth(data, meta)[source]

Plot the spatial profile’s fitted Gaussian width. (Fig 3105)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

Notes

History:

  • 2022-07-11 Caroline Piaulet

    First version of this function

eureka.S3_data_reduction.plots_s3.image_and_background(data, meta, log, m)[source]

Make image+background plot. (Figs 3301)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

mint

The file number.

eureka.S3_data_reduction.plots_s3.lc_nodriftcorr(meta, wave_1d, optspec, optmask=None)[source]

Plot a 2D light curve without drift correction. (Fig 3101+3102)

Fig 3101 uses a linear wavelength x-axis, while Fig 3102 uses a linear detector pixel x-axis.

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

wave_1dXarray Dataset

Wavelength array with trimmed edges depending on xwindow and ywindow which have been set in the S3 ecf

optspecXarray Dataset

The optimally extracted spectrum.

optmaskXarray Dataset; optional

A mask array to use if optspec is not a masked array. Defaults to None in which case only the invalid values of optspec will be masked.

eureka.S3_data_reduction.plots_s3.median_frame(data, meta, m)[source]

Plot the cleaned time-median frame. (Fig 3308)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

mint

The file number.

Notes

History:

  • 2022-08-06 KBS

    Initial version

eureka.S3_data_reduction.plots_s3.optimal_spectrum(data, meta, n, m)[source]

Make optimal spectrum plot. (Figs 3302)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

nint

The integration number.

mint

The file number.

eureka.S3_data_reduction.plots_s3.phot_2d_frame(data, meta, m, i)[source]

Plots the 2D frame together with the centroid position, the target aperture and the background annulus. (Fig 3306) If meta.isplots_S3 >= 5, this function will additionally create another figure - Fig 3504 - but it only includes the target area. (Fig 3306 and 3504)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

iint

The integration number.

mint

The file number.

Notes

History:

  • 2022-08-02 Sebastian Zieba

    Initial version

eureka.S3_data_reduction.plots_s3.phot_2d_frame_diff(data, meta)[source]

Plots the difference between to consecutive 2D frames. This might be helpful in order to investigate flux changes due to mirror tilts which have been observed during commissioning. (Fig 3505)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

Notes

History:

  • 2022-08-02 Sebastian Zieba

    Initial version

eureka.S3_data_reduction.plots_s3.phot_2d_frame_oneoverf(data, meta, m, i, flux_w_oneoverf)[source]

Plots the 2D frame with a low vmax so that the background is well visible. The top panel is before the 1/f correction, the lower panel shows the 2D frame after the 1/f correction. The typical “stripy” structure for each row should have been mitigated after the 1/f correction in Stage 3. (Fig 3307)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

iint

The integration number.

mint

The file number.

flux_w_oneoverf2D numpy array

The 2D frame before the 1/f correction

Notes

History:

  • 2022-08-02 Sebastian Zieba

    Initial version

eureka.S3_data_reduction.plots_s3.phot_bg(data, meta)[source]

Plots the background flux as determined by the photometry routine as a function of time. (Fig 3305)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

Notes

History:

  • 2022-08-02 Sebastian Zieba

    Initial version

eureka.S3_data_reduction.plots_s3.phot_centroid(data, meta)[source]

Plots the (x, y) centroids and (sx, sy) the Gaussian 1-sigma half-widths as a function of time. (Fig 3109)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

Notes

History:

  • 2022-08-02 Sebastian Zieba

    Initial version

eureka.S3_data_reduction.plots_s3.phot_centroid_fgc(img, x, y, sx, sy, i, m, meta)[source]

Plot of the gaussian fit to the centroid cutout. (Fig 3503)

Parameters
img2D numpy array

Cutout of the center of the target which is used to determine the centroid position.

xfloat

Centroid position in x direction.

yfloat

Centroid position in y direction.

sxfloat

Gaussian Sigma of Centroid position in x direction.

syfloat

Gaussian Sigma of Centroid position in y direction.

iint

The integration number.

mint

The file number.

metaeureka.lib.readECF.MetaClass

The metadata object.

Notes

History:

  • 2022-08-02 Sebastian Zieba

    Initial version

eureka.S3_data_reduction.plots_s3.phot_lc(data, meta)[source]

Plots the flux as determined by the photometry routine as a function of time. (Fig 3108)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

Notes

History:

  • 2022-08-02 Sebastian Zieba

    Initial version

eureka.S3_data_reduction.plots_s3.phot_npix(data, meta)[source]

Plots the number of pixels within the target aperture and within the background annulus as a function of time. (Fig 3502)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

Notes

History:

  • 2022-08-02 Sebastian Zieba

    Initial version

eureka.S3_data_reduction.plots_s3.profile(meta, profile, submask, n, m)[source]

Plot weighting profile from optimal spectral extraction routine. (Figs 3303)

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

profilendarray

Fitted profile in the same shape as the data array.

submaskndarray

Outlier mask.

nint

The current integration number.

mint

The file number.

eureka.S3_data_reduction.plots_s3.residualBackground(data, meta, m, vmin=-200, vmax=1000)[source]

Plot the median, BG-subtracted frame to study the residual BG region and aperture/BG sizes. (Fig 3304)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

mint

The file number.

vminint; optional

Minimum value of colormap. Default is -200.

vmaxint; optional

Maximum value of colormap. Default is 1000.

Notes

History:

  • 2022-07-29 KBS

    Initial version

eureka.S3_data_reduction.plots_s3.source_position(meta, x_dim, pos_max, m, n, isgauss=False, x=None, y=None, popt=None, isFWM=False, y_pixels=None, sum_row=None, y_pos=None)[source]

Plot source position for MIRI data. (Figs 3103)

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

x_dimint

The number of pixels in the y-direction in the image.

pos_maxfloat

The brightest row.

mint

The file number.

nint

The integration number.

isgaussbool; optional

Used a guassian centring method.

xtype; optional

Unused.

ytype; optional

Unused.

poptlist; optional

The fitted Gaussian terms.

isFWMbool; optional

Used a flux-weighted mean centring method.

y_pixels1darray; optional

The indices of the y-pixels.

sum_row1darray; optional

The sum over each row.

y_posfloat; optional

The FWM central position of the star.

Notes

History:

  • 2021-07-14: Sebastian Zieba

    Initial version.

  • Oct 15, 2021: Taylor Bell

    Tidied up the code a bit to reduce repeated code.

eureka.S3_data_reduction.plots_s3.subdata(meta, i, n, m, subdata, submask, expected, loc)[source]

Show 1D view of profile for each column. (Figs 3501)

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

iint

The column number.

nint

The current integration number.

mint

The file number.

subdatandarray

Background subtracted data.

submaskndarray

Outlier mask.

expectedndarray

Expected profile

locndarray

Location of worst outliers.

S3_data_reduction.s3_reduce

eureka.S3_data_reduction.s3_reduce.reduce(eventlabel, ecf_path=None, s2_meta=None)[source]

Reduces data images and calculates optimal spectra.

Parameters
eventlabelstr

The unique identifier for these data.

ecf_pathstr; optional

The absolute or relative path to where ecfs are stored. Defaults to None which resolves to ‘./’.

s2_metaeureka.lib.readECF.MetaClass; optional

The metadata object from Eureka!’s S2 step (if running S2 and S3 sequentially). Defaults to None.

Returns
metaeureka.lib.readECF.MetaClass

The metadata object with attributes added by S3.

Notes

History:

  • May 2021 Kevin Stevenson

    Initial version

  • October 2021 Taylor Bell

    Updated to allow for inputs from S2

  • July 2022 Caroline Piaulet

    Now computing the y pos and width for each integration + stored in Spec and add diagnostics plots

  • July 2022 Sebastian Zieba

    Added photometry S3

S3_data_reduction.sigrej

eureka.S3_data_reduction.sigrej.sigrej(data, sigma, mask=None, estsig=None, ival=False, axis=0, fmean=False, fstddev=False, fmedian=False, fmedstddev=False)[source]

This function flags outlying points in a data set using sigma rejection.

Parameters
datandarray

Array of points to apply sigma rejection to.

sigmandarray (1D)

1D array of sigma values for each iteration of sigma rejection. Number of elements determines number of iterations.

maskbyte array; optional

Same shape as Data, where 1 indicates the corresponding element in Data is good and 0 indicates it is bad. Only rejection of good-flagged data will be further considered. This input mask is NOT modified in the caller.

estsigndarray; optional

[nsig] array of estimated standard deviations to use instead of calculated ones in each iteration. This is useful in the case of small datasets with outliers, in which case the calculated standard deviation can be large if there is an outlier and small if there is not, leading to rejection of good elements in a clean dataset and acceptance of all elements in a dataset with one bad element. Set any element of estsig to a negative value to use the calculated standard deviation for that iteration.

ivalndarray (2D); optional

(returned) 2D array giving the median and standard deviation (with respect to the median) at each iteration.

axisint; optional

The axis along which to compute the mean/median.

fmeanndarray; optional

(returned) the mean of the accepted data.

fstddevndarray; optional

(returned) the standard deviation of the accepted data with respect to the mean.

fmedianndarray; optional

(returned) the median of the accepted data.

fmedstddevndarray; optional

(returned) the standard deviation of the accepted data with respect to the median.

Returns
rettuple

This function returns a mask of accepted values in the data. The mask is a byte array of the same shape as Data. In the mask, 1 indicates good data, 0 indicates an outlier in the corresponding location of Data. fmean, fstddev, fmedian, and fmedstddev will also be updated and returned if they were passed in. All of these will be packaged together into a tuple.

Notes

SIGREJ flags as outliers points a distance of sigma* the standard deviation from the median. Unless given as a positive value in ESTSIG, standard deviation is calculated with respect to the median, using MEDSTDDEV. For each successive iteration and value of sigma SIGREJ recalculates the median and standard deviation from the set of ‘good’ (not masked) points, and uses these new values in calculating further outliers. The final mask contains a value of 1 for every ‘inlier’ and 0 for every outlying data point.

History:

  • 2005-01-18 statia Statia Luszcz, Cornell. (shl35@cornell.edu)

    Initial version

  • 2005-01-19 statia

    Changed function to return mask, rather than a list of outlying and inlying points, added final statistics keywords

  • 2005-01-20 jh Joe Harrington, Cornell, (jh@oobleck.astro.cornell.edu)

    Header update. Added example.

  • 2005-05-26 jh

    Fixed header typo.

  • 2006-01-10 jh

    Moved definition, added test to see if all elements rejected before last iteration (e.g., dataset is all NaN). Added input mask, estsig.

  • 2010-11-01 patricio (pcubillos@fulbrightmail.org)

    Converted to python.

Examples

Define the N-element vector of sample data.

>>> print(mean(x), stddev(x), median(x), medstddev(x))
1438.47      5311.67      67.0000      5498.10
>>> sr.sigrej(x, [9,3]), ival=ival, fmean=fmean, fmedian=fmedian)

>>> x = np.array([65., 667, 84, 968, 62, 70, 66,
>>>               78, 47, 71, 56, 65, 60])
>>> q,w,e,r,t,y = sr.sigrej(x, [2,1], ival=True, fmean=True,
>>>                         fstddev=True, fmedian=True,
>>>                         fmedstddev=True)

>>> print(q)
[True False True False True True True True True True True True
True]
>>> print(w)
[[66.          65.5       ]
[313.02675604  181.61572819]]
>>> print(e)
65.8181818182
>>> print(r)
10.1174916043
>>> print(t)
65.0
>>> print(y)
10.1538170163
>>> print(fmean, fmedian)
67.0000      67.0000

S3_data_reduction.source_pos

eureka.S3_data_reduction.source_pos.gauss(x, a, x0, sigma, off)[source]

A function to find the source location using a Gaussian fit.

Parameters
xndarray

The positions at which to evaluate the Gaussian.

afloat

The amplitude of the Gaussian.

x0float

The centre point of the Gaussian.

sigmafloat

The standard deviation of the Gaussian.

offfloat

A vertical offset in the Gaussian.

Returns
gaussianndarray

The 1D Gaussian evaluated at the points x, in the same shape as x.

Notes

History:

  • 2021-07-14 Sebastian Zieba

    Initial version

  • 2021-10-15 Taylor Bell

    Separated this into its own function to allow it to be used elsewhere.

eureka.S3_data_reduction.source_pos.source_pos(flux, meta, shdr, m, n, plot=True, guess=None)[source]

Determine the source position for one frames.

Parameters
fluxnp.ma.masked_array (2D)

The 2D image from which to get the source position.

metaeureka.lib.readECF.MetaClass

The metadata object.

shdrastropy.io.fits.header.Header

The science header of the file being processed.

mint

The file number.

nint

The integration number.

plotbool; optional

If True, plot the source position determination. Defaults to True.

guessfloat; optional

The guess at the source position for WFC3 data.

Returns
src_yposint

The central position of the star.

src_ypos_exactfloat

The exact (not rounded) central position of the star.

src_ypos_widthfloat

If gaussian fit, the std of the Gaussian fitted to the image Otherwise, array of zeros.

Notes

History:

  • 2022-07-11 Caroline Piaulet

    Enable recording of the width if the source is fitted with a Gaussian + add an option to fit any integration (not hardcoded to be the first)

  • 2022-07-18, Taylor J Bell

    Tweaked to allow parallelized code if fitting multiple frames.

eureka.S3_data_reduction.source_pos.source_pos_FWM(flux, meta, m, n=0, plot=True)[source]

An alternative function to find the source location using a flux-weighted mean approach.

Parameters
fluxndarray

The 2D array of flux values.

metaeureka.lib.readECF.MetaClass

The metadata object.

mint

The file number.

nint; optional

The integration number. Default is 0 (first integration).

plotbool; optional

If True, plot the source position determination. Defaults to True.

Returns
y_posfloat

The central position of the star.

Notes

History:

  • 2021-06-24 Taylor Bell

    Initial version

  • 2021-07-14 Sebastian Zieba

    Modified

  • 2022-07-11 Caroline Piaulet

    Add option to fit any integration (not hardcoded to be the first)

eureka.S3_data_reduction.source_pos.source_pos_gauss(flux, meta, m, n=0, plot=True)[source]

A function to find the source location using a gaussian fit.

Parameters
fluxndarray

The 3D array of flux values.

metaeureka.lib.readECF.MetaClass

The metadata object.

mint

The file number.

nint; optional

The integration number. Default is 0 (first integration)

plotbool; optional

If True, plot the source position determination. Defaults to True.

Returns
y_posfloat

The central position of the star.

y_widthint

The std of the fitted Gaussian.

Notes

History:

  • 2021-07-14 Sebastian Zieba

    Initial version

  • 2021-10-15 Taylor Bell

    Tweaked to allow for cleaner plots_s3.py

  • 2022-07-11 Caroline Piaulet

    Enable recording of the width if the source is fitted with a Gaussian + add an option to fit any integration (not hardcoded to be the first)

eureka.S3_data_reduction.source_pos.source_pos_max(flux, meta, m, n=0, plot=True)[source]

A simple function to find the brightest row for source location

Parameters
fluxndarray

The 2D array of flux values.

metaeureka.lib.readECF.MetaClass

The metadata object.

mint

The file number.

nint; optional

The integration number. Default is 0 (first integration).

plotbool; optional

If True, plot the source position determination. Defaults to True.

Returns
y_posint

The central position of the star.

Notes

History:

  • 6/24/21 Megan Mansfield

    Initial version

  • 2021-07-14 Sebastian Zieba

    Modified

  • July 11, 2022 Caroline Piaulet

    Add option to fit any integration (not hardcoded to be the first)

eureka.S3_data_reduction.source_pos.source_pos_wrapper(data, meta, log, m, integ=0)[source]

Determine the source position for many frames.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

mint

The file number.

integint or None; optional

The integration number. Default is 0 (first integration). If set to None, the source position and width for each frame will be calculated and stored in data.centroid_y and data.centroid_sy.

Returns
dataXarray Dataset

The updated Dataset object.

metaeureka.lib.readECF.MetaClass

The updated metadata object.

loglogedit.Logedit

The updated log.

Notes

History:

  • 2022-07-18, Taylor J Bell

    Added source_pos_wrapper to allow multiple frames to get source positions in parallel.

S3_data_reduction.straighten

eureka.S3_data_reduction.straighten.find_column_median_shifts(data, meta, m)[source]

Takes the median frame (in time) and finds the center of mass (COM) in pixels for each column. It then returns the needed shift to apply to each column to bring the COM to the center

Parameters
datandarray (2D)

The median of all data frames

metaeureka.lib.readECF.MetaClass

The metadata object.

mint

The file number.

Returns
shiftsndarray (2D)

The shifts to apply to each column to straighten the trace.

new_centerint

The central row of the detector where the trace is moved to.

eureka.S3_data_reduction.straighten.roll_columns(data, shifts)[source]

For each column of each integration, rolls the columns by the values specified in shifts

Parameters
datandarray (3D)

Image data.

shiftsndarray (2D)

The shifts to apply to each column to straighten the trace.

Returns
rolled_datandarray (3D)

Image data with the shifts applied.

eureka.S3_data_reduction.straighten.straighten_trace(data, meta, log, m)[source]

Takes a set of integrations with a curved trace and shifts the columns to bring the center of mass to the middle of the detector (and straighten the trace)

The correction is made by whole pixels (i.e. no fractional pixel shifts) The shifts to be applied are computed once from the median frame and then applied to each integration in the timeseries

Parameters
dataXarray Dataset

The Dataset object in which the fits data will stored.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

mint

The file number.

Returns
dataXarray Dataset

The updated Dataset object with the fits data stored inside.

metaeureka.lib.readECF.MetaClass

The updated metadata object.

S3_data_reduction.wfc3

eureka.S3_data_reduction.wfc3.conclusion_step(data, meta, log)[source]

Convert lists into arrays for saving and applies meta.sum_reads if requested.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The current metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object.

metaeureka.lib.readECF.MetaClass

The updated metadata object.

loglogedit.Logedit

The updated log.

eureka.S3_data_reduction.wfc3.correct_drift2D(data, meta, log, m)[source]

Correct for calculated 2D drift.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

mint

The current file number.

Returns
dataXarray Dataset

The updated Dataset object after 2D drift correction.

metaeureka.lib.readECF.MetaClass

The updated metadata object.

loglogedit.Logedit

The current log.

eureka.S3_data_reduction.wfc3.cut_aperture(data, meta, log)[source]

Select the aperture region out of each trimmed image.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
apdatandarray

The flux values over the aperture region.

aperrndarray

The noise values over the aperture region.

apmaskndarray

The mask values over the aperture region.

apbgndarray

The background flux values over the aperture region.

apv0ndarray

The v0 values over the aperture region.

Notes

History:

  • 2022-06-17, Taylor J Bell

    Initial version, edited to work for HST scanned observations.

eureka.S3_data_reduction.wfc3.difference_frames(data, meta, log)[source]

Compute differenced frames.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object differenced frames.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

eureka.S3_data_reduction.wfc3.fit_bg(dataim, datamask, datav0, datavariance, guess, n, meta, isplots=0)[source]

Fit for a non-uniform background.

Uses the code written for NIRCam, but adds on some extra steps

Parameters
dataimndarray (2D)

The 2D image array.

datamaskndarray (2D)

An array of which data should be masked.

datav0ndarray (2D)

readNoise**2.

datavariancendarray (2D)

Initially an all zeros array.

nint

The current integration.

metaeureka.lib.readECF.MetaClass

The metadata object.

isplotsint; optional

The plotting verbosity, by default False.

Returns
bgndarray (2D)

The fitted background level.

maskndarray (2D)

The updated mask after background subtraction.

datav0ndarray (2D)

readNoise**2+np.mean(bgerr**2)

datavariancendarray (2D)

abs(dataim) / meta.gain + datav0

nint

The current integration number.

eureka.S3_data_reduction.wfc3.flag_bg(data, meta, log)[source]

Outlier rejection of sky background along time axis.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with outlier background pixels flagged.

eureka.S3_data_reduction.wfc3.flatfield(data, meta, log)[source]

Perform flatfielding.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with flatfielding applied.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

eureka.S3_data_reduction.wfc3.get_reference_frames(meta, log)[source]

Process the reference frames for each scan direction and save them in the meta object.

Parameters
metaeureka.lib.readECF.MetaClass

The current metadata object.

Returns
metaeureka.lib.readECF.MetaClass

The updated metadata object.

eureka.S3_data_reduction.wfc3.preparation_step(meta, log)[source]

Perform preperatory steps which require many frames.

Separate imaging and spectroscopy, separate observations into different scan directions, and calculate centroid for each frame.

Parameters
metaeureka.lib.readECF.MetaClass

The current metadata object.

loglogedit.Logedit

The current log.

Returns
metaeureka.lib.readECF.MetaClass

The updated metadata object.

loglogedit.Logedit

The updated log.

eureka.S3_data_reduction.wfc3.read(filename, data, meta, log)[source]

Reads single FITS file from HST’s WFC3 instrument.

Parameters
filenamestr

Single filename to read

dataXarray Dataset

The Dataset object in which the fits data will stored

metaeureka.lib.readECF.MetaClass

The metadata object

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with the fits data stored inside

metaeureka.lib.readECF.MetaClass

The metadata object

loglogedit.Logedit

The current log.

Notes

History:

  • January 2017 Kevin Stevenson

    Initial code as implemented in the WFC3 pipeline

  • 18-19 Nov 2021 Taylor Bell

    Edited and decomposed WFC3 code to integrate with Eureka!

  • May 9, 2022 Kevin Stevenson

    Convert to using Xarray Dataset

eureka.S3_data_reduction.wfc3.separate_direct(meta, log)[source]

Separate out the direct observations from the science observations.

Parameters
metaeureka.lib.readECF.MetaClass

The current metadata object.

loglogedit.Logedit

The current log.

Returns
obstimesndarray

The times of each integration.

CRPIX1float

The CRPIX1 FITS header value.

CRPIX2float

The CRPIX2 FITS header value.

postarg1float

The POSTARG1 FITS header value.

postarg2float

The POSTARG2 FITS header value.

nyint

The NAXIS2 FITS header value.

metaeureka.lib.readECF.MetaClass

The updated metadata object.

loglogedit.Logedit

The updated log.

Raises
AssertionError

All observations cannot be in imaging mode.

AssertionError

All observations cannot be spectroscopic.

AssertionError

Unknown OBSTYPE(s) encountered.

eureka.S3_data_reduction.wfc3.separate_scan_direction(meta, log)[source]

Separate alternating scan directions.

Parameters
obstimesndarray

The times for each integration.

postarg2float

The POSTARG2 FITS header value.

metaeureka.lib.readECF.MetaClass

The current metadata object.

loglogedit.Logedit

The current log.

Returns
metaeureka.lib.readECF.MetaClass

The updated metadata object.

loglogedit.Logedit

The updated log.

S4_generate_lightcurves

S4_generate_lightcurves.drift

eureka.S4_generate_lightcurves.drift.highpassfilt(signal, highpassWidth)[source]

Run a signal through a highpass filter to remove high frequency signals.

This function can be used to compute the continuum of a signal to be subtracted.

Parameters
signalndarray (1D)

1D array of values.

highpassWidthint

The width of the boxcar filter to use.

Returns
smoothed_signalndarray (1D)

An array containing the smoothed signal.

Notes

History:

  • 14 Feb 2018 Lisa Dang

    Written for early version of SPCA

  • 23 Sep 2019 Taylor Bell

    Generalized upon the code

  • 02 Nov 2021 Taylor Bell

    Added to Eureka!

eureka.S4_generate_lightcurves.drift.spec1D(spectra, meta, log, mask=None)[source]

Measures the 1D spectrum drift over all integrations.

Measure spectrum drift over all frames and all non-destructive reads.

Parameters
spectrandarray

2D array of flux values (nint, nx).

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

maskndarray (1D); optional

A mask array to use if spectra is not a masked array. Defaults to None in which case only the invalid values of spectra will be masked.

Returns
drift1dndarray

1D array of spectrum drift values.

driftwidthndarray

1D array of the widths of the Gaussians fitted to the CCFs.

driftmaskndarray

1D masked array, where True is masked.

Notes

History:

  • Dec 2013 KBS

    Written for HST.

  • Jun 2021 KBS

    Updated for JWST.

  • Oct 18, 2021 Taylor Bell

    Minor tweak to cc_spec inputs.

  • Nov 02, 2021 Taylor Bell

    Added option for subtraction of continuum using a highpass filter before cross-correlation.

  • Apr 23, 2022 Kevin Stevenson

    Switched defition of mask to coincide with np.ma definition Removed drift1d and driftmask from meta

  • Jul 11, 2022 Caroline Piaulet

    Added recording of driftwidth

S4_generate_lightcurves.generate_LD

eureka.S4_generate_lightcurves.generate_LD.exotic_ld(meta, spec, log, white=False)[source]

Generate limb-darkening coefficients using the exotic_ld package.

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

specAstreaus object

Data object of wavelength-like arrrays.

loglogedit.Logedit

The open log in which notes from this step can be added.

whitebool; optional

If True, compute the limb-darkening parameters for the white-light light curve. Defaults to False.

Returns
ld_coeffstuple

Linear, Quadratic, Non-linear (3 and 4) limb-darkening coefficients

Notes

History:

  • July 2022, Eva-Maria Ahrer

    Initial version based on exotic_ld documentation.

S4_generate_lightcurves.plots_s4

eureka.S4_generate_lightcurves.plots_s4.binned_lightcurve(meta, log, lc, i, white=False)[source]

Plot each spectroscopic light curve. (Figs 4102)

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

lcXarray Dataset

The Dataset object containing light curve and time data.

iint

The current bandpass number.

whitebool; optional

Is this figure for the additional white-light light curve

eureka.S4_generate_lightcurves.plots_s4.cc_spec(meta, ref_spec, fit_spec, n)[source]

Compare the spectrum used for cross-correlation with the current spectrum (Fig 4301).

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

ref_specndarray (1D)

The reference spectrum used for cross-correlation.

fit_specndarray (1D)

The extracted spectrum for the current integration.

nint

The current integration number.

eureka.S4_generate_lightcurves.plots_s4.cc_vals(meta, vals, n)[source]

Make the cross-correlation strength plot (Fig 4302).

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

valsndarray (1D)

The cross-correlation strength.

nint

The current integration number.

eureka.S4_generate_lightcurves.plots_s4.driftxpos(meta, lc)[source]

Plot the 1D drift/jitter results. (Fig 4103)

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

lcXarray Dataset

The light curve object containing drift arrays.

Notes

History:

  • Jul 11, 2022 Caroline Piaulet

    Edited this function to use the new naming convention for drift

eureka.S4_generate_lightcurves.plots_s4.driftxwidth(meta, lc)[source]

Plot the 1D drift width results. (Fig 4104)

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

lcXarray Dataset

The light curve object containing drift arrays.

Notes

History:

  • Jul 11, 2022 Caroline Piaulet

    Created this function

eureka.S4_generate_lightcurves.plots_s4.lc_driftcorr(meta, wave_1d, optspec_in, optmask=None)[source]

Plot a 2D light curve with drift correction. (Fig 4101)

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

wave_1dndarray

Wavelength array with trimmed edges depending on xwindow and ywindow which have been set in the S3 ecf.

optspec_inXarray DataArray

The optimally extracted spectrum.

optmaskXarray DataArray; optional

A mask array to use if optspec is not a masked array. Defaults to None in which case only the invalid values of optspec will be masked.

S4_generate_lightcurves.s4_genLC

eureka.S4_generate_lightcurves.s4_genLC.genlc(eventlabel, ecf_path=None, s3_meta=None)[source]

Compute photometric flux over specified range of wavelengths.

Parameters
eventlabelstr

The unique identifier for these data.

ecf_pathstr; optional

The absolute or relative path to where ecfs are stored. Defaults to None which resolves to ‘./’.

s3_metaeureka.lib.readECF.MetaClass

The metadata object from Eureka!’s S3 step (if running S3 and S4 sequentially). Defaults to None.

Returns
specAstreaus object

Data object of wavelength-like arrrays.

lcAstreaus object

Data object of time-like arrrays (light curve).

metaeureka.lib.readECF.MetaClass

The metadata object with attributes added by S4.

Notes

History:

  • June 2021 Kevin Stevenson

    Initial version

  • October 2021 Taylor Bell

    Updated to allow for inputs from new S3

  • April 2022 Kevin Stevenson

    Enabled Astraeus

  • July 2022 Caroline Piaulet

    Recording of x (computed in S4) and y (computed in S3) pos drifts and widths in Spec and LC objects

  • July 2022 Sebastian Zieba

    Added photometry S4

eureka.S4_generate_lightcurves.s4_genLC.load_specific_s3_meta_info(meta)[source]

Load the specific S3 MetaClass object used to make this aperture pair.

Parameters
metaeureka.lib.readECF.MetaClass

The current metadata object.

Returns
eureka.lib.readECF.MetaClass

The current metadata object with values from the old MetaClass.

S4_generate_lightcurves.wfc3

eureka.S4_generate_lightcurves.wfc3.sum_reads(spec, lc, meta)[source]

Sum together the non-destructive reads from each file to reduce noise and data volume.

specXarray Dataset

The Dataset object containing the 2D spectra.

lcXarray Dataset

The Dataset object containing light curve and time data.

metaeureka.lib.readECF.MetaClass

The current metadata object.

Returns
specXarray Dataset

The updated spec Dataset object.

lcXarray Dataset

The updated lc Dataset object.

metaeureka.lib.readECF.MetaClass

The updated metadata object.

S5_lightcurve_fitting

S5_lightcurve_fitting.models.BatmanModels

class eureka.S5_lightcurve_fitting.models.BatmanModels.BatmanEclipseModel(**kwargs)[source]

Bases: Model

Eclipse Model

Attributes
flux

A getter for the flux.

parameters

A getter for the parameters.

units

A getter for the unit.s

Methods

eval(**kwargs)

Evaluate the function with the given values.

interp(new_time, **kwargs)

Evaluate the model over a different time array.

plot(time[, components, ax, draw, color, ...])

Plot the model.

update(newparams, **kwargs)

Update the model with new parameter values.

eval(**kwargs)[source]

Evaluate the function with the given values.

Parameters
**kwargsdict

Must pass in the time array here if not already set.

Returns
lcfinalndarray

The value of the model at the times self.time.

class eureka.S5_lightcurve_fitting.models.BatmanModels.BatmanTransitModel(**kwargs)[source]

Bases: Model

Transit Model

Attributes
flux

A getter for the flux.

parameters

A getter for the parameters.

units

A getter for the unit.s

Methods

eval(**kwargs)

Evaluate the function with the given values.

interp(new_time, **kwargs)

Evaluate the model over a different time array.

plot(time[, components, ax, draw, color, ...])

Plot the model.

update(newparams, **kwargs)

Update the model with new parameter values.

eval(**kwargs)[source]

Evaluate the function with the given values.

Parameters
**kwargsdict

Must pass in the time array here if not already set.

Returns
lcfinalndarray

The value of the model at the times self.time.

eureka.S5_lightcurve_fitting.models.BatmanModels.correct_light_travel_time(time, bm_params)[source]

Correct for the finite light travel speed.

This function uses the KeplerOrbit.py file from the Bell_EBM package as that code includes a newer, faster method of solving Kepler’s equation based on Tommasini+2018.

Parameters
timendarray

The times at which observations were collected

bm_paramsbatman.TransitParams

The batman TransitParams object that contains information on the orbit.

Returns
timendarray

Updated times that can be put into batman transit and eclipse functions that will give the expected results assuming a finite light travel speed.

Notes

History:

  • 2022-03-31 Taylor J Bell

    Initial version based on the Bell_EMB KeplerOrbit.py file by Taylor J Bell and the light travel time calculations of SPIDERMAN’s web.c file by Tom Louden

S5_lightcurve_fitting.models.ExpRampModel

class eureka.S5_lightcurve_fitting.models.ExpRampModel.ExpRampModel(**kwargs)[source]

Bases: Model

Model for single or double exponential ramps

Attributes
flux

A getter for the flux.

parameters

A getter for the parameters.

time

A getter for the time.

units

A getter for the unit.s

Methods

eval(**kwargs)

Evaluate the function with the given values.

interp(new_time, **kwargs)

Evaluate the model over a different time array.

plot(time[, components, ax, draw, color, ...])

Plot the model.

update(newparams, **kwargs)

Update the model with new parameter values.

eval(**kwargs)[source]

Evaluate the function with the given values.

Parameters
**kwargsdict

Must pass in the time array here if not already set.

Returns
lcfinalndarray

The value of the model at the times self.time.

property time

A getter for the time.

S5_lightcurve_fitting.models.GPModel

class eureka.S5_lightcurve_fitting.models.GPModel.GPModel(kernel_classes, kernel_inputs, lc, gp_code='george', **kwargs)[source]

Bases: Model

Model for Gaussian Process (GP)

Attributes
flux

A getter for the flux.

parameters

A getter for the parameters.

units

A getter for the unit.s

Methods

eval(fit[, gp])

Compute GP with the given parameters

get_kernel(kernel_name, i[, channel])

Get individual kernels.

interp(new_time, **kwargs)

Evaluate the model over a different time array.

loglikelihood(fit, unc_fit)

Compute log likelihood of GP

plot(time[, components, ax, draw, color, ...])

Plot the model.

set_inputs([normalise])

Setting up kernel inputs as array and standardizing them see e.g.

setup_GP(channel)

Set up GP kernels and GP object.

update(newparams, **kwargs)

Update the model with new parameter values.

eval(fit, gp=None, **kwargs)[source]

Compute GP with the given parameters

Parameters
fiteureka.S5_lightcurve_fitting.models.Model

Current model (i.e. transit model)

gpcelerite.GP, george.GP, or tinygp.GaussianProcess; optional

The current GP object.

**kwargsdict

Must pass in the time array here if not already set.

Returns
lcfinalndarray

Predicted systematics model

get_kernel(kernel_name, i, channel=0)[source]

Get individual kernels.

Parameters
kernel_namestr

The name of the kernel to get.

iint

The kernel number.

channelint; optional

The channel number, by default 0.

Returns
kernel

The requested george, celerite, or tinygp kernel.

Raises
AssertionError

Celerite currently only supports a Matern32 kernel.

loglikelihood(fit, unc_fit)[source]

Compute log likelihood of GP

Parameters
fitndarray

The fitted model.

unc_fitndarray

The fitted uncertainty.

Returns
float

log likelihood of the GP evaluated by george/tinygp/celerite

set_inputs(normalise=False)[source]

Setting up kernel inputs as array and standardizing them see e.g. Evans et al. 2017.

Parameters
normalisebool; optional

Standardize kernels following Evans+2017. Defaults to False.

setup_GP(channel)[source]

Set up GP kernels and GP object.

Parameters
channelint

The current channel number.

Returns
celerite.GP, george.GP, or tinygp.GaussianProcess

The GP object to use for this fit.

S5_lightcurve_fitting.models.KeplerOrbit

class eureka.S5_lightcurve_fitting.models.KeplerOrbit.KeplerOrbit(a=149597870700.0, Porb=None, inc=90.0, t0=0.0, e=0.0, Omega=270.0, argp=90.0, obliq=0.0, argobliq=0.0, Prot=None, m1=1.988409870698051e+30, m2=0.0)[source]

Bases: object

A Keplerian orbit.

Code taken from: https://github.com/taylorbell57/Bell_EBM/blob/master/Bell_EBM/KeplerOrbit.py

Attributes
afloat

The semi-major axis in m.

incfloat

The orbial inclination (in degrees above face-on)

t0float

The linear ephemeris in days.

efloat

The orbital eccentricity.

Protfloat

Body 2’s rotational period in days.

Omegafloat

The longitude of ascending node (in degrees CCW from line-of-sight).

argpfloat

The argument of periastron (in degrees CCW from Omega).

obliqfloat; optional

The obliquity (axial tilt) of body 2 (in degrees toward body 1).

argobliqfloat; optional

The reference orbital angle used for obliq (in degrees from inferior conjunction).

t_perifloat

Time of body 2’s closest approach to body 1.

t_eclfloat

Time of body 2’s eclipse by body 1.

mean_motionfloat

The mean motion in radians.

Methods

FSSI(Y, x, f, fP)

Fast Switch and Spline Inversion method from Tommasini+2018.

FSSI_Eccentric_Inverse(M[, xtol])

Convert mean anomaly to eccentric anomaly using FSSI (Tommasini+2018).

Newton_Eccentric_Inverse(M[, xtol])

Convert mean anomaly to eccentric anomaly using Newton.

distance([t, TA, xtol])

Find the separation between the two bodies.

ea_to_ma(ea)

Convert eccentric anomaly to mean anomaly.

eccentric_anomaly(t[, useFSSI, xtol])

Convert time to eccentric anomaly, numerically.

get_phase(t[, TA])

Get the orbital phase.

get_sop(t)

Calculate the sub-observer longitude and latitude.

get_ssp(t[, TA])

Calculate the sub-stellar longitude and latitude.

mean_anomaly(t)

Convert time to mean anomaly.

plot_orbit()

A convenience routine to visualize the orbit

solve_period()

Find the Keplerian orbital period.

ta_to_ea(ta)

Convert true anomaly to eccentric anomaly.

ta_to_ma(ta)

Convert true anomaly to mean anomaly.

true_anomaly(t[, xtol])

Convert time to true anomaly, numerically.

xyz(t[, xtol])

Find the coordinates of body 2 with respect to body 1.

FSSI(Y, x, f, fP)[source]

Fast Switch and Spline Inversion method from Tommasini+2018.

Parameters
Yndarray

The f(x) values to invert.

xndarray

x values spanning the domain (more values for higher precision).

fcallable

The function f.

fPcallable

The first derivative of the function f with respect to x.

Returns
ndarray

The numerical approximation of f^-(y).

FSSI_Eccentric_Inverse(M, xtol=1e-10)[source]

Convert mean anomaly to eccentric anomaly using FSSI (Tommasini+2018).

Parameters
Mndarray

The mean anomaly in radians.

xtolfloat; optional

tolarance on error in eccentric anomaly. Defaults to 1e-10.

Returns
ndarray

The eccentric anomaly in radians.

Newton_Eccentric_Inverse(M, xtol=1e-10)[source]

Convert mean anomaly to eccentric anomaly using Newton.

Parameters
Mndarray

The mean anomaly in radians.

xtolfloat; optional

tolarance on error in eccentric anomaly. Defaults to 1e-10.

Returns
ndarray

The eccentric anomaly in radians.

property Porb

Orbital period.

Changing this will update Prot if none was provided when the orbit was initialized.

Returns
float

Body 2’s orbital period in days.

distance(t=None, TA=None, xtol=1e-10)[source]

Find the separation between the two bodies.

Parameters
tndarray

The time in days.

TAndarray

The true anomaly in radians (if t and TA are given, only TA will be used).

xtolfloat; optional

tolarance on error in eccentric anomaly (calculated along the way). Defaults to 1e-10.

Returns
ndarray

The separation between the two bodies.

ea_to_ma(ea)[source]

Convert eccentric anomaly to mean anomaly.

Parameters
eandarray

The eccentric anomaly in radians.

Returns
ndarray

The mean anomaly in radians.

eccentric_anomaly(t, useFSSI=None, xtol=1e-10)[source]

Convert time to eccentric anomaly, numerically.

Parameters
tndarray

The time in days.

useFSSIbool; optional

Whether or not to use FSSI to invert Kepler’s equation. Defaults to None which uses FSSI if t.size > 8.

xtolfloat; optional

tolarance on error in eccentric anomaly. Defaults to 1e-10.

Returns
ndarray

The eccentric anomaly in radians.

get_phase(t, TA=None)[source]

Get the orbital phase.

Parameters
tndarray

The time in days.

TAndarray; optional

The true anomaly. Defaults to None which calculates the TA using self.true_anomaly(t).

Returns
ndarray

The orbital phase.

get_sop(t)[source]

Calculate the sub-observer longitude and latitude.

Parameters
tndarray

The time in days.

Returns
list

A list of 2 ndarrays containing the sub-observer longitude and latitude. Each ndarray is in the same shape as t.

get_ssp(t, TA=None)[source]

Calculate the sub-stellar longitude and latitude.

Parameters
tndarray

The time in days.

TAndarray; optional

The true anomaly. Defaults to None which calculates the TA using self.true_anomaly(t).

Returns
list

A list of 2 ndarrays containing the sub-stellar longitude and latitude. Each ndarray is in the same shape as t.

property m1

Body 1’s mass in kg.

If no period was provided when the orbit was initialized, changing this will update the period.

Returns
float

Body 1’s mass in kg.

property m2

Body 2’s mass in kg.

If no period was provided when the orbit was initialized, changing this will update the period.

Returns
float

Body 2’s mass in kg.

mean_anomaly(t)[source]

Convert time to mean anomaly.

Parameters
tndarray

The time in days.

Returns
ndarray

The mean anomaly in radians.

property phase_eclipse

Phase of eclipse.

Read-only.

Returns
float

The orbital phase of eclipse.

property phase_periastron

Phase of periastron.

Read-only.

Returns
float

The orbital phase of periastron.

property phase_transit

Phase of transit.

Read-only.

Returns
float

The orbital phase of transit.

plot_orbit()[source]

A convenience routine to visualize the orbit

Returns
figure

The figure containing the plot.

solve_period()[source]

Find the Keplerian orbital period.

Returns
float

The Keplerian orbital period.

property t_trans

Time of transit.

Read-only.

Returns
float

Time of body 1’s eclipse by body 2.

ta_to_ea(ta)[source]

Convert true anomaly to eccentric anomaly.

Parameters
tandarray

The true anomaly in radians.

Returns
ndarray

The eccentric anomaly in radians.

ta_to_ma(ta)[source]

Convert true anomaly to mean anomaly.

Parameters
tandarray

The true anomaly in radians.

Returns
ndarray

The mean anomaly in radians.

true_anomaly(t, xtol=1e-10)[source]

Convert time to true anomaly, numerically.

Parameters
tndarray

The time in days.

xtolfloat; optional

tolarance on error in eccentric anomaly (calculated along the way). Defaults to 1e-10.

Returns
——-
ndarray

The true anomaly in radians.

xyz(t, xtol=1e-10)[source]

Find the coordinates of body 2 with respect to body 1.

Parameters
tndarray

The time in days.

xtolfloat; optional

tolarance on error in eccentric anomaly (calculated along the way). Defaults to 1e-10.

Returns
list

A list of 3 ndarrays containing the x,y,z coordinate of body 2 with respect to body 1. - The x coordinate is along the line-of-sight. - The y coordinate is perpendicular to the line-of-sight and in the orbital plane. - The z coordinate is perpendicular to the line-of-sight and above the orbital plane

S5_lightcurve_fitting.models.Model

class eureka.S5_lightcurve_fitting.models.Model.CompositeModel(models, **kwargs)[source]

Bases: Model

A class to create composite models.

Attributes
flux

A getter for the flux.

parameters

A getter for the parameters.

units

A getter for the unit.s

Methods

GPeval(fit, **kwargs)

Evaluate the GP model components only.

eval([incl_GP])

Evaluate the model components.

interp(new_time, **kwargs)

Evaluate the model over a different time array.

physeval([interp])

Evaluate the physical model components only.

plot(time[, components, ax, draw, color, ...])

Plot the model.

syseval(**kwargs)

Evaluate the systematic model components only.

update(newparams, **kwargs)

Update parameters in the model components.

GPeval(fit, **kwargs)[source]

Evaluate the GP model components only.

Parameters
fitndarray

The model predictions (excluding the GP).

**kwargsdict

Must pass in the time array here if not already set.

Returns
fluxndarray

The evaluated GP model predictions at the times self.time.

eval(incl_GP=False, **kwargs)[source]

Evaluate the model components.

Parameters
incl_GPbool; optional

Whether or not to include the GP’s predictions in the evaluated model predictions.

**kwargsdict

Must pass in the time array here if not already set.

Returns
fluxndarray

The evaluated model predictions at the times self.time.

physeval(interp=False, **kwargs)[source]

Evaluate the physical model components only.

Parameters
interpbool; optional

Whether to uniformly sample in time or just use the self.time time points. Defaults to False.

**kwargsdict

Must pass in the time array here if not already set.

Returns
fluxndarray

The evaluated physical model predictions at the times self.time if interp==False, else at evenly spaced times between self.time[0] and self.time[-1] with spacing self.time[1]-self.time[0].

syseval(**kwargs)[source]

Evaluate the systematic model components only.

Parameters
**kwargsdict

Must pass in the time array here if not already set.

Returns
fluxndarray

The evaluated systematics model predictions at the times self.time.

update(newparams, **kwargs)[source]

Update parameters in the model components.

Parameters
newparamsndarray

New parameter values.

**kwargsdict

Additional parameters to pass to eureka.S5_lightcurve_fitting.models.Model.update().

class eureka.S5_lightcurve_fitting.models.Model.Model(**kwargs)[source]

Bases: object

Attributes
flux

A getter for the flux.

parameters

A getter for the parameters.

units

A getter for the unit.s

Methods

interp(new_time, **kwargs)

Evaluate the model over a different time array.

plot(time[, components, ax, draw, color, ...])

Plot the model.

update(newparams, **kwargs)

Update the model with new parameter values.

property flux

A getter for the flux.

interp(new_time, **kwargs)[source]

Evaluate the model over a different time array.

Parameters
new_timesequence

The time array.

**kwargsdict

Additional parameters to pass to self.eval().

property parameters

A getter for the parameters.

plot(time, components=False, ax=None, draw=False, color='blue', zorder=inf, share=False, chan=0, **kwargs)[source]

Plot the model.

Parameters
timearray-like

The time axis to use.

componentsbool; optional

Plot all model components.

axMatplotlib Axes; optional

The figure axes to plot on.

drawbool; optional

Whether or not to display the plot. Defaults to False.

colorstr; optional

The color to use for the plot. Defaults to ‘blue’.

zordernumeric; optional

The zorder for the plot. Defaults to np.inf.

sharebool; optional

Whether or not this model is a shared model. Defaults to False.

chanint; optional

The current channel number. Detaults to 0.

**kwargsdict

Additional parameters to pass to plot and self.eval().

Returns
figure

The figure.

property units

A getter for the unit.s

update(newparams, **kwargs)[source]

Update the model with new parameter values.

Parameters
newparamsndarray

New parameter values.

**kwargsdict

Unused by the base eureka.S5_lightcurve_fitting.models.Model class.

S5_lightcurve_fitting.models.PolynomialModel

class eureka.S5_lightcurve_fitting.models.PolynomialModel.PolynomialModel(**kwargs)[source]

Bases: Model

Polynomial Model

Attributes
flux

A getter for the flux.

parameters

A getter for the parameters.

time

A getter for the time.

units

A getter for the unit.s

Methods

eval(**kwargs)

Evaluate the function with the given values.

interp(new_time, **kwargs)

Evaluate the model over a different time array.

plot(time[, components, ax, draw, color, ...])

Plot the model.

update(newparams, **kwargs)

Update the model with new parameter values.

eval(**kwargs)[source]

Evaluate the function with the given values.

Parameters
**kwargsdict

Must pass in the time array here if not already set.

Returns
lcfinalndarray

The value of the model at the times self.time.

property time

A getter for the time.

S5_lightcurve_fitting.models.SinusoidPhaseCurve

class eureka.S5_lightcurve_fitting.models.SinusoidPhaseCurve.SinusoidPhaseCurveModel(transit_model=None, eclipse_model=None, **kwargs)[source]

Bases: Model

A sinusoidal phase curve model

Attributes
flux

A getter for the flux.

parameters

A getter for the parameters.

time

A getter for the time.

units

A getter for the unit.s

Methods

eval(**kwargs)

Evaluate the function with the given values.

interp(new_time, **kwargs)

Evaluate the model over a different time array.

plot(time[, components, ax, draw, color, ...])

Plot the model.

update(newparams, **kwargs)

Update the model with new parameter values.

eval(**kwargs)[source]

Evaluate the function with the given values.

Parameters
**kwargsdict

Must pass in the time array here if not already set.

Returns
lcfinalndarray

The value of the model at the times self.time.

property time

A getter for the time.

update(newparams, **kwargs)[source]

Update the model with new parameter values.

Parameters
newparamsndarray

New parameter values.

**kwargsdict

Additional parameters to pass to eureka.S5_lightcurve_fitting.models.Model.update().

S5_lightcurve_fitting.models.StepModel

class eureka.S5_lightcurve_fitting.models.StepModel.StepModel(**kwargs)[source]

Bases: Model

Model for step-functions in time

Attributes
flux

A getter for the flux.

parameters

A getter for the parameters.

units

A getter for the unit.s

Methods

eval(**kwargs)

Evaluate the function with the given values.

interp(new_time, **kwargs)

Evaluate the model over a different time array.

plot(time[, components, ax, draw, color, ...])

Plot the model.

update(newparams, **kwargs)

Update the model with new parameter values.

eval(**kwargs)[source]

Evaluate the function with the given values.

Parameters
**kwargsdict

Must pass in the time array here if not already set.

Returns
lcfinalndarray

The value of the model at the times self.time.

S5_lightcurve_fitting.fitters

eureka.S5_lightcurve_fitting.fitters.demcfitter(lc, model, meta, log, **kwargs)[source]

Perform sampling using Differential Evolution Markov Chain.

This is an empty placeholder function to be filled later.

Parameters
lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model to fit.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

**kwargsdict

Arbitrary keyword arguments.

Returns
best_modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model after fitting

Notes

History:

  • December 29, 2021 Taylor Bell

    Updated documentation and arguments

eureka.S5_lightcurve_fitting.fitters.dynestyfitter(lc, model, meta, log, **kwargs)[source]

Perform sampling using dynesty.

Parameters
lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model to fit.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

**kwargsdict

Arbitrary keyword arguments.

Returns
best_modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model after fitting

Notes

History:

  • December 29, 2021 Taylor Bell

    Updated documentation. Reduced repeated code.

  • January 7-22, 2022 Megan Mansfield

    Adding ability to do a single shared fit across all channels

  • February 23-25, 2022 Megan Mansfield

    Added log-uniform and Gaussian priors.

  • February 28-March 1, 2022 Caroline Piaulet

    Adding scatter_ppm parameter.

  • Mar 13-Apr 18, 2022 Caroline Piaulet

    Record an astropy table for mean, median, percentiles, +/- 1 sigma, all params

eureka.S5_lightcurve_fitting.fitters.emceefitter(lc, model, meta, log, **kwargs)[source]

Perform sampling using emcee.

Parameters
lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model to fit

metaeureka.lib.readECF.MetaClass

The metadata object

loglogedit.Logedit

The open log in which notes from this step can be added.

**kwargsdict

Arbitrary keyword arguments.

Returns
best_modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model after fitting

Notes

History:

  • December 29, 2021 Taylor Bell

    Updated documentation. Reduced repeated code.

  • January 7-22, 2022 Megan Mansfield

    Adding ability to do a single shared fit across all channels

  • February 23-25, 2022 Megan Mansfield

    Added log-uniform and Gaussian priors.

  • February 28-March 1, 2022 Caroline Piaulet

    Adding scatter_ppm parameter. Added statements to avoid some initial state issues.

  • Mar 13-Apr 18, 2022 Caroline Piaulet

    Record an astropy table for mean, median, percentiles, +/- 1 sigma, all params

eureka.S5_lightcurve_fitting.fitters.group_variables(model)[source]

Group variables into fitted and frozen.

Parameters
modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model to fit

Returns
freenamesnp.array

The names of fitted variables.

freeparsnp.array

The fitted variables.

prior1np.array

The lower bound for constrained variables with uniform/log uniform priors, or mean for constrained variables with Gaussian priors.

prior2np.array

The upper bound for constrained variables with uniform/log uniform priors, or mean for constrained variables with Gaussian priors.

priortypenp.array

Keywords indicating the type of prior for each free parameter.

indep_varsdict

The frozen variables.

Notes

History:

  • December 29, 2021 Taylor Bell

    Moved code to separate function to reduce repeated code.

  • January 11, 2022 Megan Mansfield

    Added ability to have shared parameters

  • February 23-25, 2022 Megan Mansfield

    Added log-uniform and Gaussian priors.

eureka.S5_lightcurve_fitting.fitters.group_variables_lmfit(model)[source]

Group variables into fitted and frozen for lmfit fitter.

Parameters
modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model to fit

Returns
paramlistlist

The fitted variables.

freenamesnp.array

The names of fitted variables.

indep_varsdict

The frozen variables.

Notes

History:

  • December 29, 2021 Taylor Bell

    Moved code to separate function to look similar to other fitters.

eureka.S5_lightcurve_fitting.fitters.initialize_emcee_walkers(meta, log, ndim, lsq_sol, freepars, prior1, prior2, priortype)[source]

Initialize emcee walker starting positions

Parameters
metaeureka.lib.readECF.MetaClass

The meta data object.

loglogedit.Logedit

The open log in which notes from this step can be added.

ndimint

The number of fitted parameters.

lsq_solThe results from the lsqfitter.

The results from the lsqfitter.

freeparslist

The names of the fitted parameters.

prior1list

The list of prior1 values.

prior2list

The list of prior2 values.

priortypelist

The types of each prior (to determine meaning of prior1 and prior2).

Returns
posndarray

The starting position of all walkers.

nwalkersint

The number of walkers (may differ from the requested number if unable to get all walkers within the priors).

Raises
AssertionError

Failed to initialize any walkers within the priors

AssertionError

Failed to initialize enough walkers within the priors

eureka.S5_lightcurve_fitting.fitters.lmfitter(lc, model, meta, log, **kwargs)[source]

Perform a fit using lmfit.

Parameters
lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model to fit.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

**kwargsdict

Arbitrary keyword arguments.

Returns
best_modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model after fitting

Notes

History:

  • December 29, 2021 Taylor Bell

    Updated documentation. Reduced repeated code.

  • February 28-March 1, 2022 Caroline Piaulet

    Adding scatter_ppm parameter.

  • Mar 13-Apr 18, 2022 Caroline Piaulet

    Record an astropy table for parameter values

eureka.S5_lightcurve_fitting.fitters.load_old_fitparams(meta, log, channel, freenames)[source]

Load in the best-fit values from a previous fit.

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

channelint

Unused. The current channel.

freenameslist

The names of the fitted parameters.

Returns
fitted_valuesnp.array

The best-fit values from a previous fit

Raises
AssertionError

The old fit is incompatible with the current fit.

eureka.S5_lightcurve_fitting.fitters.lsqfitter(lc, model, meta, log, calling_function='lsq', **kwargs)[source]

Perform least-squares fit.

Parameters
lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model to fit.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

calling_functionstr

The fitter that is being run (e.g. may be ‘emcee’ if running lsqfitter to initialize emcee walkers). Defailts to ‘lsq’.

**kwargsdict

Arbitrary keyword arguments.

Returns
best_modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model after fitting

Notes

History:

  • December 29-30, 2021 Taylor Bell

    Updated documentation and arguments. Reduced repeated code. Also saving covariance matrix for later estimation of sampler step size.

  • January 7-22, 2022 Megan Mansfield

    Adding ability to do a single shared fit across all channels

  • February 28-March 1, 2022 Caroline Piaulet

    Adding scatter_ppm parameter

  • Mar 13-Apr 18, 2022 Caroline Piaulet

    Record an astropy table for param values

eureka.S5_lightcurve_fitting.fitters.save_fit(meta, lc, model, fitter, results_table, freenames, samples=[])[source]

Save a fit as a txt file as well as the entire chain if provided.

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model to fit.

fitterstr

The current fitter being used.

fit_paramsnp.array

The best-fit values from the current fit.

freenameslist

The list of fitted parameter names.

samplesndarray; optional

The full chain from a sampling method, by default [].

Notes

History:

  • Mar 13-Apr 18, 2022 Caroline Piaulet

    Record an astropy table for mean, median, percentiles, +/- 1 sigma, all params

eureka.S5_lightcurve_fitting.fitters.start_from_oldchain_emcee(meta, log, ndim, channel, freenames)[source]

Restart emcee using the ending point of an old chain.

Parameters
metaeureka.lib.readECF.MetaClass

The meta data object.

loglogedit.Logedit

The open log in which notes from this step can be added.

ndimint

The number of fitted parameters.

channelint

The channel number.

freenameslist

The names of the fitted parameters.

Returns
posndarray

The starting positions for all walkers.

nwalkersint

The number of walkers (may differ from the requested number if unable to get all walkers within the priors).

Raises
AssertionError

The old chain is not compatible with the current fit.

AssertionError

Unable to get enough walkers within the prior range.

S5_lightcurve_fitting.lightcurve

class eureka.S5_lightcurve_fitting.lightcurve.LightCurve(time, flux, channel, nchannel, log, longparamlist, parameters, unc=None, time_units='BJD', name='My Light Curve', share=False, white=False)[source]

Bases: Model

Attributes
flux

A getter for the flux.

parameters

A getter for the parameters.

units

A getter for the unit.s

Methods

fit(model, meta, log[, fitter])

Fit the model to the lightcurve

interp(new_time, **kwargs)

Evaluate the model over a different time array.

plot(meta[, fits])

Plot the light curve with all available fits.

reset()

Reset the results

update(newparams, **kwargs)

Update the model with new parameter values.

fit(model, meta, log, fitter='lsq', **kwargs)[source]

Fit the model to the lightcurve

Parameters
modeleureka.S5_lightcurve_fitting.models.CompositeModel

The model to fit to the data.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

fitterstr

The name of the fitter to use.

**kwargsdict

Arbitrary keyword arguments.

Notes

History:

  • Dec 29, 2021 Taylor Bell

    Updated documentation and reduced repeated code

plot(meta, fits=True)[source]

Plot the light curve with all available fits. (Figs 5103)

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

fitsbool; optional

Plot the fit models. Defaults to True.

reset()[source]

Reset the results

S5_lightcurve_fitting.likelihood

eureka.S5_lightcurve_fitting.likelihood.GP_loglikelihood(model, fit, unc_fit)[source]

Compute likelihood, when model fit includes GP

Parameters
modeleureka.S5_lightcurve_fitting.models.CompositeModel

The model including the GP model

fitndarray

The evaluated model without the GP

unc_fitndarray

The fitted (or initially provided) uncertainty on each data point.

Returns
loglikelihoodfloat

The likelihood of the model.

Notes

History:

  • March 11, 2022 Eva-Maria Ahrer

    moved code from Model.py

eureka.S5_lightcurve_fitting.likelihood.computeRMS(data, maxnbins=None, binstep=1, isrmserr=False)[source]

Compute the root-mean-squared and standard error for various bin sizes.

Parameters
datandarray

The residuals after fitting.

maxnbinsint; optional

The maximum number of bins. Use None to default to 10 points per bin.

binstepint; optional

Bin step size. Defaults to 1.

isrmserrbool

True if return rmserr, else False. Defaults to False.

Returns
rmsndarray

The RMS for each bin size.

stderrndarray

The standard error for each bin size.

binszndarray

The different bin sizes.

rmserrndarray; optional

The uncertainty in the RMS. Only returned if isrmserr==True.

Notes

History:

  • December 29-30, 2021 Taylor Bell

    Moved code to separate file, added documentation.

eureka.S5_lightcurve_fitting.likelihood.computeRedChiSq(lc, log, model, meta, freenames)[source]

Compute the reduced chi-squared value.

Parameters
lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object

loglogedit.Logedit

The open log in which notes from this step can be added.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model to fit

metaeureka.lib.readECF.MetaClass

The metadata object.

freenamesiterable

The names of the fitted parameters.

Returns
chi2redfloat

The reduced chi-squared value.

Notes

History:

  • December 29-30, 2021 Taylor Bell

    Moved code to separate file, added documentation.

  • February, 2022 Eva-Maria Ahrer

    Added GP functionality

eureka.S5_lightcurve_fitting.likelihood.ln_like(theta, lc, model, freenames)[source]

Compute the log-likelihood.

Parameters
thetandarray

The current estimate of the fitted parameters.

lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model to fit.

freenamesiterable

The names of the fitted parameters.

Returns
ln_like_valndarray

The log-likelihood value at the position theta.

Notes

History:

  • December 29-30, 2021 Taylor Bell

    Moved code to separate file, added documentation.

  • January 22, 2022 Megan Mansfield

    Adding ability to do a single shared fit across all channels

  • February, 2022 Eva-Maria Ahrer

    Adding GP likelihood

eureka.S5_lightcurve_fitting.likelihood.lnprior(theta, prior1, prior2, priortype)[source]

Compute the log-prior.

Parameters
thetandarray

The current estimate of the fitted parameters.

prior1ndarray

The lower-bound for uniform/log uniform priors, or mean for normal priors.

prior2ndarray

The upper-bound for uniform/log uniform priors, or std. dev. for normal priors.

priortypendarray

Keywords indicating the type of prior for each free parameter.

Returns
lnprior_probndarray

The log-prior probability value at the position theta.

Notes

History:

  • December 29-30, 2021 Taylor Bell

    Moved code to separate file, added documentation.

  • February 23-25, 2022 Megan Mansfield

    Added log-uniform and Gaussian priors.

eureka.S5_lightcurve_fitting.likelihood.lnprob(theta, lc, model, prior1, prior2, priortype, freenames)[source]

Compute the log-probability.

Parameters
thetandarray

The current estimate of the fitted parameters.

lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The composite model to fit.

prior1ndarray

The lower-bound for uniform/log uniform priors, or mean for normal priors.

prior2ndarray

The upper-bound for uniform/log uniform priors, or std. dev. for normal priors.

priortypendarray

Keywords indicating the type of prior for each free parameter.

freenamesiterable

The names of the fitted parameters.

Returns
ln_prob_valndarray

The log-probability value at the position theta.

Notes

History:

  • December 29-30, 2021 Taylor Bell

    Moved code to separate file, added documentation.

  • February 23-25, 2022 Megan Mansfield

    Added log-uniform and Gaussian priors.

eureka.S5_lightcurve_fitting.likelihood.ptform(theta, prior1, prior2, priortype)[source]

Compute the prior transform for nested sampling.

Parameters
thetandarray

The current estimate of the fitted parameters.

prior1ndarray

The lower-bound for uniform/log uniform priors, or mean for normal priors.

prior2ndarray

The upper-bound for uniform/log uniform priors, or std. dev. for normal priors.

priortypendarray

Keywords indicating the type of prior for each free parameter.

Returns
pndarray

The prior transform.

Notes

History:

  • February 23-25, 2022 Megan Mansfield

    Added log-uniform and Gaussian priors.

eureka.S5_lightcurve_fitting.likelihood.transform_log_uniform(x, a, b)[source]

The log-uniform prior transform function needed for dynesty.

Parameters
xfloat

The position at which to calculate the prior.

afloat

The log lower limit.

bfloat

The log upper limit.

Returns
float

The log-uniform prior transform.

eureka.S5_lightcurve_fitting.likelihood.transform_normal(x, mu, sigma)[source]

The normal prior transform function needed for dynesty.

Parameters
xfloat

The position at which to calculate the prior.

mufloat

The prior mean.

sigmafloat

The prior standard deviation.

Returns
float

The normal prior transform.

eureka.S5_lightcurve_fitting.likelihood.transform_uniform(x, a, b)[source]

The uniform prior transform function needed for dynesty.

Parameters
xfloat

The position at which to calculate the prior.

afloat

The lower limit.

bfloat

The upper limit.

Returns
float

The uniform prior transform.

S5_lightcurve_fitting.limb_darkening_fit

A module to calculate limb darkening coefficients from a grid of model spectra

class eureka.S5_lightcurve_fitting.limb_darkening_fit.LDC(model_grid)[source]

Bases: object

A class to hold all the LDCs you want to run.

Examples

from exoctk.limb_darkening import limb_darkening_fit as lf from exoctk import modelgrid from svo_filters import Filter from pkg_resources import resource_filename fits_files = resource_filename(‘exoctk’, ‘data/core/modelgrid/’) model_grid = modelgrid.ModelGrid(fits_files, resolution=700) ld = lf.LDC(model_grid) bp = Filter(‘WFC3_IR.G141’, n_bins=5) ld.calculate(4000, 4.5, 0.0, ‘quadratic’, bandpass=bp) ld.calculate(4000, 4.5, 0.0, ‘4-parameter’, bandpass=bp) ld.plot(show=True)

Methods

bootstrap_errors(mu_vals, func, coeffs, errors)

Bootstrapping LDC errors.

calculate(Teff, logg, FeH, profile[, ...])

Calculates the limb darkening coefficients for a given synthetic spectrum.

plot([fig, show])

Plot the LDCs

plot_tabs([show])

Plot the LDCs in a tabbed figure

static bootstrap_errors(mu_vals, func, coeffs, errors, n_samples=1000)[source]

Bootstrapping LDC errors.

Parameters
mu_valssequence

The mu values.

funccallable

The LD profile function.

coeffssequence

The coefficients.

errorssequence

The errors on each coeff.

n_samplesint; optional

The number of samples. Defaults to 1000.

Returns
tuple

The lower and upper errors.

calculate(Teff, logg, FeH, profile, mu_min=0.05, ld_min=0.01, bandpass=None, name=None, color=None, **kwargs)[source]

Calculates the limb darkening coefficients for a given synthetic spectrum. If the model grid does not contain a spectrum of the given parameters, the grid is interpolated to those parameters.

Reference for limb-darkening laws: http://www.astro.ex.ac.uk/people/sing/David_Sing/Limb_Darkening.html

Parameters
Teffint

The effective temperature of the model.

loggfloat

The logarithm of the surface gravity.

FeHfloat

The logarithm of the metallicity.

profilestr

The name of the limb darkening profile function to use, including ‘uniform’, ‘linear’, ‘quadratic’, ‘squareroot’, ‘logarithmic’, ‘exponential’, and ‘4-parameter’.

mu_minfloat; optional

The minimum mu value to consider. Defaults to 0.05.

ld_minfloat; optional

The minimum limb darkening value to consider. Defaults to 0.01.

bandpasssvo_filters.svo.Filter(); optional

The photometric filter through which the limb darkening is to be calculated. Defaults to None.

namestr; optional

A name for the calculation. Defaults to None.

colorstr; optional

A color for the plotted result. Defaults to None.

**kwargsdict

Unused.

plot(fig=None, show=False, **kwargs)[source]

Plot the LDCs

Parameters
figmatplotlib.pyplot.figure, bokeh.plotting.figure; optional

An existing figure to plot on. Defaults to None.

showbool; optional

Show the figure. Defaults to False.

**kwargsdict

Additional parameters to be passed into plotting and utils.filter_table().

Returns
figmatplotlib.pyplot.figure, bokeh.plotting.figure; optional

The resulting figure. Only returned if show==False.

plot_tabs(show=False, **kwargs)[source]

Plot the LDCs in a tabbed figure

Parameters
showbool; optional

Show the figure. Defaults to False.

**kwargsdict

Unused.

Returns
finalbokeh.models.widgets.Tabs; optional

The final tabbed figure. Only returned if show==False.

eureka.S5_lightcurve_fitting.limb_darkening_fit.exponential(m, c1, c2)[source]

Exponential limb darkening.

Parameters
mndarray, float

The normalized radial coordinate.

c1float

The first limb darkening coefficient.

c2float

The second limb darkening coefficient.

Returns
ndarray, float

The relative intensity of the star at each position m.

eureka.S5_lightcurve_fitting.limb_darkening_fit.four_parameter(m, c1, c2, c3, c4)[source]

4-parameter limb darkening.

Parameters
mndarray, float

The normalized radial coordinate.

c1float

The first limb darkening coefficient.

c2float

The second limb darkening coefficient.

c3float

The third limb darkening coefficient.

c4float

The fourth limb darkening coefficient.

Returns
ndarray, float

The relative intensity of the star at each position m.

eureka.S5_lightcurve_fitting.limb_darkening_fit.kipping2013(m, c1, c2)[source]

Reparameterized Quadratic (Kipping 2013) limb darkening.

Parameters
mndarray, float

The normalized radial coordinate.

c1float

The first limb darkening coefficient.

c2float

The second limb darkening coefficient.

Returns
ndarray, float

The relative intensity of the star at each position m.

eureka.S5_lightcurve_fitting.limb_darkening_fit.ld_profile(name='quadratic', latex=False, use_gen_ld='batman')[source]

Define the function to fit the limb darkening profile.

Parameters
namestr; optional

The name of the limb darkening profile function to use, including ‘uniform’, ‘linear’, ‘quadratic’, ‘kipping2013’, ‘squareroot’, ‘logarithmic’, ‘exponential’, ‘3-parameter’, and ‘4-parameter’. Defaults to ‘quadratic’.

latexbool; optional

Return the function as a LaTeX formatted string. Defaults to False.

use_gen_ldstr; optional

Which tool will be doing the limb darkening modelling from [‘batman’, ‘exotic-ld’]. Defaults to ‘batman’.

Returns
function

The corresponding function for the given profile. Returned if latex==False.

OR str

A string representation of the corresponding function for the given profile. Returned if latex==True.

References

https://www.cfa.harvard.edu/~lkreidberg/batman/tutorial.html#limb-darkening-options https://exotic-ld.readthedocs.io/en/latest/views/quick_start.html

eureka.S5_lightcurve_fitting.limb_darkening_fit.linear(m, c1)[source]

Linear limb darkening.

Parameters
mndarray, float

The normalized radial coordinate.

c1float

The limb darkening coefficient.

Returns
ndarray, float

The relative intensity of the star at each position m.

eureka.S5_lightcurve_fitting.limb_darkening_fit.logarithmic(m, c1, c2)[source]

Logarithmic limb darkening.

Parameters
mndarray, float

The normalized radial coordinate.

c1float

The first limb darkening coefficient.

c2float

The second limb darkening coefficient.

Returns
ndarray, float

The relative intensity of the star at each position m.

eureka.S5_lightcurve_fitting.limb_darkening_fit.quadratic(m, c1, c2)[source]

Quadratic limb darkening.

Parameters
mndarray, float

The normalized radial coordinate.

c1float

The first limb darkening coefficient.

c2float

The second limb darkening coefficient.

Returns
ndarray, float

The relative intensity of the star at each position m.

eureka.S5_lightcurve_fitting.limb_darkening_fit.square_root(m, c1, c2)[source]

Squareroot limb darkening.

Parameters
mndarray, float

The normalized radial coordinate.

c1float

The first limb darkening coefficient.

c2float

The second limb darkening coefficient.

Returns
ndarray, float

The relative intensity of the star at each position m.

eureka.S5_lightcurve_fitting.limb_darkening_fit.three_parameter(m, c1, c2, c3)[source]

3-parameter limb darkening.

Parameters
mndarray, float

The normalized radial coordinate.

c1float

The first limb darkening coefficient.

c2float

The second limb darkening coefficient.

c3float

The third limb darkening coefficient.

Returns
ndarray, float

The relative intensity of the star at each position m.

eureka.S5_lightcurve_fitting.limb_darkening_fit.uniform(m)[source]

Uniform limb darkening.

Parameters
mndarray, float

The normalized radial coordinate.

Returns
ndarray, float

The relative intensity of the star at each position m.

S5_lightcurve_fitting.modelgrid

A module for creating and managing grids of model spectra

class eureka.S5_lightcurve_fitting.modelgrid.ModelGrid(model_directory, bibcode='2013A & A...553A...6H', names={'FeH': 'PHXM_H', 'Lbol': 'PHXLUM', 'Teff': 'PHXTEFF', 'logg': 'PHXLOGG', 'mass': 'PHXMASS'}, resolution=None, wave_units=Unit('um'), **kwargs)[source]

Bases: object

Creates a ModelGrid object which contains a multi-parameter grid of model spectra and its references

Parameters
pathstr

The path to the directory of FITS files used to create the ModelGrid

refslist, str

The references for the data contained in the ModelGrid

teff_rngtuple

The range of effective temperatures [K]

logg_rngtuple

The range of surface gravities [dex]

FeH_rngtuple

The range of metalicities [dex]

wave_rngarray-like

The wavelength range of the models [um]

n_binsint

The number of bins for the ModelGrid wavelength array

dataastropy.table.Table

The table of parameters for the ModelGrid

inv_filestr

An inventory file to more quickly load the database

Methods

customize([Teff_rng, logg_rng, FeH_rng, ...])

Trims the model grid by the given ranges in effective temperature, surface gravity, and metallicity.

export(filepath, **kwargs)

Export the model with the given parameters to a FITS file at the given filepath.

get(Teff, logg, FeH[, resolution, interp])

Retrieve the wavelength, flux, and effective radius for the spectrum of the given parameters

grid_interp(Teff, logg, FeH[, plot])

Interpolate the grid to the desired parameters

info()

Print a table of info about the current ModelGrid

load_flux([reset])

Retrieve the flux arrays for all models and load into the ModelGrid.array attribute with shape (Teff, logg, FeH, mu, wavelength)

reset()

Reset the current grid to the original state

set_units([wave_units])

Set the wavelength and flux units

customize(Teff_rng=(2300, 8000), logg_rng=(0, 6), FeH_rng=(-2, 1), wave_rng=(<Quantity 0. um>, <Quantity 40. um>), n_bins='')[source]

Trims the model grid by the given ranges in effective temperature, surface gravity, and metallicity. Also sets the wavelength range and number of bins for retrieved model spectra.

Parameters
Teff_rngarray-like; optional

The lower and upper inclusive bounds for the effective temperature (K). Defaults to (2300, 8000).

logg_rngarray-like; optional

The lower and upper inclusive bounds for the logarithm of the surface gravity (dex). Defaults to (0, 6).

FeH_rngarray-like; optional

The lower and upper inclusive bounds for the logarithm of the ratio of the metallicity and solar metallicity (dex). Defaults to (-2, 1).

wave_rngarray-like; optional

The lower and upper inclusive bounds for the wavelength (microns). Defaults to (0*q.um, 40*q.um).

n_binsint; optional

The number of bins for the wavelength axis. Defaults to ‘’.

export(filepath, **kwargs)[source]

Export the model with the given parameters to a FITS file at the given filepath.

Parameters
filepathstr

The path to the target FITS file.

**kwargsdict

Additional parameters to pass to self.get().

get(Teff, logg, FeH, resolution=None, interp=True)[source]

Retrieve the wavelength, flux, and effective radius for the spectrum of the given parameters

Parameters
Teffint

The effective temperature (K)

loggfloat

The logarithm of the surface gravity (dex)

FeHfloat

The logarithm of the ratio of the metallicity and solar metallicity (dex)

resolutionint; optional

The desired wavelength resolution (lambda/d_lambda). Defaults to None.

interpbool; optional

Interpolate the model if possible. Defaults to True.

Returns
spec_dictdict

A dictionary of arrays of the wavelength, flux, and mu values and the effective radius for the given model

grid_interp(Teff, logg, FeH, plot=False)[source]

Interpolate the grid to the desired parameters

Parameters
Teffint

The effective temperature (K)

loggfloat

The logarithm of the surface gravity (dex)

FeHfloat

The logarithm of the ratio of the metallicity and solar metallicity (dex)

plotbool; optional

Plot the interpolated spectrum along with the 8 neighboring grid spectra. Defaults to False.

Returns
grid_pointdict

A dictionary of arrays of the wavelength, flux, and mu values and the effective radius for the given model

info()[source]

Print a table of info about the current ModelGrid

load_flux(reset=False)[source]

Retrieve the flux arrays for all models and load into the ModelGrid.array attribute with shape (Teff, logg, FeH, mu, wavelength)

Parameters
resetbool; optional

Delete the old file and clear the flux attribute. Defaults to False.

reset()[source]

Reset the current grid to the original state

set_units(wave_units=Unit('um'))[source]

Set the wavelength and flux units

Parameters
wave_unitsstr, astropy.units.core.PrefixUnit/CompositeUnit; optional

The wavelength units. Defaults to astropy.units.um.

S5_lightcurve_fitting.plots_s5

eureka.S5_lightcurve_fitting.plots_s5.plot_GP_components(lc, model, meta, fitter, isTitle=True)[source]

Plot the lightcurve + GP model + residuals (Figs 5102)

Parameters
lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The fitted composite model.

metaeureka.lib.readECF.MetaClass

The metadata object.

fitterstr

The name of the fitter (for plot filename).

isTitlebool; optional

Should figure have a title. Defaults to True.

Notes

History:

  • February 28, 2022 Eva-Maria Ahrer

    Written function

  • March 9, 2022 Eva-Maria Ahrer

    Adapted with shared parameters

eureka.S5_lightcurve_fitting.plots_s5.plot_chain(samples, lc, meta, freenames, fitter='emcee', burnin=False, nburn=0, nrows=3, ncols=4, nthin=1)[source]

Plot the evolution of the chain to look for temporal trends. (Figs 5303)

Parameters
samplesndarray

The samples produced by the sampling algorithm.

lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

metaeureka.lib.readECF.MetaClass

The metadata object.

freenamesiterable

The names of the fitted parameters.

fitterstr; optional

The name of the fitter (for plot filename). Defaults to ‘emcee’.

burninbool; optional

Whether or not the samples include the burnin phase. Defaults to False.

nburnint; optional

The number of burn-in steps that are discarded later. Defaults to 0.

nrowsint; optional

The number of rows to make per figure. Defaults to 3.

ncolsint; optional

The number of columns to make per figure. Defaults to 4.

nthinint; optional

If >1, the plot will use every nthin point to help speed up computation and reduce clutter on the plot. Defaults to 1.

Notes

History:

  • December 29, 2021 Taylor Bell

    Moved plotting code to a separate function.

eureka.S5_lightcurve_fitting.plots_s5.plot_corner(samples, lc, meta, freenames, fitter)[source]

Plot a corner plot. (Figs 5501)

Parameters
samplesndarray

The samples produced by the sampling algorithm.

lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

freenamesiterable

The names of the fitted parameters.

metaeureka.lib.readECF.MetaClass

The metadata object.

fitterstr

The name of the fitter (for plot filename).

Notes

History:

  • December 29, 2021 Taylor Bell

    Moved plotting code to a separate function.

eureka.S5_lightcurve_fitting.plots_s5.plot_fit(lc, model, meta, fitter, isTitle=True)[source]

Plot the fitted model over the data. (Figs 5101)

Parameters
lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The fitted composite model.

metaeureka.lib.readECF.MetaClass

The metadata object.

fitterstr

The name of the fitter (for plot filename).

isTitlebool; optional

Should figure have a title. Defaults to True.

Notes

History:

  • December 29, 2021 Taylor Bell

    Moved plotting code to a separate function.

  • January 7-22, 2022 Megan Mansfield

    Adding ability to do a single shared fit across all channels

  • February 28-March 1, 2022 Caroline Piaulet

    Adding scatter_ppm parameter

eureka.S5_lightcurve_fitting.plots_s5.plot_res_distr(lc, model, meta, fitter)[source]

Plot the normalized distribution of residuals + a Gaussian. (Fig 5302)

Parameters
lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The fitted composite model.

metaeureka.lib.readECF.MetaClass

The metadata object.

fitterstr

The name of the fitter (for plot filename).

Notes

History:

  • February 18, 2022 Caroline Piaulet

    Created function

eureka.S5_lightcurve_fitting.plots_s5.plot_rms(lc, model, meta, fitter)[source]

Plot an Allan plot to look for red noise. (Figs 5301)

Parameters
lceureka.S5_lightcurve_fitting.lightcurve.LightCurve

The lightcurve data object.

modeleureka.S5_lightcurve_fitting.models.CompositeModel

The fitted composite model.

metaeureka.lib.readECF.MetaClass

The metadata object.

fitterstr

The name of the fitter (for plot filename).

Notes

History:

  • December 29, 2021 Taylor Bell

    Moved plotting code to a separate function.

  • January 7-22, 2022 Megan Mansfield

    Adding ability to do a single shared fit across all channels

S5_lightcurve_fitting.s5_fit

eureka.S5_lightcurve_fitting.s5_fit.fit_channel(meta, lc, time, flux, chan, flux_err, eventlabel, params, log, longparamlist, time_units, paramtitles, chanrng, ldcoeffs, white=False)[source]

Run a fit for one channel or perform a shared fit.

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

lcXarray Dataset

The light curve object.

timendarray

The time array.

fluxndarray

The flux array.

chanint

The current channel number.

flux_errndarray

The uncertainty on each data point.

eventlabelstr

The unique identifier for this analysis.

paramseureka.lib.readEPF.Parameters

The Parameters object containing the fitted parameters and their priors.

loglogedit.Logedit

The current log in which to output messages from this current stage.

longparamlistlist

The long list of all parameters relevant to this fit.

time_unitsstr

The units of the time array.

paramtitleslist

The names of the fitted parameters.

chanrngint

The number of fitted channels.

ldcoeffslist

Limb-darkening coefficients if used from Stage 4, otherwise None.

whitebool; optional

Is this a white-light fit? Defaults to False.

Returns
metaeureka.lib.readECF.MetaClass

The updated metadata object.

eureka.S5_lightcurve_fitting.s5_fit.fitlc(eventlabel, ecf_path=None, s4_meta=None)[source]

Fits 1D spectra with various models and fitters.

Parameters
eventlabelstr

The unique identifier for these data.

ecf_pathstr; optional

The absolute or relative path to where ecfs are stored. Defaults to None which resolves to ‘./’.

s4_metaeureka.lib.readECF.MetaClass; optional

The metadata object from Eureka!’s S4 step (if running S4 and S5 sequentially). Defaults to None.

Returns
metaeureka.lib.readECF.MetaClass

The metadata object with attributes added by S5.

Notes

History:

  • November 12-December 15, 2021 Megan Mansfield

    Original version

  • December 17-20, 2021 Megan Mansfield

    Connecting S5 to S4 outputs

  • December 17-20, 2021 Taylor Bell

    Increasing connectedness of S5 and S4

  • January 7-22, 2022 Megan Mansfield

    Adding ability to do a single shared fit across all channels

  • January - February, 2022 Eva-Maria Ahrer

    Adding GP functionality

  • April 2022 Kevin Stevenson

    Enabled Astraeus

eureka.S5_lightcurve_fitting.s5_fit.load_specific_s4_meta_info(meta)[source]

Load the specific S4 MetaClass object used to make this aperture pair.

Parameters
metaeureka.lib.readECF.MetaClass

The current metadata object.

Returns
eureka.lib.readECF.MetaClass

The current metadata object with values from the old MetaClass.

eureka.S5_lightcurve_fitting.s5_fit.make_longparamlist(meta, params, chanrng)[source]

Make a long list of all relevant parameters.

Parameters
metaeureka.lib.readECF.MetaClass

The current metadata object.

paramseureka.lib.readEPF.Parameters

The Parameters object containing the fitted parameters and their priors.

chanrngint

The number of fitted channels.

Returns
longparamlistlist

The long list of all parameters relevant to this fit.

paramtitleslist

The names of the fitted parameters.

S5_lightcurve_fitting.simulations

eureka.S5_lightcurve_fitting.simulations.simulate_lightcurve(target, snr=1000.0, npts=1000, nbins=10, radius=None, ldcs=('quadratic', [0.1, 0.1]), plot=False)[source]

Simulate lightcurve data for the given target exoplanet

Parameters
targetstr

The name of the target to simulate.

snrfloat; optional

The signal to noise to use. Defaults to 1000.

nptsint; optional

The number of points in each lightcurve. Defaults to 1000.

nbinsint; optional

The number of lightcurves. Defaults to 10.

radiusarray-like, float; optional

The radius or radii value(s) to use. Defaults to None which will use the literature Rp/Rs value if found or 0.1 if not.

ldcssequence; optional

The limb darkening profile name and coefficients. Defaults to (‘quadratic’, [0.1, 0.1]).

plotbool; optional

If True, plot the figure. Defaults to False.

Returns
tuple

The time, flux, uncertainty, and transit parameters

S5_lightcurve_fitting.utils

A module for utility funtions

eureka.S5_lightcurve_fitting.utils.build_target_url(target_name)[source]

Build restful api url based on target name.

Parameters
target_namestr

The name of the target transit.

Returns
target_urlstr
eureka.S5_lightcurve_fitting.utils.calc_zoom(R_f, arr)[source]

Calculate the zoom factor required to make the given array into the given resolution.

Parameters
R_fint

The desired final resolution of the wavelength array.

arrarray-like

The array to zoom.

Returns
zfloat

The zoom factor

eureka.S5_lightcurve_fitting.utils.color_gen(colormap='viridis', key=None, n=10)[source]

Color generator for Bokeh plots.

Parameters
colormapstr, sequence

The name of the color map.

keystr; optional

The palette key. Defaults to None which uses the first palette key.

nint; optional

If palette is callable, the argument to that function. Defaults to 10.

Returns
generator

A generator for the color palette.

eureka.S5_lightcurve_fitting.utils.download_exoctk_data(download_location='/home/docs')[source]

Retrieves the exoctk_data materials from Box, downloads them to the user’s local machine, uncompresses the files, and arranges them into an exoctk_data directory.

Parameters
download_locationstr; optional

The path to where the ExoCTK data package will be downloaded. The default setting is the user’s $HOME directory.

eureka.S5_lightcurve_fitting.utils.filter_table(table, **kwargs)[source]

Retrieve the filtered rows.

Parameters
tableastropy.table.Table, pandas.DataFrame

The table to filter.

**kwargsdict
paramstr

The parameter to filter by, e.g. ‘Teff’.

valuestr, float, int, sequence

The criteria to filter by, which can be single valued like 1400 or a range with operators [<,<=,>,>=], e.g. (‘>1200’,’<=1400’).

Returns
astropy.table.Table, pandas.DataFrame

The filtered table.

eureka.S5_lightcurve_fitting.utils.find_closest(axes, points, n=1, values=False)[source]

Find the n-neighboring elements of a given value in an array.

Parameters
axeslist, np.array

The array(s) to search.

pointsarray-like, float

The point(s) to search for.

nint; optional

The number of values to the left and right of the points. Defaults to 1.

valuesbool; optional

Defaults to False.

Returns
np.ndarray

The n-values to the left and right of ‘points’ in ‘axes’.

eureka.S5_lightcurve_fitting.utils.get_canonical_name(target_name)[source]

Get ExoMAST prefered name for exoplanet.

Parameters
target_namestr

The name of the target transit.

Returns
canonical_namestr
eureka.S5_lightcurve_fitting.utils.get_env_variables()[source]

Returns a dictionary containing various environment variable information.

Returns
env_variablesdict

A dictionary containing various environment variable data

eureka.S5_lightcurve_fitting.utils.get_target_data(target_name)[source]

Send request to exomast restful api for target information.

Parameters
target_namestr

The name of the target transit

Returns
target_datajson

json object with target data.

eureka.S5_lightcurve_fitting.utils.interp_flux(mu, flux, params, values)[source]

Interpolate a cube of synthetic spectra for a given index of mu.

Parameters
muint

The index of the (Teff, logg, FeH, mu, wavelength) data cube to interpolate.

fluxnp.ndarray

The 5D data array.

paramslist

A list of each free parameter range.

valueslist

A list of each free parameter values.

Returns
tuple

The array of new flux values, and the generators.

eureka.S5_lightcurve_fitting.utils.rebin_spec(spec, wavnew, oversamp=100, plot=False)[source]

Rebin a spectrum to a new wavelength array while preserving the total flux.

Parameters
specarray-like

The wavelength and flux to be binned.

wavenewarray-like

The new wavelength array.

oversampint; optional

The oversampling factor. Defaults to 100.

plotbool; optional

Unused. Defaults to False.

Returns
np.ndarray

The rebinned flux

eureka.S5_lightcurve_fitting.utils.writeFITS(filename, extensions, headers=())[source]

Write some data to a new FITS file.

Parameters
filenamestr

The filename of the output FITS file.

extensionsdict

The extension name and associated data to include. in the file

headersarray-like; optional

The (keyword, value, comment) groups for the PRIMARY header extension. Defaults to ().

S6_planet_spectra

S6_planet_spectra.plots_s6

eureka.S6_planet_spectra.plots_s6.plot_spectrum(meta, model_x=None, model_y=None, y_scalar=1, ylabel='$R_{\\rm p}/R_{\\rm *}$', xlabel='Wavelength ($\\mu$m)', scaleHeight=None, planet_R0=None)[source]

Plot the planetary transmission or emission spectrum.

Parameters
metaeureka.lib.readECF.MetaClass

The meta data object.

model_xndarray; optional

The wavelength array for the model to plot, by default None

model_yndarray; optional

The transmission or emission spectrum from the model, by default None

y_scalarint; optional

The multiplier for the y-axis (100=%, 1e6=ppm), by default 1

ylabelstr; optional

The y-axis label, by default r’{rm p}/R_{rm *}$’

xlabelstr; optional

The x-axis label, by default r’Wavelength ($mu)’

scaleHeightfloat; optional

The planetary atmospheric scale height, by default None

planet_R0float; optional

The reference radius for the scale height, by default None

S6_planet_spectra.s6_spectra

eureka.S6_planet_spectra.s6_spectra.compute_scale_height(meta, log)[source]

Compute the atmospheric scale height for a planet.

Parameters
metaeureka.lib.readECF.MetaClass

The current meta data object.

loglogedit.Logedit

The open log in which notes from this step can be added.

Returns
metaeureka.lib.readECF.MetaClass

The updated meta data object.

eureka.S6_planet_spectra.s6_spectra.compute_timescale(meta)[source]

Convert the fitted r1 or r4 value to a timescale.

Parameters
metaeureka.lib.readECF.MetaClass

The current meta data object.

Returns
metaeureka.lib.readECF.MetaClass

The updated meta data object.

eureka.S6_planet_spectra.s6_spectra.compute_transit_depth(meta)[source]

Convert the fitted rp values to transit depth.

Parameters
metaeureka.lib.readECF.MetaClass

The current meta data object.

Returns
metaeureka.lib.readECF.MetaClass

The updated meta data object.

eureka.S6_planet_spectra.s6_spectra.load_model(meta, log, x_unit)[source]

Load in a model to plot above/below the fitted data.

Parameters
metaeureka.lib.readECF.MetaClass

The current meta data object.

loglogedit.Logedit

The open log in which notes from this step can be added.

x_unitstr

The astropy.units unit that will be used in the plot.

Returns
metaeureka.lib.readECF.MetaClass

The updated meta data object.

Raises
AssertionError

Unknown conversion between y_param and model_y_param.

eureka.S6_planet_spectra.s6_spectra.load_specific_s5_meta_info(meta)[source]

Load in the MetaClass object from the particular aperture pair being used.

Parameters
metaeureka.lib.readECF.MetaClass

The current meta data object.

Returns
metaeureka.lib.readECF.MetaClass

The current meta data object with values from earlier stages.

eureka.S6_planet_spectra.s6_spectra.parse_s5_saves(meta, log, fit_methods, channel_key='shared')[source]

Load in an S5 save file.

Parameters
metaeureka.lib.readECF.MetaClass

The current meta data object.

loglogedit.Logedit

The open log in which notes from this step can be added.

fit_methodslist

The fitting methods used in S5.

channel_keystr; optional

A string describing the current channel (e.g. ch0), by default ‘shared’.

Returns
medians

The best-fit values from S5.

errs

The uncertainties from a sampling algorithm like dynesty or emcee.

eureka.S6_planet_spectra.s6_spectra.parse_unshared_saves(meta, log, fit_methods)[source]

Load in the many S5 save files for an unshared fit.

Parameters
metaeureka.lib.readECF.MetaClass

The current meta data object.

loglogedit.Logedit

The open log in which notes from this step can be added.

fit_methodslist

The fitting methods used in S5.

Returns
metaeureka.lib.readECF.MetaClass

The updated meta data object.

eureka.S6_planet_spectra.s6_spectra.plot_spectra(eventlabel, ecf_path=None, s5_meta=None)[source]

Gathers together different wavelength fits and makes transmission/emission spectra.

Parameters
eventlabelstr

The unique identifier for these data.

ecf_pathstr; optional

The absolute or relative path to where ecfs are stored. Defaults to None which resolves to ‘./’.

s5_metaeureka.lib.readECF.MetaClass; optional

The metadata object from Eureka!’s S5 step (if running S5 and S6 sequentially). Defaults to None.

Returns
metaeureka.lib.readECF.MetaClass

The metadata object with attributes added by S6.

Notes

History:

  • Feb 14, 2022 Taylor Bell

    Original version

eureka.S6_planet_spectra.s6_spectra.roundToDec(x, nDec=2)[source]

Round a value to a requested number of decimals.

Parameters
xnumerical type

A float or int to be rounded.

nDecint

The number of decimals desired, by default 2.

Returns
outputstr

x formatted as a string with the requested number of decimals.

Notes

History:

  • 2022-08-22, Taylor J Bell

    Imported code written for SPCA, and optimized for Python3.

eureka.S6_planet_spectra.s6_spectra.roundToSigFigs(x, sigFigs=2)[source]

Round a value to a requested number of significant figures.

Parameters
xnumerical type

A float or int to be rounded.

sigFigsint; optional

The number of significant figures desired, by default 2.

Returns
nDecint

The number of decimals corresponding to sigFigs where nDec = -1 for a value rounded to the ten’s place (e.g. 101 -> 100 if nDec = -1).

outputstr

x formatted as a string with the requested number of significant figures.

Notes

History:

  • 2022-08-22, Taylor J Bell

    Imported code written for SPCA, and optimized for Python3.

eureka.S6_planet_spectra.s6_spectra.save_table(meta, log)[source]

Clean y_param for filenames and save the table of values.

Also calls transit_latex_table().

Parameters
metaeureka.lib.readECF.MetaClass

The current meta data object.

loglogedit.Logedit

The open log in which notes from this step can be added.

eureka.S6_planet_spectra.s6_spectra.transit_latex_table(meta, log)[source]

Write a nicely formatted LaTeX table for each plotted value.

Parameters
metaeureka.lib.readECF.MetaClass

The current meta data object.

loglogedit.Logedit

The open log in which notes from this step can be added.

lib

lib.apphot

eureka.lib.apphot.apphot(meta, image, ctr, photap, skyin, skyout, betahw, targpos, mask=None, imerr=None, skyfrac=0.0, med=False, nochecks=False, expand=1, order=1, aperr=False, nappix=False, skylev=False, skyerr=False, nskypix=False, nskyideal=False, status=False, isbeta=False, betaper=False)[source]

Perform aperture photometry on the input image.

Parameters
image2D ndimage

Float array containing object to measure.

ctr2 elements tuple

x,y location of object’s center.

photapScalar

Size of photometry apperture in pixels.

skyinScalar

Inner sky annulus edge, in pixels.

skyoutScalar

Outer sky annulus edge, in pixels.

betahwScalar

Half-width of box size around centroid for beta calculation.

targpos2 elements tuple

x,y location of object’s center calculated from mean image.

mask2D ndimage

Byte array giving status of corresponding pixel in Image: bad pixel=0, good pixel=1. Default: all pixels are good. Same shape as image.

imerr2D ndimage

Error estimate for each pixel in the image. Suggest sqrt(image/flat/gain+rdnoise^2), with proper adjustment if a sky, dark, or bias frame has been removed. Same shape as image.

skyfracScalar

Minimum fraction of sky pixels required to be good. Must be in range 0 < skyfrac < 1.

medBoolean

If True use median rather than mean in sky level estimation.

nochecksBoolean

Set to True to skip checks of input sanity.

expandInteger scalar

Positive integer factor by which to blow up image, for more accurate aperture arithmetic. If expand=5, each pixel becomes a 5x5 block of pixels. If the pixel is on the edge of an aperture or annulus radius, some of the 5x5 block will be counted and some will not.

orderInteger scalar

Set order to 0 to do nearest-neighbor interpolation if expand. Default: 1, bilinear interpolation.

aperrBoolean

Set to True to return flux error.

nappixBoolean

Set to True to return number of total pixels in aperture.

skylevBoolean

Set to True to return the sky level.

skyerrBoolean

Set to True to return the error in the sky level.

nskypixboolean

Set to True to return the number of good pixels in sky annulus.

nskyideal: Boolean

Set to True to return the number of pixels that should be in sky annulus.

statusBoolean

Set to True to return a status flag. If status = 0, result is good. Bits: 0 = there are NaN(s) in the photometry aperture 1 = there are masked pixel(s) in the photometry aperture 2 = the aperture is off the edge of the image 3 = a fraction less than skyfrac of the sky annulus pixels is in the image and not masked

isbetaboolean

If True photometric extraction aperture scales with noise pixel parameter (beta).

betaperScalar

Returns aperture size used for beta.

Returns
This function returns the flux within Photap pixels of
[Cx,Cy], after subtracting the average per-pixel flux in the
sky annulus. See POCEDURE for details of the calculation.

Notes

The sky level is the mean, error-weighted mean (if errors are present), or median (if /med is set) of the non-masked Image pixels in the sky annulus. NaN values and values whose errors are zero (for the error-weighted mean) are not included in the average. No flagging is done if these values are found in the sky annulus. SKYERR is the error in the mean, even for the median calculation. Errors in the median can only be estimated using the compute-intensive bootstrap Monte-Carlo method.

The sky value is subtracted from the Image. The photometric flux is then the total of Image pixels in the aperture, whether in the Mask or not. NaN values are not included in the calculation, and set the STATUS flag. It would be much better for the user to pass an interpolated image instead.

For expansion, it is recommended to use bilinear interpolation, which is flux-conserving:

sz = [50, 50] expand = 4 a = dblarr(sz) a[25, 25] = 1 b = rebin(a, expand * sz) / expand^2 print, total(b) 1.0000000 a[25, 26] = 1 b = rebin(a, expand * sz) / expand^2 print, total(b) 2.0000000 a[26, 26] = 3 b = rebin(a, expand * sz) / expand^2 print, total(b) 5.0000000

Of course, pixels on the high-indexed edge will not follow that. Neither will integer-arithmetic images, particularly at low integer values (such as masks).

If either the entire sky annulus or the entire aperture is bad or filled with NaNs, the function sets a flag and returns NaN for all incalculable values.

History:

  • 27-02-2004: Joseph Harrington, Cornell. jh@oobleck.astro.cornell.edu

    Initial version

  • 18-03-2004: jh

    Added nochecks keyword.

  • 19-03-2004: jh

    Added error calculation.

  • 13-01-2005: jh

    Fixed header comment. Added NAN keyword.

  • 14-10-2005: jh

    Found and fixed major bug in sky mask calculation (needed parens around subtraction next to mask multiplication). Added skyfrac.

  • 07-11-2005: shl35

    Added STATUS keyword, error-weighted sky mean.

  • 16-11-2005: jh

    Rewrote, using meanerr. Fixed major bug in error calc. Added scaling and test cases.

  • 24-11-2005: jh

    Return NAPPIX, NSKYPIX, NSKYIDEAL (all renamed).

  • 30-11-2005: jh

    Changed NAPPIX, NSKYPIX, NSKYIDEAL to give fractional, unexpanded pixels.

  • 21-07-2010: patricio

    Converted to python.

Examples

This being one of my most important routines, and being also complex, the following examples are also its test suite. Any changes should produce exactly the same numerical results. These tests should also be available in the accompanying file apphottest.pro.

eureka.lib.apphot.apphot_status(data)[source]

Prints a warning if aperture step had errors. Bit flag definitions from the apphot function:

statnan = 2 ** 0
statbad = 2 ** 1
statap = 2 ** 2
statsky = 2 ** 3
E.g., If the flag is 6 then is was created by a flag in
statap and statbad as 2 ** 2 + 2 ** 1 = 6.
This function is converting the flags back to binary
and checking which flags were triggered.
Parameters
dataXarray Dataset

The Dataset object.

lib.astropytable

eureka.lib.astropytable.readtable(filename)[source]

Read in a saved ECSV file.

Parameters
filenamestr

The fully qualified filename of the file to read.

Returns
astropy.table.QTable

The table previously saved by savetable_S5 or savetable_S6.

eureka.lib.astropytable.savetable_S5(filename, time, wavelength, bin_width, lcdata, lcerr, model, residuals)[source]

Save the results from Stage 5 as an ECSV file.

Parameters
filenamestr

The fully qualified filename that the results will be stored in.

timendarray (1D)

The times for each data point.

wavelengthndarray (1D)

The wavelengths of each data point.

bin_widthndarray (1D)

The width of each wavelength bin.

lcdatandarray (1D)

The normalized flux measurements for each data point.

lcerrndarray (1D)

The normalized uncertainties for each data point.

modelndarray (1D)

The predicted values from the fitted model.

residualsndarray (1D)

The residuals from lcdata - model.

Raises
ValueError

There was a shape mismatch between your arrays

eureka.lib.astropytable.savetable_S6(filename, key, wavelength, bin_width, value, error)[source]

Save the results from Stage 6 as an ECSV.

Parameters
filenamestr

The fully qualified filename that the results will be stored in.

keystr

The parameter being saved.

wavelengthndarray (1D)

The wavelengths of each data point.

bin_widthndarray (1D)

The width of each wavelength bin.

valuendarray (1D)

The fitted value at each wavelength.

errorndarray (1D)

The uncertainty on each value.

Raises
ValueError

There was a shape mismatch between your arrays

lib.centerdriver

eureka.lib.centerdriver.centerdriver(method, data, guess, trim, radius, size, mask=None, uncd=None, fitbg=1, maskstar=True, expand=5.0, psf=None, psfctr=None, i=None, m=None, meta=None)[source]

Use the center method to find the center of a star in data, starting from position guess.

Parameters
method: string

Name of the centering method to use.

data: 2D ndarray

Array containing the star image.

guess: 2 elements 1D array

y, x initial guess position of the target.

trim: integer

Semi-lenght of the box around the target that will be trimmed.

radius: float

least asymmetry parameter. See err_fasym_c.

size: float

least asymmetry parameter. See err_fasym_c.

mask: 2D ndarray

A mask array of bad pixels. Same shape of data.

uncd: 2D ndarray

An array containing the uncertainty values of data. Same shape of data.

Returns
A y,x tuple (scalars) with the coordinates of center of the target
in data.

Notes

History:

23-11-2010 patricio Written by Patricio Cubillos

pcubillos@fulbrightmail.org

lib.centroid

eureka.lib.centroid.ctrgauss(data, guess=None, mask=None, indarr=None, trim=None)[source]

Finds and records the stellar centroid of a set of images by fitting a two dimensional Gaussian function to the data.

It does not find the average centroid, but instead records the centroid of each image in the supplied frame parameters array at the supplied indices. The frame parameters array is assumed to have the same number of rows as the number of frames in the data cube.

Parameters
datandarray (2D)

The stellar image.

guessarray_like

The initial guess of the position of the star. Has the form (y, x) of the guess center.

maskndarray (2D)

The stellar image.

indarrarray_like

The indices of the x and y center columns of the frame parameters and the width index. Defaults to 4, 5, and 6 respectively.

trimScalar (positive)

If trim!=0, trims the image in a box of 2*trim pixels around the guess center. Must be !=0 for ‘col’ method.

Returns
centery, x

The updated frame parameters array. Contains the centers of each star in each image and their average width.

Notes

History:

  • 2010-06-23, Patricio E. Cubillos

    Adapted to POET from Chris’ routines.

  • 2009-10-30, Christopher J. Campo

    Initial version.

eureka.lib.centroid.ctrguess(data, mask=None, guess=None)[source]

Calculates crude initial guesses of parameters required for Gaussian centroiding of stellar images.

Speciffically, this function guesses the flux of the center of a star, the array indices of this location, and a rough guess of the width of the associated PSF. This method is not robust to bad pixels or any other outlying values.

Parameters
datandarray (2D)

The image in the form of a 2D array containing the star to be centroided. Works best if this is a small subarray of the actual data image.

maskndarray (2D)

The image in the form of a 2D array containing the star to be centroided. Works best if this is a small subarray of the actual data image.

Returns
ghtscalar

The rough estimate of the height (or max flux) of the stars PSF.

gwdtuple

The guessed width of the PSF, in the form (gwdy, gwdx) where gwdy and gwdx are the y and x widths respectively.

gcttuple

The guessed center of the PSF, in the form (gcty, gctx) where gcty and gctx are the y and x center indices respectively.

Notes

Logic adapted from gaussian.py

History:

  • 2009-10-27, Christopher Campo

    Initial Version

lib.clipping

eureka.lib.clipping.clip_outliers(data, log, wavelength, wavelength_units='microns', mask=None, sigma=10, box_width=5, maxiters=5, boundary='extend', fill_value='mask', verbose=False)[source]

Find outliers in 1D time series.

Be careful when using this function on a time-series with known astrophysical variations. The variable box_width should be set to be significantly smaller than any astrophysical variation timescales otherwise these signals may be clipped.

Parameters
datandarray (1D)

The input array in which to identify outliers

loglogedit.Logedit

The open log in which notes from this step can be added.

wavelengthfloat

The wavelength currently under consideration.

wavelength_unitsfloat

The wavelength units currently under consideration.

maskndarray (1D); optional

A mask array to use if data is not a masked array. Defaults to None in which case only the invalid values of data will be masked.

sigmafloat; optional

The number of sigmas a point must be from the rolling mean to be considered an outlier. Defaults to 10.

box_widthint; optional

The width of the box-car filter (used to calculated the rolling median) in units of number of data points. Defaults to 5.

maxitersint; optional

The number of iterations of sigma clipping that should be performed. Defaults to 5.

boundarystr; optional

The boundary argument to pass to astropy.convolution.convolve. Defaults to ‘extend’.

fill_valuestr or float; optional

Either the string ‘mask’ to mask the outlier values, ‘boxcar’ to replace data with the mean from the box-car filter, or a constant float-type fill value. Defaults to ‘mask’.

verbosebool; optional

If True, log details about the outliers found at this wavelength. Defaults to False.

Returns
datandarray (1D)

An array with the same dimensions as the input array with outliers replaced with fill_value.

outliersndarray (1D)

A boolean array where True for values that were clipped.

noutliersint

The number of outliers identified.

Notes

History:

  • Jan 29-31, 2022 Taylor Bell

    Initial version, added logging

eureka.lib.clipping.gauss_removal(img, mask, linspace, where='bkg')[source]

An additional step to remove cosmic rays.

This fits a Gaussian to the background (or a skewed Gaussian to the orders) and masks data points which are above a certain sigma.

Parameters
imgnp.ndarray

Single exposure image.

masknp.ndarray

An approximate mask for the orders.

linspacearray

Sets the lower and upper bin bounds for the pixel values. Should be of length = 2.

wherestr; optional

Sets where the mask is covering. Default is bkg. Other option is order.

Returns
imgnp.ndarray

The same input image, now masked for newly identified outliers.

lib.disk

eureka.lib.disk.disk(r, ctr, size, status=False)[source]

This function returns a byte array containing a disk.

The disk is centered at (ctr[0], ctr[1]), and has radius r. The array is (size[0], size[1]) in size and has byte type. Pixel values of 1 indicate that the center of a pixel is within r of (ctr[0], ctr[1]). Pixel values of 0 indicate the opposite. The center of each pixel is the integer position of that pixel.

Parameters
rfloat

The radius of the disk.

ctrtuple, list, or array

The x,y position of the center of the disk, 2-element vector.

sizetuple, list, or array

The x,y size of the output array, 2-element vector.

statusbool; optional

If True, return the status optional output.

Returns
retndarray

A boolean array where False if outside the disk or True if inside the disk.

retstatusint; optional

Set to 1 if any part of the disk is outside the image boundaries. Only returned if status==True.

Notes

History:

  • 2003 April 4; Joseph Harrington, jh@oobleck.astro.cornell.edu

    Initial version.

  • 2004 Feb 27; jh

    Added alternate input method

  • 2005 Nov 16; jh

    Added STATUS, simplified disk calculation, use double precision

lib.gaussian

eureka.lib.gaussian.fitgaussian(y, x=None, bgpars=None, fitbg=0, guess=None, mask=None, weights=None, maskg=False, yxguess=None)[source]

Fits an N-dimensional Gaussian to (value, coordinate) data.

Parameters
yndarray

Array giving the values of the function.

xndarray

(optional) Array (any shape) giving the abcissas of y (if missing, uses np.indices(y). The highest dimension must be equal to the number of other dimensions (i.e., if x has 6 dimensions, the highest dimension must have length 5). The rest of the dimensions must have the same shape as y. Must be sorted ascending (which is not checked), if guess is not given.

bgparsndarray or tuple, 3-elements

Background parameters, the elements determine a X- and Y-linearly dependant level, of the form: f = Y*bgparam[0] + X*bgparam[1] + bgparam[2] (Not tested for 1D yet).

fitbgInteger

This flag indicates the level of background fitting: fitbg=0: No fitting, estimate the bg as median(data). fitbg=1: Fit a constant to the bg (bg = c). fitbg=2: Fit a plane as bg (bg = a*x + b*y + c).

guesstuple, (width, center, height)

Tuple giving an initial guess of the Gaussian parameters for the optimizer. If supplied, x and y can be any shape and need not be sorted. See gaussian() for meaning and format of this tuple.

maskndarray

Same shape as y. Values where its corresponding mask value is 0 are disregarded for the minimization. Only values where the mask value is 1 are considered.

weightsndarray

Same shape as y. This array defines weights for the minimization, for scientific data the weights should be 1/sqrt(variance).

maskgbool; optional

If true, mask the gaussian.

yxguesstuple; optional

A guess at just the centroid. Defaults to None which uses the data point with the highest value.

Returns
paramsndarray

This array contains the best fitting values parameters: width, center, height, and if requested, bgpars. with: width : The fitted Gaussian widths in each dimension. center : The fitted Gaussian center coordinate in each dimension. height : The fitted height.

errndarray

An array containing the concatenated uncertainties corresponding to the values of params. For example, 2D input gives np.array([widthyerr, widthxerr, centeryerr, centerxerr, heighterr]).

Notes

If the input does not look anything like a Gaussian, the result might not even be the best fit to that.

Method: First guess the parameters (if no guess is provided), then call a Levenberg-Marquardt optimizer to finish the job.

History:

  • 2007-09-17 Joe jh@physics.ucf.edu

    Initial version, portions adapted from http://www.scipy.org/Cookbook/FittingData.

  • 2007-11-13 Joe

    Made N-dimensional.

  • 2008-12-02 Nate nlust@physics.ucf.edu

    Included error calculation, and return Fixed a bug in which if the initial guess was None, and incorrect shape array was generated. This caused gaussian guess to fail.

  • 2009-10-25

    Converted to standard doc header, fixed examples to return 4 parameters.

  • 2011-05-03 patricio pcubillos@fulbrightmail.org

    Added mask, weights, and background-fitting options.

Examples

>>> import matplotlib.pyplot as plt
>>> import gaussian as g

>>> # parameters for X
>>> lx = -3.  # low end of range
>>> hx = 5.   # high end of range
>>> dx = 0.05 # step

>>> # parameters of the noise
>>> nc = 0.0  # noice center
>>> ns = 1.0  # noise width
>>> na = 0.2  # noise amplitude

>>> # 1D Example

>>> # parameters of the underlying Gaussian
>>> wd = 1.1  # width
>>> ct = 1.2  # center
>>> ht = 2.2  # height

>>> # x and y data to fit
>>> x  = np.arange(lx, hx + dx / 2., dx)
>>> x += na * np.random.normal(nc, ns, x.size)
>>> y  = g.gaussian(x, wd, ct, ht)+na*np.random.normal(nc, ns, x.size)
>>> s  = x.argsort()   # sort, in case noise violated order
>>> xs = x[s]
>>> ys = y[s]

>>> # calculate guess and fit
>>> (width, center, height)     = g.gaussianguess(ys, xs)
>>> (fw,    fc,     fh,    err) = g.fitgaussian(ys, xs)

>>> # plot results
>>> plt.clf()
>>> plt.plot(xs, ys)
>>> plt.plot(xs, g.gaussian(xs, wd, ct, ht))
>>> plt.plot(xs, g.gaussian(xs, width, center, height))
>>> plt.plot(xs, g.gaussian(xs, fw, fc, fh))
>>> plt.title('Gaussian Data, Guess, and Fit')
>>> plt.xlabel('Abcissa')
>>> plt.ylabel('Ordinate')
>>> # plot residuals
>>> plt.clf()
>>> plt.plot(xs, ys - g.gaussian(xs, fw, fc, fh))
>>> plt.title('Gaussian Fit Residuals')
>>> plt.xlabel('Abcissa')
>>> plt.ylabel('Ordinate')

>>> # 2D Example

>>> # parameters of the underlying Gaussian
>>> wd = (1.1, 3.2)  # width
>>> ct = (1.2, 3.1)  # center
>>> ht = 2.2         # height

>>> # x and y data to fit
>>> nx = (hx - lx) / dx + 1
>>> x  = np.indices((nx, nx)) * dx + lx
>>> y  = g.gaussian(x, wd, ct, ht) + na * np.random.normal(nc, ns,
                                                        x.shape[1:])

>>> # calculate guess and fit
>>> #(width, center, height) = g.gaussianguess(y, x) # not in 2D yet...
>>> (fw, fc, fh, err) = g.fitgaussian(y, x, (wd, ct, ht))

>>> # plot results
>>> plt.clf()
>>> plt.title('2D Gaussian Given')
>>> plt.xlabel('X')
>>> plt.ylabel('Y')
>>> plt.imshow(    g.gaussian(x, wd, ct, ht))
>>> plt.clf()
>>> plt.title('2D Gaussian With Noise')
>>> plt.xlabel('X')
>>> plt.ylabel('Y')
>>> plt.imshow(y)
>>> #plt.imshow(g.gaussian(x, width, center, height))  # not in 2D yet
>>> plt.clf()
>>> plt.title('2D Gaussian Fit')
>>> plt.xlabel('X')
>>> plt.ylabel('Y')
>>> plt.imshow(    g.gaussian(x, fw, fc, fh))
>>> plt.clf()
>>> plt.title('2D Gaussian Fit Residuals')
>>> plt.xlabel('X')
>>> plt.ylabel('Y')
>>> plt.imshow(y - g.gaussian(x, fw, fc, fh))

>>> # All cases benefit from...

>>> # show difference between fit and underlying Gaussian
>>> # Random data, your answers WILL VARY.
>>> np.array(fw) - np.array(wd)
array([ 0.00210398, -0.00937687])
>>> np.array(fc) - np.array(ct)
array([-0.00260803,  0.00555011])
>>> np.array(fh) - np.array(ht)
0.0030143371034774269

>>> # Last Example:
>>> x = np.indices((30,30))
>>> g1 = g.gaussian(x, width=(1.2, 1.15), center=(13.2,15.75),
>>>                 height=1e4, bgpars=[0.0, 0.0, 100.0])
>>> error = np.sqrt(g1) * np.random.randn(30,30)
>>> y = g1 + error
>>> var = g1

>>> plt.figure(1)
>>> plt.clf()
>>> plt.imshow(y, origin='lower_left', interpolation='nearest')
>>> plt.colorbar()
>>> plt.title('2D Gaussian')
>>> plt.xlabel('X')
>>> plt.ylabel('Y')

>>> guess = ((1.2,1.2),(13,16.),1e4)
>>> reload(g)
>>> fit = g.fitgaussian(y, x, bgpars=[0.0, 0.0, 110.], fitbg=1,
                        guess=guess, mask=None, weights=1/np.sqrt(var))
>>> print(fit[0])
eureka.lib.gaussian.fitgaussians(y, x=None, guess=None, sigma=1.0)[source]

Fit position and flux of a data image with gaussians, same sigma is applied to all directions.

Parameters
yarray_like

Array giving the values of the function.

xarray_like

(optional) Array (any shape) giving the abcissas of y (if missing, uses np.indices(y).

guess2D-tuple

[[width1, center1, height1], [width2, center2, height2], … ] Tuple giving an initial guess of the Gaussian parameters for the optimizer. If supplied, x and y can be any shape and need not be sorted. See gaussian() for meaning and format of this tuple.

eureka.lib.gaussian.gaussian(x, width=1.0, center=0.0, height=None, bgpars=[0.0, 0.0, 0.0])[source]

Evaluates the Gaussian and a background with given parameters at locations in x.

Parameters
xndarray (any shape)

Abcissa values. Arranged as the output of np.indices() but may be float. The highest dimension must be equal to the number of other dimensions (i.e., if x has 6 dimensions, the highest dimension must have length 5, and each of those must give the coordinate along the respective axis). May also be 1-dimensional. Default: np.indices(y.shape).

widtharray_like; optional

The width of the Gaussian function, sometimes called sigma. If scalar, assumed constant for all dimensions. If array, must be linear and the same length as the first dimension of x. In this case, each element gives the width of the function in the corresponding dimension. Defaults to 1.0.

centerarray_like; optional

The mean value of the Gaussian function, sometimes called x0. Same scalar/array behavior as width. Defaults to 0.0.

heightscalar; optional

The height of the Gaussian at its center. If not set, initialized to the value that makes the Gaussian integrate to 1. If you want it to integrate to another number, leave height alone and multiply the result by that other number instead. Must be scalar. Defaults to None which resolves to [product(1./sqrt(2 * pi * width**2))].

bgparsndarray or tuple, 3-element; optional

Background parameters, the elements determine a X- and Y-linearly dependant level, of the form: f = Y*bgparam[0] + X*bgparam[1] + bgparam[2] (Not tested for 1D yet). Defaults to [0.0, 0.0, 0.0].

Returns
resultsndarray

Same shape as x (or first element of x if multidimensional) This function returns the Gaussian function of the given width(s), center(s), and height applied to its input plus a linear background level. The Gaussian function is: f(x) = 1./sqrt(2 * pi * width**2) * exp(-0.5 * ((x - center) / width)**2). It is defined in multiple dimensions as the product of orthogonal, single-dimension Gaussians.

Notes

History:

Examples

>>> import matplotlib.pyplot as plt
>>> import gaussian as g

>>> x = np.arange(-10., 10.005, 0.01)
>>> plt.plot(x, g.gaussian(x))
>>> plt.title('Gaussian')
>>> plt.xlabel('Abcissa')
>>> plt.ylabel('Ordinate')

>>> # use an array [3] as a single parameter vector
>>> z = np.array([2., 2, 3])
>>> plt.plot(x, g.gaussian(x, *z))

>>> # Test that it integrates to 1.
>>> a = np.indices([100, 100]) - 50
>>> print(np.sum(g.gaussian(a, 3, 3)))
0.999999999999997
>>> print(np.sum(g.gaussian(a, np.array([1,2]), np.array([2,3]))))
1.0000000107

>>> plt.clf()
>>> plt.imshow(g.gaussian(a, [3,5], [7,3]))
>>> plt.title('2D Gaussian')
>>> plt.xlabel('X')
>>> plt.ylabel('Y')

>>> A gaussian + a linear background level:
>>> g2 = g.gaussian(x, width=(1.2, 1.15), center=(13.2,15.75),
>>>                 height=4.3, bgpars=[0.05, 0.01, 1.0])
>>> plt.figure(1)
>>> plt.clf()
>>> plt.imshow(g2, origin='lower_left', interpolation='nearest')
>>> plt.colorbar()
>>> plt.title('2D Gaussian')
>>> plt.xlabel('X')
>>> plt.ylabel('Y')

>>> plt.figure(2)
>>> plt.clf()
>>> plt.plot(g2[13,:])
>>> plt.title('X slice of 2D Gaussian')
>>> plt.xlabel('X')
>>> plt.ylabel('Z')

>>> plt.figure(3)
>>> plt.clf()
>>> plt.plot(g2[:,16])
>>> plt.title('Y slice of 2D Gaussian')
>>> plt.xlabel('Y')
>>> plt.ylabel('Z')
eureka.lib.gaussian.gaussianguess(data, mask=None, yxguess=None)[source]

Used by fitgaussian to get an initial guess at the parameters for a Gaussian fit.

Parameters
datandarray (2D)

The data to which a Gaussian is being fit.

maskndarray (2D); optional

An integer mask array where 1 is unmasked and 0 is masked. Defaults to None which leaves all data unmasked.

yxguesstuple; optional

A guess at the centroid. Defaults to None which uses the data point with the highest value.

Returns
gwidthtuple

The guess for the Gaussian width in each direction.

gcentertuple

The guess for the centroid. Returns yxguess if it is not None, else uses the data point with the highest value.

gheightfloat

The guess for the Gaussian amplitude.

eureka.lib.gaussian.gaussians(x, param)[source]

Evaluate more than 1 gaussian.

eureka.lib.gaussian.resids(param, x, ngauss, y)[source]

Get the residuals of a Gaussian compared to data for fitting.

Parameters
paramndarray (1D)

The fitted parameters raveled into a 1D array.

xndarray (1D)

The x-positions of the values y.

ngaussint

The number of Gaussians being fitted.

yndarray (1D)

The values to which a Gaussian should be fitted.

Returns
ndarray (1D)

The difference between y and the Gaussian.

eureka.lib.gaussian.residuals(params, x, data, mask, weights, bgpars, fitbg)[source]

Calculates the residuals between data and a gaussian model determined by the rest of the parameters. Used in fitgaussian.

Parameters
params1D ndarray

This array contains the parameters desired to fit with fitgaussian, depending on fitbg, the number of elements varies.

xndarray

Array (any shape) giving the abcissas of data.

datandarray

Array giving the values of the function.

maskndarray

Same shape as data. Values where its corresponding mask value is 0 are disregarded for the minimization. Only values where the mask value is 1 are considered.

weightsndarray

Same shape as data. This array defines weights for the minimization, for scientific data the weights should be 1/sqrt(variance).

bgparsndarray or tuple, 3-elements

Background parameters, the elements determine a X- and Y-linearly dependant level, of the form: background = Y*bgparam[0] + X*bgparam[1] + bgparam[2]

fitbgInteger

This flag indicates the level of background fitting: fitbg=0: No fitting, estimate the bg as median(data). fitbg=1: Fit a constant to the bg (bg = c). fitbg=2: Fit a plane as bg (bg = a*x + b*y + c).

Returns
residuals1D ndarray

An array of the (unmasked) weighted residuals between data and a gaussian model determined by params (and bgpars when necessary).

Notes

History:

lib.gelmanrubin

eureka.lib.gelmanrubin.convergetest(pars, nchains)[source]

Driver routine for gelmanrubin.

Perform convergence test of Gelman & Rubin (1992) on a MCMC chain.

Parameters
parsndarray

A 2D array containing a separate parameter MCMC chain per row.

nchainsscalar

The number of chains to split the original chain into. The length of each chain MUST be evenly divisible by nchains.

Returns
psrfndarray

The potential scale reduction factors of the chain. If the chain has converged, each value should be close to unity. If they are much greater than 1, the chain has not converged and requires more samples. The order of psrfs in this vector are in the order of the free parameters.

meanpsrfscalar

The mean of psrf. This should be ~1 if your chain has converged.

Notes

History:

2010-08-20 ccampo

Initial version.

Examples

Consider four MCMC runs that has already been loaded. The individual fits are located in the fit list. These are for channels 1-4.

>>> import gelmanrubin
>>> import numpy as np
>>> # channels 1/3 free parameters
>>> ch13pars = np.concatenate((fit[0].allparams[fit[0].freepars],
>>>                            fit[2].allparams[fit[2].freepars]))

>>> # channels 2/4 free parameters
>>> ch24pars = np.concatenate((fit[1].allparams[fit[1].freepars],
>>>                            fit[3].allparams[fit[3].freepars]))

>>> # number of chains to split into
>>> nchains = 4

>>> # test for convergence
>>> ch13conv  = gelmanrubin.convergetest(ch13pars, nchains)
>>> ch24conv  = gelmanrubin.convergetest(ch24pars, nchains)

>>> # show results
>>> print(ch13conv)
(array([1.02254252, 1.00974035, 1.04838778, 1.0017869 , 1.7869707,
        2.15683239, 1.00506215, 1.00235165, 1.06784124, 1.04075207,
        1.01452032]), 1.1960716427734874)
>>> print(ch24conv)
(array([1.01392515, 1.00578357, 1.03285576, 1.13138702, 1.0001787,
        3.52118005, 1.10592542, 1.05514509, 1.00101459]),
        1.3185994837687156)
eureka.lib.gelmanrubin.gelmanrubin(chain, nchains)[source]

Perform convergence test of Gelman & Rubin (1992) on a MCMC chain.

Parameters
chainndarray

A vector of parameter samples from a MCMC routine.

nchainsscalar

The number of chains to split the original chain into. The length of chain WILL BE MODIFIED if NOT evenly divisible by nchains.

Returns
psrfscalar

The potential scale reduction factor of the chain. If the chain has converged, this should be close to unity. If it is much greater than 1, the chain has not converged and requires more samples.

Notes

History:

2010-08-20 ccampo

Initial version.

2011-07-07 kevin

Removed chain length constraint.

lib.imageedit

eureka.lib.imageedit.pasteimage(data, subim, dy_, syx=(None, None))[source]

Inserts the subim array into data, the data coordinates (dyc,dxc) will match the subim coordinates (syc,sxc). The arrays can have not overlapping pixels.

Parameters
data2D ndarray

Image where subim will be inserted.

subim2D ndarray

Image so be inserted.

dy_2 elements scalar tuple

dyc, dxc. Position in data that will match the (syc,sxc) position of subim.

syx: 2 elements scalar tuple

syc, sxc. Semi-length of the extracted image. if not specified, (syc,sxc) will be the center of subim.

Returns
The data array with the subim array inserted, according to the
given coordinates.

Notes

History:

  • 2010-07-11 patricio pcubillos@fulbrightmail.org

    Added documentation.

  • 2022-08-03 szieba

    changed (syc, sxc) is (None, None) to (syc, sxc) == (None, None)

Examples

eureka.lib.imageedit.trimimage(data, c, r, mask=None, uncd=None, oob=0)[source]

Extracts a rectangular area of an image masking out of bound pixels.

Parameters
data2D ndarray

Image from where extract a sub image.

c: 2-elements tuple

yc, xc. Position in data, where the extracted image will be centered. yc and xc must have integer values.

r2-elements tuple

yr, xr. Semi-length of the extracted image. Integer values.

mask2D ndarray

If specified, this routine will extract the mask subimage as well. out of bound pixels values will have value oob.

uncd2D ndarray

If specified, this routine will extract the uncd subimage as well.

oobscalar

Value for out of bound pixels in the mask. Default is 0.

Returns
Tuple, up to 3 2D-ndarray images containing the extracted image,
its mask (if specified) and a uncd array (if specified). The shape
of each array is (2*yr+1, 2*xr+1).

Notes

History:

Examples

lib.interp2d

eureka.lib.interp2d.interp2d(image, expand=5, y=None, x=None, yi=None, xi=None)[source]

This function oversamples a 2D frame (image) which can be used if the user decides that the resolution of the image is not enough and they want to split a pixel into more subpixels.

Parameters
image2D numpy array

Contains the 2D frame which will be oversampled in pixels

expandint

The factor by which a pixel should be oversampled. E.g., if set to 5, a pixel will turn into 25 subpixels.

y1D numpy array

np.arange(ny), with ny being the number of pixels in the y direction

x1D numpy array

np.arange(nx), with nx being the number of pixels in the x direction

yi1D numpy array

np.linspace(0, ny - 1, isz[0]), with isz = np.array(sz, dtype=int) + (np.array(sz, dtype=int)-1)*(expand-1) and sz = np.shape(image)

xi1D numpy array

np.linspace(0, ny - 1, isz[0]), with isz = np.array(sz, dtype=int) + (np.array(sz, dtype=int)-1)*(expand-1) and sz = np.shape(image)

lib.logedit

class eureka.lib.logedit.Logedit(logname, read=None)[source]

Bases: object

This object handles writing text outputs into a log file and to the screen as well.

Notes

History:

  • 2010-07-10 Patricio Cubillos

    Initial version

  • 2010-11-24 Patricio Cubillos

    logedit converted to a class.

Examples

>>> from logedit import Logedit
>>> message1 = 'This message will be logged and displayed.'
>>> message2 = 'This message too.'
>>> message3 = 'This one is Not going to delete previous lines.'
>>> message4 = ('This one copies previous lines and keeps previous '
                'log, but saves to new log.')
>>> message5 = 'This one deletes previous lines.'

>>> logname = 'out.log'
>>> logname2 = 'out2.log'

>>> # Create and print lines to a log
>>> log = Logedit(logname)
>>> log.writelog(message1)
This message will be logged and displayed.
>>> log.writelog(message2)
This message too.
>>> log.closelog()

>>> # Edit log without overiding previous lines
>>> log = Logedit(logname, read=logname)
>>> log.writelog(message3)
This one is Not going to delete previous lines.
>>> log.closelog()

>>> # copy a pre-existing log on a new log, and edit it.
>>> log = Logedit(logname2, read=logname)
>>> log.writelog(message4)
This one copies previous lines and keeps previous log, but saves to
new log.
>>> log.closelog()

>>> # overite a pre-existing log
>>> log = Logedit(logname)
>>> log.writelog(message5)
This one deletes previous lines.
>>> log.closelog()

>>> # See the output files: 'out.log' and 'out2.log' to see results.

Methods

closelog()

Closes an existing log file.

writeclose(message[, mute, end])

Print message in terminal and log, then close log.

writelog(message[, mute, end])

Prints message in the terminal and stores it in the log file.

closelog()[source]

Closes an existing log file.

writeclose(message, mute=False, end='\n')[source]

Print message in terminal and log, then close log.

Parameters
messagestr

The message to log.

mutebool; optional

If True, only log and do not pring. Defaults to False.

endstr; optional

Can be set to ‘\r’ to have the printed line overwritten which is useful for progress bars. Defaults to ‘\n’.

writelog(message, mute=False, end='\n')[source]

Prints message in the terminal and stores it in the log file.

Parameters
messagestr

The message to log.

mutebool; optional

If True, only log and do not pring. Defaults to False.

endstr; optional

Can be set to ‘\r’ to have the printed line overwritten which is useful for progress bars. Defaults to ‘\n’.

lib.manageevent

eureka.lib.manageevent.findevent(meta, stage, allowFail=False)[source]

Loads in an earlier stage meta file.

Parameters
metaeureka.lib.readECF.MetaClass

The new meta object for the current processing.

stagestr

The previous stage (e.g. “S2” for Stage 3).

allowFailbool; optional

Whether to allow the code to find no previous stage metadata files (for S2, S3) or throw an error if no metadata files are found. Default is False.

Returns
old_metaeureka.lib.readECF.MetaClass

The old metadata object.

inputdirstr

The new inputdir to use (based on the present location of the located metadata file).

inputdir_rawstr

The new inputdir_raw to use (based on the present location of the located metadata file).

Raises
AssertionError

Unable to find a metadata save file and allowFail was False.

Notes

History:

  • April 25, 2022 Taylor Bell

    Initial version.

eureka.lib.manageevent.loadevent(filename, load=[], loadfilename=None)[source]

Loads an event stored in .dat and .h5 files.

Parameters
filenamestr

The string contains the name of the event file.

loadstr tuple; optional

The elements of this tuple contain the parameters to read. We usually use the values: ‘data’, ‘uncd’, ‘head’, ‘bdmskd’, ‘brmskd’ or ‘mask’. Defaults to [].

loadfilenamestr; optional

The filename of the .h5 save file (excluding the file extension). Defaults to None which uses filename.

Returns
eureka.lib.readECF.MetaClass

The requested metadata object.

Notes

The input filename should not have the .dat nor the .h5 extentions.

History:

  • 2010-07-10 patricio

    Added documentation.

  • 2010-11-12 patricio

    reimplemented using exec()

eureka.lib.manageevent.mergeevents(new_meta, old_meta)[source]

Merge the current MetaClass data into the MetaClass object from a previous stage.

Parameters
new_metaeureka.lib.readECF.MetaClass

The metadata object for the current stage.

old_metaeureka.lib.readECF.MetaClass

The metadata object for the previous stage.

Returns
new_metaeureka.lib.readECF.MetaClass

The current metadata object containing the details from the previous metadata object.

Notes

History:

  • April 25, 2022 Taylor Bell

    Initial version.

eureka.lib.manageevent.saveevent(event, filename, save=[], delete=[], protocol=3)[source]

Saves an event in .dat (using cpickle) and .h5 (using h5py) files.

Parameters
eventeureka.lib.readECF.MetaClass

The meta data object to save.

filenamestr

The string contains the name of the event file.

savestr tuple

The elements of this tuple contain the parameters to save. We usually use the values: ‘data’, ‘uncd’, ‘head’, ‘bdmskd’, ‘brmksd’ or ‘mask’.

deletestr tuple

Parameters to be deleted.

Notes

The input filename should not have the .dat nor the .h5 extentions. Side effect: This routine deletes all parameters except ‘event’ after saving it.

History:

  • 2010-07-10 patricio

    Added documentation.

  • 2010-11-12 patricio

    reimplemented using exec()

eureka.lib.manageevent.updateevent(event, filename, add)[source]

Adds parameters given by add from filename to event.

Parameters
eventeureka.lib.readECF.MetaClass

The metadata object to update.

filenamestr

The string contains the name of the event file.

addstr tuple

The elements of this tuple contain the parameters to add. We usually use the values: ‘data’, ‘uncd’, ‘head’, ‘bdmskd’, ‘brmaskd’ or ‘mask’.

Returns
eureka.lib.readECF.MetaClass

The updated metadata object.

Notes

The input filename should not have the .dat nor the .h5 extentions.

History:

  • 2010-07-10 patricio

    Initial version.

  • 2010-11-12 patricio

    reimplemented using exec()

lib.mastDownload

eureka.lib.mastDownload.cleanup(download_dir='.')[source]

Remove empty folders from download directory.

Parameters
download_dirstr; optional

Temporary download directory specified for mastDownload.download(). Defaults to ‘.’.

Notes

History:

  • June 2022 Kevin Stevenson

    Initial version

eureka.lib.mastDownload.columnNames()[source]

Print column names from MAST Observation table.

Notes

History:

  • June 2022 Kevin Stevenson

    Initial version

eureka.lib.mastDownload.consolidate(result, final_dir)[source]

Consolidate downloaded files into a single directory

Parameters
resultAstroPy Table

The manifest of files downloaded, returned from mastDownload.download().

final_dirstr

Final destination of files.

Notes

History:

  • June 2022 Kevin Stevenson

    Initial version

eureka.lib.mastDownload.downloadHST(proposal_id, visit, inst='WFC3', download_dir='.', subgroup='IMA')[source]

Download observation visit number from specified proposal ID.

Parameters
proposal_idstr or int

HST proposal/program ID (e.g., 13467).

visitstr or int

HST visit number listed on the Visit Status Report (e.g., 60). See https://www.stsci.edu/cgi-bin/get-visit-status?id=XXXXX, where XXXXX is the proposal/program ID.

inststr; optional

HST instrument name, can be upper or lower case. Supported options include: WFC3, STIS, COS, or FGS. Defaults to ‘WFC3’.

download_dirstr; optional

Temporary download directory will be ‘download_dir’/mastDownload/… Defaults to ‘.’.

subgroupstr; optional

FITS file type (usually IMA, sometimes FLT). Defaults to ‘IMA’.

Returns
resultAstroPy Table

The manifest of files downloaded.

Notes

History:

  • June 2022 Kevin Stevenson

    Initial version

eureka.lib.mastDownload.filterJWST(proposal_id, observation, visit, calib_level, subgroup)[source]

Find JWST data products by applying standard filters.

Parameters
proposal_idstr or int

JWST proposal/program ID (e.g., 1366).

observationstr or int

JWST observation number listed on the Visit Status Report (e.g., 2). See www.stsci.edu/cgi-bin/get-visit-status?id=XXXXX&observatory=JWST, where XXXXX is the proposal/program ID.

visitstr or int

JWST visit number listed on the Visit Status Report (e.g., 2). See www.stsci.edu/cgi-bin/get-visit-status?id=XXXXX&observatory=JWST, where XXXXX is the proposal/program ID.

calib_levellist or int

Product Calibration Level (0 = raw, 1 = uncalibrated, 2 = calibrated, 3 = science product, 4 = contributed science product)

subgroupstr

FITS file type, varies by calib_level. 1: UNCAL, GS-ACQ1, GS-ACQ2, GS-FG, GS-ID, GS-TRACK 2: CAL, CALINTS, RATE, RATEINTS, X1DINTS, ANNNN_CRFINTS, GS-ACQ1, GS-ACQ2, GS-FG, GS-ID, GS-TRACK, RAMP 3: X1DINTS, WHTLT

Returns
tableAstroPy Table

The filtered table of data products.

Notes

History:

  • July 2022 Kevin Stevenson

    Initial version

eureka.lib.mastDownload.login(mast_token=None)[source]

Log into the MAST portal.

Parameters
mast_tokenstr; optional

The token to authenticate the user. Default is None. This can be generated at https://auth.mast.stsci.edu/token. If not supplied, it will be prompted for if not in the keyring or set via $MAST_API_TOKEN.

Notes

History:

  • July 2022 Kevin Stevenson

    Initial version

eureka.lib.mastDownload.logout()[source]

Log out of current MAST session.

Notes

History:

  • July 2022 Kevin Stevenson

    Initial version

eureka.lib.mastDownload.sortHST(final_dir, sci_dir='sci', cal_dir='cal')[source]

Sort files into science and calibration subdirectories.

Parameters
final_dirstr

Final destination of files.

sci_dirstr; optional

Name of science subdirectory within ‘final_dir’. Defaults to ‘sci’.

cal_dirstr; optional

Name of calibration subdirectory within ‘final_dir’. Defaults to ‘cal’.

Notes

History:

  • June 2022 Kevin Stevenson

    Initial version

eureka.lib.mastDownload.sortJWST(source_dir, target_dir, filetype)[source]
eureka.lib.mastDownload.writeTable_JWST(proposal_id, observation, visit, filename, format='csv')[source]

Write all products from specified visit to an ASCII file

Parameters
proposal_idstr or int

JWST proposal/program ID (e.g., 1366).

observationstr or int

JWST observation number listed on the Visit Status Report (e.g., 2). See www.stsci.edu/cgi-bin/get-visit-status?id=XXXXX&observatory=JWST, where XXXXX is the proposal/program ID.

visitstr or int

JWST visit number listed on the Visit Status Report (e.g., 1). See www.stsci.edu/cgi-bin/get-visit-status?id=XXXXX&observatory=JWST, where XXXXX is the proposal/program ID.

filenamestr; optional

The file format to use. Defaults to ‘csv’.

Notes

History:

  • July 2022 Kevin Stevenson

    Initial version

lib.meanerr

eureka.lib.meanerr.meanerr(data, derr, mask=None, err=False, status=False)[source]

Calculate the error-weighted mean and the error in the error-weighted mean of the input data, omitting masked data, NaN data or errors, and data whose errors are zero.

Parameters
data: ndarray

The data to average.

derr: ndarray

The 1-sigma uncertainties in data, same shape as data.

mask: ndarray

A 1 indicates the corresponding element of Data is good, a 0 indicates it is bad, same shape as data.

err: boolean

Set to True to return error in the mean.

status: boolean

Set to True to return a bit flag. If value=0, result is good. Bits: 0 = NaN(s) in data. 1 = some errors equal zero. 2 = masked pixel(s) in data.

Returns
This function returns the error-weighted mean of the unmasked
elements of Data. If err or status were set to True, return a
tuple.

Notes

Follows maximum likelihood method (see, e.g., Bevington and Robinson 2003, Data Reduction and Error Analysis for the Physical Sciences, 3rd ed, McGraw Hill, Ch. 4.).

History:

Examples

lib.medstddev

eureka.lib.medstddev.medstddev(data, mask=None, medi=False, axis=0)[source]

Compute the stddev with respect to the median.

This is rather than the standard method of using the mean.

Parameters
datandarray

An array from which to caculate the median standard deviation.

mask1D ndarray

Mask indicating the good values (ones) and bad values (zeros). Same shape as data. Defaults to None.

mediboolean; optional

If True return a tuple with (stddev, median) of data. Defaults to False.

axisint; optional

The axis along wich the median std deviation is calculated. Defaults to 0.

Returns
float

The stadard deviation.

float; optional

The median; only returned if medi==True.

Notes

MEANSTDDEV calculates the median, subtracts it from each value of X, then uses this residual to calculate the standard deviation.

The numerically-stable method for calculating the variance from moment.pro doesn’t work for the median standard deviation. It only works for the mean, because by definition the residuals from the mean add to zero.

History:

  • 2005-01-18 statia

    Written by Statia Luszcz.

  • 2005-01-19 statia

    Updated variance calculation according to algorithm in moment.pro, added medi keyword.

  • 2005-01-20 Joe Harrington, Cornell, jh@oobleck.astro.cornell.edu

    Header update. Removed algorithm from moment.pro because it doesn’t work for the median. Added /double.

  • 2010-11-05 patricio pcubillos@fulbrightmail.org

    Converted to python, documented.

  • 2022-04-11 Taylor James Bell

    Efficiently using numpy axes

Examples

>>> import medstdev as m
>>> a  = np.array([1,3,4,5,6,7,7])
>>> std, med = m.medstddev(a, medi=True)
>>> print(median(a))
5.0
>>> print(med)
5.0
>>> print(std)
2.2360679775

>>> # use masks
>>> a    = np.array([1,3,4,5,6,7,7])
>>> mask = np.array([1,1,1,0,0,0,0])
>>> std, med = m.medstddev(a, mask, medi=True)
>>> print(std)
1.58113883008
>>> print(med)
3.0

>>> # automatically mask invalid values
>>> a = np.array([np.nan, 1, 4, np.inf, 6])
>>> std, med = m.medstddev(a, medi=True)
>>> print(std, med)
(2.5495097567963922, 4.0)

>>> # critical cases:
>>> # only one value, return std = 0.0
>>> a    = np.array([1, 4, 6])
>>> mask = np.array([0, 0, 1])
>>> std, med = m.medstddev(a, mask, medi=True)
>>> print(std, med)
(0.0, 6.0)

>>> # no good values, return std = nan, med = nan
>>> mask[-1] = 0
>>> std, med = m.medstddev(a, mask, medi=True)
>>> print(std, med)
(nan, nan)

lib.plots

eureka.lib.plots.set_rc(style='preserve', usetex=False, filetype='.png', from_scratch=False, **kwargs)[source]

Function to adjust matplotlib rcParams for plotting procedures.

Parameters
stylestr; optional

Your plotting style from (“custom”, “eureka”, “preserve”, or “default”). Custom passes all kwargs to the ‘font’ rcParams group at the moment. Eureka sets some nicer rcParams settings recommended by the Eureka team. Preserve leaves all rcParams as-is and can be used to toggle the usetex parameter. By default uses ‘preserve’.

usetexbool; optional

Do you want to use LaTeX fonts (which requires LaTeX to be installed), by default False

filetypestr

The file type that all Eureka figures should be saved as (e.g. .png, .pdf).

from_scratchbool; optional

Should the rcParams first be set to rcdefaults? By default False.

**kwargsdict

Any additional parameters to be passed to rcParams.update.

Raises
ValueError

Ensures that usetex and from_scratch arguments are boolean

ValueError

Ensures that input style is one of: “custom”, “eureka”, “preserve”, or “default”

lib.readECF

class eureka.lib.readECF.MetaClass(folder=None, file=None, **kwargs)[source]

Bases: object

A class to hold Eureka! metadata.

This class loads a Eureka! Control File (ecf) and lets you query the parameters and values.

Notes

History:

  • 2009-01-02 Christopher Campo

    Initial Version.

  • 2010-03-08 Patricio Cubillos

    Modified from ccampo version.

  • 2010-10-27 Patricio Cubillos

    Docstring updated

  • 2011-02-12 Patricio Cubillos

    Merged with ccampo’s tepclass.py

  • 2022-03-24 Taylor J Bell

    Significantly modified for Eureka

Methods

copy_ecf()

Copy an ECF file to the output directory to ensure reproducibility.

read(folder, file)

A function to read ECF files

write(folder)

A function to write an ECF file based on the current MetaClass settings.

copy_ecf()[source]

Copy an ECF file to the output directory to ensure reproducibility.

NOTE: This will update the inputdir of the ECF file to point to the exact inputdir used to avoid ambiguity later and ensure that the ECF could be used to make the same outputs.

Notes

History:

  • Mar 2022 Taylor J Bell

    Initial Version based on old readECF code.

read(folder, file)[source]

A function to read ECF files

Parameters
folderstr

The folder containing an ECF file to be read in.

filestr

The ECF filename to be read in.

Notes

History:

  • Mar 2022 Taylor J Bell

    Initial Version based on old readECF code.

  • April 25, 2022 Taylor J Bell

    Joining topdir and inputdir/outputdir here.

write(folder)[source]

A function to write an ECF file based on the current MetaClass settings.

NOTE: For now this only rewrites the input ECF file to a new ECF file in the requested folder. In the future this function should make a full ECF file based on any adjusted parameters.

Parameters
folderstr

The folder where the ECF file should be written.

Notes

History:

  • Mar 2022 Taylor J Bell

    Initial Version.

lib.readEPF

class eureka.lib.readEPF.Parameter(name, value, ptype, priorpar1=None, priorpar2=None, prior=None)[source]

Bases: object

A generic parameter class

Attributes
ptype

Getter for the ptype

values

Return all values for this parameter

property ptype

Getter for the ptype

property values

Return all values for this parameter

Returns
list
[self.name, self.value, self.ptype, self.priorpar1,

self.priorpar2, self.prior] excluding any values which are None.

class eureka.lib.readEPF.Parameters(param_path=None, param_file=None, **kwargs)[source]

Bases: object

A class to hold the Parameter instances

This class loads a Eureka! Parameter File (epf) and lets you query the parameters and values.

Notes

History:

  • 2022-03-24 Taylor J Bell

    Based on readECF with significant edits for Eureka

Methods

read(folder, file)

A function to read EPF files

write(folder)

A function to write an EPF file based on the current Parameters settings.

read(folder, file)[source]

A function to read EPF files

Parameters
folderstr

The folder containing an EPF file to be read in.

filestr

The EPF filename to be read in.

Notes

History:

  • Mar 2022 Taylor J Bell

    Initial Version based on old readECF code.

write(folder)[source]

A function to write an EPF file based on the current Parameters settings.

NOTE: For now this only rewrites the input EPF file to a new EPF file in the requested folder. In the future this function should make a full EPF file based on any adjusted parameters.

Parameters
folderstr

The folder where the EPF file should be written.

Notes

History:

  • Mar 2022 Taylor J Bell

    Initial Version.

lib.smooth

eureka.lib.smooth.medfilt(x, window_len)[source]

Apply a length-k median filter to a 1D array x. Boundaries are extended by repeating endpoints.

Parameters
xndarray (1D)

The data to be smoothed.

window_lenint

The smoothing window length.

Returns
ndarray

A smoothed copy of x.

eureka.lib.smooth.smooth(x, window_len=10, window='hanning')[source]

Smooth the data using a window with requested size.

This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the begining and end part of the output signal.

Parameters
xndarray

The input signal.

window_lenint; optional

The dimension of the smoothing window. Defaults to 10.

windowstr; optional

The type of window from ‘flat’, ‘hanning’, ‘hamming’,’bartlett’, or ‘blackman’. flat window will produce a moving average smoothing. Defaults to ‘hanning’.

Returns
ndarray

the smoothed signal

See also

numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman
numpy.convolve, scipy.signal.lfilter

Notes

To Do: The window parameter could be the window itself if an array instead of a string.

References

http://www.scipy.org/Cookbook/SignalSmooth 2009-03-13

Examples

>>> t=linspace(-2,2,0.1)
>>> x=sin(t)+randn(len(t))*0.1
>>> y=smooth(x)

lib.sort_nicely

eureka.lib.sort_nicely.alphanum_key(s)[source]
Turn a string into a list of string and number chunks.

“z23a” -> [“z”, 23, “a”]

Parameters
sstr

The string to break into a list.

Returns
list

The string broken into a list of strings and ints.

eureka.lib.sort_nicely.sort_nicely(list1)[source]

Sort the given list in the way that humans expect.

Parameters
list1list

The list to sort nicely.

Returns
list

The nicely sorted list.

eureka.lib.sort_nicely.tryint(s)[source]

Turn a string into an int if possible.

Parameters
sstr

The string to try to convert to an int.

Returns
int OR str

An int if s was numeric, otherwise just returns s.

lib.splinterp

eureka.lib.splinterp.splinterp(x2, x, y)[source]

This function implements the methods splrep and splev of the module scipy.interpolate

Parameters
x21D array_like

array of points at which to return the value of the smoothed spline or its derivatives

xarray_like

The x data points defining a curve y = f(x).

yarray_like

The y data points defining a curve y = f(x).

Returns
array_like

An array of values representing the spline function or curve. If tck was returned from splrep, then this is a list of arrays representing the curve in N-dimensional space.

Examples

>>> import numpy as np
>>> import matplotlib.pyplot as plt

>>> x = np.arange(21)/20.0 * 2.0 * np.pi
>>> y = np.sin(x)
>>> x2 = np.arange(41)/40.0 *2.0 * np.pi

>>> y2 = splinterp(x2, x, y)
>>> plt.plot(x2,y2)

lib.suntimecorr

eureka.lib.suntimecorr.getcoords(file)[source]

Use regular expressions to extract X,Y,Z, and time values from the horizons file.

Parameters
filestrs list

A list containing the lines of a horizons file.

Returns
list

A four elements list containing the X, Y, Z, and time arrays of values from file.

Notes

History:

  • 2010-11-01, Patricio Cubillos

    Initial version

Examples

>>> start_data = '$$SOE'
>>> end_data   = '$$EOE'

>>> # Read in whole table as an list of strings, one string per line
>>> ctable = open('/home/esp01/ancil/horizons/all_spitzer.vec', 'r')
>>> wholetable = ctable.readlines()
>>> ctable.close()

>>> # Find start and end line
>>> i = 0
>>> while wholetable[i].find(end_data) == -1:
>>>     if wholetable[i].find(start_data) != -1:
>>>        start = i + 1
>>>     i += 1

>>> # Chop table
>>> data = wholetable[start:i-2]

>>> # Find values:
>>> x, y, z, t = getcoords(data)

>>> print(x, y, z, t)
eureka.lib.suntimecorr.suntimecorr(ra, dec, obst, coordtable, verbose=False)[source]

This function calculates the light-travel time correction from observer to a standard location. It uses the 2D coordinates (RA and DEC) of the object being observed and the 3D position of the observer relative to the standard location. The latter (and the former, for solar-system objects) may be gotten from JPL’s Horizons system.

Parameters
rafloat

Right ascension of target object in radians.

decfloat

Declination of target object in radians.

obstfloat or numpy float array

Time of observation in Julian Date (may be a vector)

coordtablestr

Filename of output table from JPL HORIZONS specifying the position of the observatory relative to the standard position.

verbosebool

If True, print X,Y,Z coordinates.

Returns
np.array

This function returns the time correction in seconds to be ADDED to the observation time to get the time when the observed photons would have reached the plane perpendicular to their travel and containing the reference position.

Notes

The position vectors from coordtable are given in the following coordinate system: Reference epoch : J2000.0 xy-plane : plane of the Earth’s mean equator at the reference epoch x-axis : out along ascending node of instantaneous plane of the Earth’s orbit and the Earth’s mean equator at the reference epoch z-axis : along the Earth mean north pole at the reference epoch

Ephemerides are often calculated for BJD, barycentric Julian date. That is, they are correct for observations taken at the solar system barycenter’s distance from the target. The BJD of our observation is the time the photons we observe would have crossed the sphere centered on the object and containing the barycenter. We must thus add the light-travel time from our observatory to this sphere. For non-solar-system observations, we approximate the sphere as a plane, and calculate the dot product of the vector from the barycenter to the telescope and a unit vector to from the barycenter to the target, and divide by the speed of light.

Properly, the coordinates should point from the standard location to the object. Practically, for objects outside the solar system, the adjustment from, e.g., geocentric (RA-DEC) coordinates to barycentric coordinates has a negligible effect on the trig functions used in the routine.

History:

  • 2005-12-01, Statia Luszcz

    Initial version.

  • 2006-03-09, jh

    Corrected 90deg error in algorithm, renamed, updated header, made Coordtable a positional arg since it’s required, switched to radians.

  • 2007-06-28, jh

    Renamed to suntimecorr since we now use barycentric Julian date.

  • 2009-01-28, jh

    Change variables to long, use spline instead of linfit so we can use one HORIZONS file for the whole mission.

  • 2009-02-22, jh

    Reshape spline results to shape of obst. Make it handle unsorted unput data properly. Header update.

  • 2010-07-10, patricio

    Converted to python.

  • 2010-11-01, patricio

    Docstring updated.

Examples

>>> # Spitzer is in nearly the Earth's orbital plane.  Light coming
>>> # from the north ecliptic pole should hit the observatory and
>>> # the sun at about the same time.

>>> import suntimecorr as sc
>>> ra  = 18.0 * np.pi /  12 # ecliptic north pole coords in radians
>>> dec = 66.5 * np.pi / 180 # "
>>> obst = np.array([2453607.078])  # Julian date of 2005-08-24 14:00
>>> print(sc.suntimecorr(
>>>           ra, dec, obst,
>>>           '/home/esp01/ancil/horizons/cs41_spitzer.vec'))
1.00810877 # about 1 sec, close to zero

>>> # If the object has the RA and DEC of Spitzer, light time should be
>>> # about 8 minutes to the sun.
>>> obs  = np.array([111093592.8346969, -97287023.315796047,
>>>                  -42212080.826677799])
>>> # vector to the object
>>> obst = np.array([2453602.5])

>>> print( np.sqrt(np.sum(obs**2.0)) )
153585191.481 # about 1 AU, good
>>> raobs  = np.arctan(obs[1]/ obs[0])
>>> decobs = np.arctan(obs[2]/ np.sqrt(obs[0]**2 + obs[1]**2))
>>> print(raobs, decobs)
-0.7192383661, -0.2784282118
>>> print(sc.suntimecorr(raobs, decobs, obst,
>>>                      '/home/esp01/ancil/horizons/cs41_spitzer.vec')
>>>       / 60.0)
8.5228630 # good, about 8 minutes light time to travel 1 AU

lib.utc_tt

eureka.lib.utc_tt.leapdates(rundir, log)[source]

Generates an array of leap second dates.

The array is automatically updated every six months. Uses a local leap second file, but retrieves a leap second file from NIST if the current file is missing or out of date.

Parameters
rundirstr

The folder in which to cache the leapdates array.

loglogedit.Logedit

The current log.

Returns
ndarray

The Julian dates of leap seconds.

eureka.lib.utc_tt.leapseconds(jd_utc, dates)[source]

Computes the difference between UTC and TT for a given date.

Parameters
jd_utcfloat

UTC Julian date.

datesarray_like

An array of Julian dates on which leap seconds occur.

Returns
float

The difference between UTC and TT for a given date.

eureka.lib.utc_tt.utc_tdb(jd_utc, leapdir, log)[source]

Converts UTC Julian dates to Barycentric Dynamical Time (TDB).

Formula taken from USNO Circular 179, based on that found in Fairhead and Bretagnon (1990). Accurate to 10 microseconds.

Parameters
jd_utcarray-like

UTC Julian date.

leapdirstr

The folder containing leapdir save files.

loglogedit.Logedit

The current log.

Returns
array-like

time in JD_TDB.

eureka.lib.utc_tt.utc_tt(jd_utc, leapdir, log)[source]

Converts UTC Julian dates to Terrestrial Time (TT).

Parameters
jd_utcarray-like

UTC Julian date.

leapdirstr

The folder containing leapdir save files.

loglogedit.Logedit

The current log.

Returns
array-like

Time in TT.

lib.util

eureka.lib.util.check_nans(data, mask, log, name='')[source]

Checks where a data-like array is invalid (contains NaNs or infs).

Parameters
datandarray

a data-like array (e.g. data, err, dq, …).

maskndarray

Input mask.

loglogedit.Logedit

The open log in which NaNs/Infs will be mentioned, if existent.

namestr; optional

The name of the data array passed in (e.g. SUBDATA, SUBERR, SUBV0). Defaults to ‘’.

Returns
maskndarray

Output mask where 0 will be written where the input data array has NaNs or infs.

eureka.lib.util.find_fits(meta)[source]

Locates S1 or S2 output FITS files if unable to find an metadata file.

Parameters
metaeureka.lib.readECF.MetaClass

The new meta object for the current stage processing.

Returns
metaeureka.lib.readECF.MetaClass

The meta object with the updated inputdir pointing to the location of the input files to use.

Notes

History:

  • April 25, 2022 Taylor Bell

    Initial version.

eureka.lib.util.get_mad(meta, log, wave_1d, optspec, optmask=None, wave_min=None, wave_max=None)[source]

Computes variation on median absolute deviation (MAD) using ediff1d for 2D data.

The computed MAD is the average MAD along the wavelength direction. In otherwords, the MAD is computed in the spectral direction for each integration, and then the returned value is the average of those MAD values.

Parameters
metaeureka.lib.readECF.MetaClass

Unused. The metadata object.

loglogedit.Logedit

The current log.

wave_1dndarray

Wavelength array (nx) with trimmed edges depending on xwindow and ywindow which have been set in the S3 ecf

optspecndarray

Optimally extracted spectra, 2D array (time, nx)

optmaskndarray (1D); optional

A mask array to use if optspec is not a masked array. Defaults to None in which case only the invalid values of optspec will be masked.

wave_minfloat; optional

Minimum wavelength for binned lightcurves, as given in the S4 .ecf file. Defaults to None which does not impose a lower limit.

wave_maxffloat; optional

Maximum wavelength for binned lightcurves, as given in the S4 .ecf file. Defaults to None which does not impose an upper limit.

Returns
madfloat

Single MAD value in ppm

eureka.lib.util.get_mad_1d(data, ind_min=0, ind_max=None)[source]

Computes variation on median absolute deviation (MAD) using ediff1d for 1D data.

Parameters
datandarray

The array from which to calculate MAD.

int_minint

Minimum index to consider.

ind_maxint

Maximum index to consider (excluding ind_max).

Returns
madfloat

Single MAD value in ppm

eureka.lib.util.interp_masked(data, meta, i, log)[source]

Interpolates masked pixels. Based on the example here: https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

iint

The current integration.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with requested pixels masked.

eureka.lib.util.makedirectory(meta, stage, counter=None, **kwargs)[source]

Creates a directory for the current stage.

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

stagestr

‘S#’ string denoting stage number (i.e. ‘S3’, ‘S4’).

counterint; optional

The run number if you want to force a particular run number. Defaults to None which automatically finds the run number.

**kwargsdict

Additional key,value pairs to add to the folder name (e.g. {‘ap’: 4, ‘bg’: 10}).

Returns
runint

The run number

eureka.lib.util.manmask(data, meta, log)[source]

Manually mask input bad pixels.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
dataXarray Dataset

The updated Dataset object with requested pixels masked.

eureka.lib.util.manual_clip(lc, meta, log)[source]

Manually clip integrations along time axis.

Parameters
lcXarray Dataset

The Dataset object containing light curve and time data.

metaeureka.lib.readECF.MetaClass

The current metadata object.

loglogedit.Logedit

The open log in which notes from this step can be added.

Returns
lcXarray Dataset

The updated Dataset object containing light curve and time data with the requested integrations removed.

metaeureka.lib.readECF.MetaClass

The updated metadata object.

loglogedit.Logedit

The updated log.

eureka.lib.util.normalize_spectrum(meta, optspec, opterr=None, optmask=None)[source]

Normalize a spectrum by its temporal mean.

Parameters
metaeureka.lib.readECF.MetaClass

The new meta object for the current stage processing.

optspecndarray

The spectrum to normalize.

opterrndarray; optional

The noise array to normalize using optspec, by default None.

optmaskndarray (1D); optional

A mask array to use if optspec is not a masked array. Defaults to None in which case only the invalid values of optspec will be masked.

Returns
normspec

The normalized spectrum.

normerrndarray; optional

The normalized error. Only returned if opterr is not none.

eureka.lib.util.pathdirectory(meta, stage, run, old_datetime=None, **kwargs)[source]

Finds the directory for the requested stage, run, and datetime (or old_datetime).

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

stagestr

‘S#’ string denoting stage number (i.e. ‘S3’, ‘S4’)

runint

run #, output from makedirectory function

old_datetimestr; optional

The date that a previous run was made (for looking up old data). Defaults to None in which case meta.datetime is used instead.

**kwargsdict

Additional key,value pairs to add to the folder name (e.g. {‘ap’: 4, ‘bg’: 10}).

Returns
pathstr

Directory path for given parameters

eureka.lib.util.phot_arrays(data)[source]

Setting up arrays for the photometry routine.

These arrays will be populated by the returns coming from centerdriver.py and apphot.py

Parameters
dataXarray Dataset

The Dataset object.

Returns
dataXarray Dataset

The updated Dataset object with new arrays where the outputs from the photometry routine will be saved in.

eureka.lib.util.read_time(meta, data, log)[source]

Read in a time CSV file instead of using the FITS time array.

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

dataXarray Dataset

The Dataset object with the fits data stored inside.

loglogedit.Logedit

The current log.

Returns
timendarray

The time array stored in the meta.time_file CSV file.

eureka.lib.util.readfiles(meta, log)[source]

Reads in the files saved in topdir + inputdir and saves them into a list.

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

loglogedit.Logedit

The current log.

Returns
metaeureka.lib.readECF.MetaClass

The metadata object with added segment_list containing the sorted data fits files.

eureka.lib.util.trim(data, meta)[source]

Removes the edges of the data arrays.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

Returns
subdataXarray Dataset

A new Dataset object with arrays that have been trimmed, depending on xwindow and ywindow as set in the S3 ecf.

metaeureka.lib.readECF.MetaClass

The metadata object.