The Code (API)

S1_detector_processing

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[, disable])

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

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[, disable])

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'

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[, disable])

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[, disable])

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, isplots)[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.

isplotsint

The amount of plots saved; set in ecf.

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]

Calulate drift2D

Parameters
im1ndarray

The reference image.

im2ndarray

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:

  • Initial version by LK

  • November 2021, Kevin Stevenson

    Modified

eureka.S3_data_reduction.hst_scan.calc_slitshift(wavegrid, xrng, refwave=None, width=3, deg=2)[source]

Estimate slit shift

Calculates horizontal shift to correct tilt in data using wavelength.

Parameters
wavegridndarray

The 2D wavelength grid.

xrngndarray

_description_

refwavendarray; optional

The 1D wavelength grid, by default None.

widthint; optional

The initial guess for the Gaussian width, defaults to 3.

degint; optional

The degree of the np.polyfit, defaults to 2.

Returns
shift_modelsndarray

The fitted polynomial model to the drift.

shift_valuesndarray

The fitted drifts.

Notes

History:

  • Nov 2013, Kevin Stevenson

    Initial Version

eureka.S3_data_reduction.hst_scan.calc_slitshift2(spectrum, xrng, ywindow, xwindow, width=5, deg=1)[source]

Calculate slit shifts

Calcualte horizontal shift to correct tilt in data using spectrum.

Parameters
spectrumndarray

The 2D image.

xrngtype

Unused.

xwindowndarray

Array containing image limits in wavelength direction.

ywindowndarray

Array containing image limits in spatial direction.

widthint; optional

The initial guess for the Gaussian width, defaults to 5.

degint; optional

The degree of the np.polyfit, defaults to 1.

Returns
shift_modelsndarray

The fitted polynomial model to the drift.

shift_valuesndarray

The fitted drifts.

yfitrange

The y values used when calculating drifts.

Notes

History:

  • July 2014, Kevin Stevenson

    Initial version

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

Calculates coefficients for the dispersion solution

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:

  • Initial version by LK

  • November 2021, Kevin Stevenson

    Modified

eureka.S3_data_reduction.hst_scan.correct_slitshift2(data, slitshift, mask=None, isreverse=False)[source]

Applies horizontal shift to correct tilt in data.

Parameters
datandarray

The 2D image.

slitshiftndarray

The fitted drifts.

maskndarray; optional

Data that should be masked, by default None.

isreversebool; optional

If true subtract slitshift, else addd slitshift. By default False.

Returns
cordatandarray

The 2D image corrected for slit shifts.

cormask.astype(int)ndarray; optional

The corrected mask, only returned if input mask is not None.

Notes

History:

  • June 2012, Kevin Stevenson

    Initial Version

eureka.S3_data_reduction.hst_scan.drift_fit2D(meta, data, validRange=9)[source]

Measures the spectrum drift over all frames and all non-destructive reads.

Parameters
metaeureka.lib.readECF.MetaClass

Event object.

datandarray

4D data frames.

validRangeint

Trim spectra by +/- pixels to compute valid region of cross correlation.

Returns
driftndarray

Array of measured drift values.

Notes

History:

  • January 2017, Kevin Stevenson

    Initial version

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

Group frames by 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.

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.

eureka.S3_data_reduction.hst_scan.replacePixels(shiftdata, shiftmask, m, n, i, j, k, ktot, ny, nx, sy, sx)[source]

Replace bad pixels

Parameters
shiftdatandarray

_description_

shiftmaskndarray

_description_

mint

_description_

nint

_description_

iint

_description_

jint

_description_

kint

_description_

ktotint

_description_

nyint

_description_

nxint

_description_

syint

_description_

sxint

_description_

Returns
shiftfloat
mint
nint
iint
jint

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_hardcoded()[source]

Compute wavelengths for simulated MIRI observations.

This code contains the wavelength array for MIRI data. It was generated by using the jwst and gwcs packages to get the wavelength information out of the WCS.

Returns
lam_x_fulllist

A list of the wavelengths

Notes

History:

  • Apr 2022 Sebastian Zieba

    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.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.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.find_column_median_shifts(data)[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

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.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

eureka.S3_data_reduction.nirspec.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.nirspec.straighten_trace(data, meta, log)[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.

Returns
dataXarray Dataset

The updated Dataset object with the fits data stored inside.

metaeureka.lib.readECF.MetaClass

The updated metadata object.

S3_data_reduction.optspex

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.

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.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.

windowtype{‘flat’,’hanning’,’hamming’,’bartlett’,’blackman’}; optional

UNUSED. The type of window. A flat window will produce a moving average smoothing.

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.drift_2D(data, meta)[source]

Plot the fitted 2D drift. (Fig 3102)

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 3305)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

Returns
None

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 3306)

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

Returns
None

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.

Returns
None
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)

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

optspecndarray

The optimally extracted spectrum.

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
None
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.

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

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

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.

Returns
None
eureka.S3_data_reduction.plots_s3.source_position(meta, x_dim, pos_max, m, 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 3303)

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.

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.

Returns
None

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.

Returns
None

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

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(data, meta, m, integ=0)[source]

Make image+background plot.

Parameters
dataXarray Dataset

The Dataset object.

metaeureka.lib.readECF.MetaClass

The metadata object.

mint

The file number.

integint, optional

The integration number. Default is 0 (first integration)

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)

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

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

Parameters
fluxndarray

The 3D array of flux values.

metaeureka.lib.readECF.MetaClass

The metadata object.

mint

The file number.

integint, optional

The integration number. Default is 0 (first integration)

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, integ=0)[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.

integint, optional

The integration number. Default is 0 (first integration)

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, integ=0, plot=True)[source]

A simple function to find the brightest row for source location

Parameters
fluxndarray

The 3D array of flux values.

metaeureka.lib.readECF.MetaClass

The metadata object.

mint

The file number.

integint, 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)

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.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.

Returns
None

Notes

History:

  • Jul 11, 2022 Caroline Piaulet

    Created this function

eureka.S4_generate_lightcurves.plots_s4.lc_driftcorr(meta, wave_1d, optspec, 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.

optspecndarray

The optimally extracted spectrum.

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.

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. :param eventlabel: The unique identifier for these data. :type eventlabel: str :param ecf_path: The absolute or relative path to where ecfs are stored.

Defaults to None which resolves to ‘./’.

Parameters

s3_meta (eureka.lib.readECF.MetaClass) – The metadata object from Eureka!’s S3 step (if running S3 and S4 sequentially). Defaults to None.

Returns

  • spec (Astreaus object) – Data object of wavelength-like arrrays.

  • lc (Astreaus object) – Data object of time-like arrrays (light curve).

  • meta (eureka.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

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.

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.

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, names, **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.

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, names, **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, names, **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.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.

time

A getter for the time.

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, names, **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.

time

A getter for the time.

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, names, **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, names, **kwargs)[source]

Update parameters in the model components.

Parameters
newparamsndarray

New parameter values.

nameslist

Parameter names.

**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.

time

A getter for the time.

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, names, **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 time

A getter for the time.

property units

A getter for the unit.s

update(newparams, names, **kwargs)[source]

Update the model with new parameter values.

Parameters
newparamsndarray

New parameter values.

nameslist

Parameter names.

**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, names, **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.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, names, **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, names, **kwargs)[source]

Update the model with new parameter values.

Parameters
newparamsndarray

New parameter values.

nameslist

Parameter names.

**kwargsdict

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

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, unc=None, parameters=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.

time

A getter for the time.

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, names, **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’, ‘square-root’, ‘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’, ‘square-root’, ‘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]

Square-root 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, 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.

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_namestring

The name of the target transit.

Returns
target_urlstring
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_locationstring; 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_namestring

The name of the target transit.

Returns
canonical_namestring
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_namestring

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

Returns
None

S6_planet_spectra.s6_spectra

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, fit_methods, y_param, channel_key='shared')[source]

Load in the S5 save file.

Parameters
metaeureka.lib.readECF.MetaClass

The current meta data object.

fit_methodslist

The fitting methods used in S5.

y_paramstr

The parameter to plot.

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.

Raises
AssertionError

The y_param was not found in the list of fitted parameter names.

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

lib

lib.astropytable

eureka.lib.astropytable.readtable(filename)[source]
eureka.lib.astropytable.savetable_S5(filename, time, wavelength, bin_width, lcdata, lcerr, model, residuals)[source]
eureka.lib.astropytable.savetable_S6(filename, wavelength, bin_width, tr_depth, tr_depth_err, ecl_depth, ecl_depth_err)[source]

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).

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 dispersions.

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]
eureka.lib.gaussian.gaussians(x, param)[source]

Evaluate more than 1 gaussian.

eureka.lib.gaussian.resids(param, x, ngauss, y)[source]
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:

2011-05-03 patricio Initial version.

pcubillos@fulbrightmail.org

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.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 the 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.

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.

filenameString

The string contains the name of the event file.

savestring tuple

The elements of this tuple contain the parameters to save. We usually use the values: ‘data’, ‘uncd’, ‘head’, ‘bdmskd’, ‘brmksd’ or ‘mask’.

deletestring 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.

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.

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.smoothing

eureka.lib.smoothing.gauss_kernel_mask2(ny_nx, sy_sx, j_i, mask)[source]

Create a 2D Gaussian kernel mask.

Parameters
ny_nxlist/ndarray

The ny and nx values.

sy_sxlist/ndarray

The sy and sx values.

j_ilist/ndarray

The j and i values.

maskndarray

The current mask.

Returns
ndarray

The Gaussian kernel.

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
fileStrings 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)

coordtablestring

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 coordinates 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 array has NaNs.

Parameters
datandarray

a data array (e.g. data, err, dq, …).

maskndarray

Input mask.

loglogedit.Logedit

The open log in which NaNs 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

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.

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=- 1)[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.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.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.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)[source]

Reads in the files saved in topdir + inputdir and saves them into a list.

Parameters
metaeureka.lib.readECF.MetaClass

The metadata object.

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.