ACID_code_v2.Acid
- class ACID_code_v2.Acid(velocities: Array1D | None = None, linelist: Array2D | None | str | LineList | dict = None, linelist_wl: Array1D | None = None, linelist_depths: Array1D | None = None, order: IntLike | None = None, order_range: Array1D | None = None, verbose: IntLike | bool | str | None = None, telluric_lines: Array1D | Array2D | dict | MaskingLines | list[tuple] | None = None, telluric_width: Scalar | None = None, hydrogen_lines: Array1D | Array2D | dict | MaskingLines | list[tuple] | None = None, hydrogen_width: Scalar | None = None, seed: IntLike | None = None, data: Data | DataList | None = None, config: Config | None = None, **kwargs)[source]
Accurate Continuum fItting and Deconvolution (ACID) class. This class contains the ACID method which fits the continuum of spectra and performs Least Squares Deconvolution (LSD) to obtain LSD profiles for each spectrum. It also contains many internal methods used within the main ACID function. See Dolan et al (2024) for more details on the ACID method and its applications.
Notes
Initialises the Acid class with inputted parameters. The class keeps calculations stored in the Data class and run configurations in the Config class (stored in Data for convenience). Both Data and the Result class (passed after ACID) have save and load methods which can save the result of any calculations, with the Result class naturally saving the Data class together. ACID is designed now to be run on only one order at a time, for running and keeping track of multiple orders, please see the DataList class for a natural implementation of running ACID on multiple orders and keeping track of which orders have been run and which haven’t, as well as storing the results for each order. The DataList instance has been designed with parallelization on HPC’s in mind, allowing orders (which are independent) to be run by different jobs. See also the multiprocessing section of the Read the Docs: (https://acid-v2.readthedocs.io/en/stable/using_ACID.html#multiprocessing).
Important note: All defaults in the signature are None, meaning if any values are input, they will override the default Config and/or Data values or any values that have already been input. The defaults within the config are written below. The config defaults can also be accessed by: ACID_code_v2.Config.defaults (returning a dictionary of defaults for both initialisation and run_acid). Note that some of the defaults in the config are also None, such as velocities, as this can be calculated from the input wavelengths.
Also shown is where each parameters is stored (either in the Data instance obtained from Acid.data) or in the Config instance (obtained from either Acid.config or Acid.data.config, which should be the same). The Config instance is for runtime settings and the Data instance is for storing data and any calculations.
- Parameters:
velocities (Array1D, optional) – Velocity grid for LSD profiles (in km/s). For example, use: np.arange(-25, 25, 0.82) to create. If None, a default grid from -25 to 25 km/s with a spacing calculated by calc_deltav after the wavelengths are provided. It is highly recommended to choose your own velocity grid, by default None, stored in the Data instance.
linelist (Array2D | str | LineList | dict, optional) – The linelist to use for LSD. The linelist should have wavelengths in angstroms and depths relative depths between 0 and 1. This is a required parameter if linelist_wl and linelist_depths are not provided. It can be of the forms: - String: A path to a VALD linelist in string format. Support for other linelists may be added in the future or on request. - Array2D: A 2D array-like object indexed such that index 0 is wavelengths and index 1 is depths. - dict: A dictionary with keys “wavelengths” and “depths”, each containing array-like objects for the wavelengths and depths respectively. - LineList: The LineList class is used to expose the linelist for masking or getting/plotting the linelist. You can input an instance if you have one. - If None, linelist_wl and linelist_depths must be provided (see below), by default None
linelist_wl (Array1D, optional) – Wavelengths of lines in linelist (in Angstroms). Only necessary if linelist is not provided. Must be same length as linelist_depths. If None, linelist must be provided (see above), by default None
linelist_depths (Array1D, optional) – Relative depths of lines in linelist (between 0 and 1). Only necessary if linelist is not provided. Must be same length as linelist_wl. If None, linelist must be provided (see above), by default None
order (IntLike, optional) – If this ACID instance is intended as a run on a specific order, then you can designate this instance for that order. This will allow the resulting Data instance to track of which order the profiles correspond to. Note that orders can be indexed by the correct indexing of the spectrograph (ie. some spectrographs start at order ~20). By default 0.
order_range (Array1D, optional) – Optionally also give ACID the full order range of the spectograph for the observation. ACID only ever runs on one order at a time, but this will allows ACID and eventually the DataList to keep track of which orders have been run and which haven’t, and will be used in the future for plotting and saving results. As with order (above), the orders can be indexed to the spectrograph orders. By default [0]
verbose (bool | IntLike | str, optional) – The verbosity for printing and plotting the progress and warnings of ACID. The verbosities are natively stored as integers corresponding to: 0: No printing or plotting, all warnings are ignored. 1: Only printing warnings. 2: Printing progress and warnings. 3: Printing progress and warnings, as well as additional plots and helpful information about the run. The possible input types are described below: - Integer: Must be between 0 and 3, corresponding to the verbosities described above. - Boolean: If True, defaults to 2. If False, defaults to 0. - String: Can be one of [“none”, “low”, “medium”, “high”] or their common variants.
telluric_lines (Array1D | Array2D | dict | MaskingLines | list[tuple], optional) –
Telluric lines (in angstroms) and widths in (km/s) to mask from the wavelength regions from. For many types of inputs, widths are optional, and if not provided, the default telluric width is used (see below). The inputs must be of the following forms: - 1D or 2D Array-like: Wavelengths at index 0, and optionally widths at index 1. The length of both indices must match if provided. - Dictionary: with keys “lines” and optionally “widths” (both array-like), length of both must match if provided. - MaskingLines class: The MaskingLines class is used to expose the linelist for masking or getting/plotting the Masked lines. You can input
an instance if you have one.
List of tuples: Each tuple should be in the format (line:float, width:Optional(float)). This format is useful for directly inputting lines with default width unless explicitly specified for some lines. Again, lines without the width provided will be set from the default telluric_width input.
telluric_width (Scalar, optional) – The default telluric width if any widths are missing from the above inputs. For each inputted telluric line, if a width is not provided, this width is used. The default is 21 km/s, a typical width of telluric lines.
hydrogen_lines (Array1D | Array2D | dict | MaskingLines | list[tuple], optional) – The exact same format as telluric_lines, but for hydrogen lines. The masking process is also identical, but the default widths can be different (see below).
hydrogen_width (Scalar, optional) – Works the same way as telluric_width, but for hydrogen lines. The default is 1000 km/s, a typical width of hydrogen lines, it may be worth increasing for hotter stars.
seed (IntLike, optional) – Random seed for reproducibility, leave it on None for a random seed, by default None.
data (Data | DataList, optional) – An optional backend Data object to use for storing data. Allows previously calculated results to be used skipped. If None, a new Data object is created. Please note that if the Data class already has a saved ACID config class, then any inputs to the Acid initialisation and ACID method will overwrite these config values. If a DataList instance is inputted, the data instance corresponding to the inputted order is used.
config (Config, optional) – An optional Config object to use for storing the configuration. Allows you to override the config values stored in the Data object, otherwise, inputs to the initialisation here and the ACID method will overwrite these config values again (if entered).
**kwargs (dict, optional) – Unused, mainly only to catch if users use the “linelist_path” input rather than the now “linelist” input.
- ACID(wavelengths: Array1D | Array2D | None = None, flux: Array1D | Array2D | None = None, errors: Array1D | Array2D | None = None, sn: Array1D | Array2D | Scalar | None = None, deterministic_profile: bool | None = None, poly_ord: IntLike | None = None, continuum_percentile: IntLike | None = None, bin_size: IntLike | None = None, pix_chunk: IntLike | None = None, dev_perc: IntLike | None = None, n_sig: IntLike | None = None, skips: IntLike | None = None, parallel: bool | None = None, cores: IntLike | None = None, nsteps: IntLike | None = None, max_steps: IntLike | None = None, check_interval: IntLike | None = None, min_checks: IntLike | None = None, min_tau_factor: IntLike | None = None, tau_tol: float | None = None, moves: list | None = None, run_mcmc: bool | None = True, _all_frames=None, **kwargs) Result | None[source]
Notes
Fits the continuum of the given spectra and performs LSD on the continuum corrected spectra, returning an LSD profile for each spectrum given. Spectra must cover a similiar wavelength range.
Important note: All defaults in the signature are None, meaning if any values are input, they will override the default Config and/or Data values or any values that have already been input. The defaults within the config are written below. The config defaults can also be accessed by: ACID_code_v2.Config.defaults (returning a dictionary of defaults for both initialisation and run_acid). Note that some of the defaults in the config are also None, such as velocities, as this can be calculated from the input wavelengths.
- Parameters:
wavelengths (Array1D | Array2D, optional) – An array of wavelengths for each frame (in Angstroms). For multiple frames this should be a 2D array such that wavelengths[i] corresponds to the wavelengths for the ith frame. Can only be None if a data instance was provided in initialisation. If a 2D array is provided, they are treated as multiple frames (not orders), by default None
flux (Array1D | Array2D, optional) – An array of spectral frames (in flux). For multiple frames this should be a 2D array such that flux[i] corresponds to the spectral fluxes for the ith frame. Can only be None if a data instance was provided in initialisation. If a 2D array is provided, they are treated as multiple frames (not orders), by default None
errors (Array1D | Array2D, optional) – Errors for each frame (in flux). For multiple frames this should be a 2D array such that errors[i] corresponds to the spectral errors for the ith frame. Can only be None if a data instance was provided in initialisation. If a 2D array is provided, they are treated as multiple frames (not orders), by default None
sn (Scalar | IntLike | Array1D, optional) – Average signal-to-noise ratio for each frame (used to calculate minimum line depth to consider from line list). Each frame should have only one S/N value, so for multiple frames this should be a 1D array such that sn[i] corresponds to the S/N for the ith frame. If None, the S/N will be estimated from the input spectra, by default None
deterministic_profile (bool, optional) – If True, fits both the continuum and the LSD profile simultaneously. If False, only fits the continuum in mcmc, the profile is inferred from the continuum fit. This is a new feature that has been set to the default as it significantly decrease convergence time and computation time per step, while fully maintaining accuracy. Setting this to False will match legacy behaviour, by default True.
poly_ord (IntLike, optional) – Order of polynomial to fit as the continuum, by default 3
continuum_percentile (IntLike, optional) – The percentile to use when fitting the continuum, by default 90. For example, if 90, the continuum fit will be performed on the points in the spectra that are above the 90th percentile in flux in each spectral bin (determined by bin_size below).
bin_size (IntLike, optional) – The size of bins to use when performing the continuum fit. The spectra are split into bins with this number of pixels, and the continuum is fit to the median wavelength and the specified percentile of flux in each bin. By default 100 pixels.
pix_chunk (IntLike, optional) – Size of ‘bad’ regions in pixels. ‘bad’ areas are identified by the residuals between an inital model and the data. If the residuals deviate by a specified percentage (see dev_perc below) for this number (pix_chunk) of pixels, then this chunk of pixels are masked in the spectra. By default 20
dev_perc (IntLike, optional) – Allowed deviation percentage. ‘bad’ areas are identified by the residuals between an inital model and the data. If a residual deviates by this percentage for a specified number of pixels, then this chunk of pixels are masked in the spectra. By default 25
n_sig (IntLike, optional) – Number of sigma to keep in sigma clipping. Ill fitting lines are identified by sigma-clipping the residuals between an inital model and the data. Regions that lie outside the median +- n_sig STDEVs are clipped. The clipped regions will be masked in the spectra. This masking is only applied to find the continuum fit and is removed when LSD is applied to obtain the final profiles, by default 1
skips (IntLike, optional) – An option to only run acid on one in every n pixels, where n is the integer argument. This is only useful for testing to get a quicker result especially for larger wavelength ranges or datasets, by default 1 (no skipping)
parallel (bool, optional) – If True uses multiprocessing to calculate the profiles for each frame in parallel, see https://acid-v2.readthedocs.io/en/stable/using_ACID.html#multiprocessing for more details. By default True
cores (IntLike, optional) – Number of cores to use if parallel=True. If None, all available cores will be used, by default None
nsteps (IntLike, optional) – Number of steps for the MCMC to run, by default 10000
max_steps (IntLike, optional) – If set, the sampler will run until max_steps or convergence is reached by estimation using the emcee autocorrelation time (tau). The sampler will check for convergence every ‘check_interval’ steps, and will require a minimum number of checks (‘min_checks’) and a minimum tau factor (‘min_tau_factor’) before it can stop. The stopping criterion is met when the change in tau is less than ‘tau_tol’ for all parameters. By default None, which means no maximum. If a value is inputted, the nsteps parameter is ignored. The continue_sampling method in Result or Acid can still be used normally to continue sampling after either stopping criterion is reached.
check_interval (IntLike, optional) – Interval (in steps) at which to check for MCMC convergence if max_steps is set, by default 1000. Only used if max_steps is set.
min_checks (IntLike, optional) – Minimum number of checks before MCMC can be stopped, by default 1. Only used if max_steps is set.
min_tau_factor (IntLike, optional) – Minimum tau factor for MCMC stopping criterion, by default 50, which is the emcee recommendation, it’s not recommend to set a value below 50 unless you want to force convergence for the deterministic_profile=False option. Only used if max_steps is set.
tau_tol (float, optional) – Tolerance for tau convergence in MCMC stopping criterion, by default 0.05. Only used if max_steps is set.
moves (list[tuple], optional) –
A list of tuples specifying the moves for the MCMC sampler. The format tries to follow the emcee documentation as closely as possible. However, the config cannot store classes directly, so move names are used instead and converted when building the sampler.
Each tuple should have the form:
(move_name: str, fraction: float, move_kwargs: dict | None)
where:
”move_name” is the name of the emcee move. Supported variants currently include “RedBlueMove”, “StretchMove”, “WalkMove”, “KDEMove”, “DEMove”, “DESnookerMove”, “MHMove”, and “GaussianMove”. Refer to the emcee documentation for more details on each move type. Input move names are checked against the “emcee.moves” module, so other moves from that module may also work, although not all have been tested with ACID.
”fraction” is the fraction of walkers to which this move should be applied.
”move_kwargs” is an optional dictionary of keyword arguments passed to the move class initialisation.
run_mcmc (bool, optional) – If True, runs the MCMC to fit the model, by default True. Can be set to False to perform all of the preparation for MCMC without actually running it. The ACID function will still update the class and data attributes. If True, the method returns a Result object, and if False, the method returns None, but attributes are updated.
**kwargs (dict, optional) – Unused, only used to catch accidental inputs of initialisation arguments into the ACID method and warn if so.
- Returns:
A Result object containing the LSD profiles and associated data. See the Result class for available methods and attributes.
If “run_mcmc” is False, “None” is returned, but the class attributes are still updated.
- Return type:
Result | None
- Raises:
ValueError – If any input arguments do not conform to the expected formats and requirements.
- combine_spec(frame_wavelengths: Array1D | Array2D | None = None, frame_flux: Array1D | Array2D | None = None, frame_errors: Array1D | Array2D | None = None, frame_sns: Array1D | Array2D | None = None, output: bool = True) tuple | None[source]
Combines multiple spectral frames into one spectrum
- Parameters:
frame_wavelengths (Array1D | Array2D, optional) – Wavelengths for the spectral frames, by default None
frame_flux (Array1D | Array2D, optional) – Fluxes for the spectral frames, by default None
frame_errors (Array1D | Array2D, optional) – Errors for the spectral frames, by default None
frame_sns (Array1D | Array2D, optional) – Signal-to-noise ratio for the spectral frames, by default None
output (bool, optional) – Whether to output the combined spectrum, by default True
- Returns:
tuple | None, if output is True, containing –
- combined_wavelengthsArray1D
Wavelengths for the combined spectrum
- combined_spectrumArray1D
Fluxes for the combined spectrum
- combined_errorsArray1D
Errors for the combined spectrum
- combined_snfloat
Signal-to-noise ratio for the combined spectrum
None, if output is False, but the combined spectrum is still saved in the data class attributes.
- continuumfit(fluxes: ACID_code_v2.utils.Array1D, wavelengths: ACID_code_v2.utils.Array1D, errors: ACID_code_v2.utils.Array1D, poly_ord: ACID_code_v2.utils.IntLike = 3, plot_result: bool = False, plot_type: str = 'initial') tuple[source]
Provides an initial, normalised continuum fit using inputted spectra.
- Parameters:
fluxes (np.ndarray) – The flux values of the spectrum.
wavelengths (np.ndarray) – The wavelengths corresponding to the spectrum.
errors (np.ndarray) – The error values associated with the spectrum.
poly_ord (int) – The order of the polynomial to fit to the continuum. By default 3.
plot_result (bool, optional) – Whether to plot the continuum fit result, by default False.
plot_type (str, optional) – The type of plot to generate, either “initial” or “masked”, by default “initial”
- Returns:
Polynomial coefficients: The coefficients of the fitted polynomial, ordered from highest degree to lowest.
Normalized flux: The flux values normalized by the fitted continuum.
Normalized errors: The error values normalized by the fitted continuum.
- Return type:
tuple containing
- residual_mask() None[source]
Masks regions of the spectrum based on residuals from an initial model fit. A purely class method not to be used elsewhere.
- continue_sampling(sampler, nsteps: IntLike | None = None, max_steps: IntLike | None = None, max_steps_kwards: dict | None = None) EnsembleSampler[source]
Continue MCMC sampling for additional steps. This should be called in Result class by the user. This necessarily requires a Data instance to have been put into the ACID init.
- Parameters:
sampler (emcee.EnsembleSampler) – The existing MCMC sampler to continue sampling from.
nsteps (int) – Number of additional steps to run the MCMC for.
max_steps (int, optional) – Maximum number of steps to run the MCMC for in total (including previous steps). If specified, the MCMC will stop if this number of steps is reached even if convergence has not been reached, by default None. If input, nsteps is ignored.
max_steps_kwards (dict, optional) – Additional keyword arguments to be passed to the run_mcmc_until_converged function if max_steps is specified, by default None. The kwargs description can be found in Acid.ACID(), they are the 4 kwargs appearing after max_steps. Typos for kwargs are silently ignored.
- Returns:
The MCMC sampler after running for the additional steps.
- Return type:
emcee.EnsembleSampler