### Install specreduce from GitHub source Source: https://specreduce.readthedocs.io/en/latest/getting_started/installation.html Clones the specreduce repository from GitHub and installs it in editable mode. Use this for development or to get the latest source. ```bash git clone https://github.com/astropy/specreduce.git cd specreduce pip install . ``` -------------------------------- ### Install specreduce with pip Source: https://specreduce.readthedocs.io/en/latest/getting_started/installation.html Installs the specreduce package from PyPI using pip. Run this in a terminal with Python and pip available. ```bash pip install specreduce ``` -------------------------------- ### Background example: two_sided and subtraction Source: https://specreduce.readthedocs.io/en/latest/api/specreduce.background.Background.html Shows how to create a Background object using the two_sided method and subtract it from an image. Requires a FlatTrace object and separation distance. ```python trace = FlatTrace(image, trace_pos) bg = Background.two_sided(image, trace, bkg_sep, width=bkg_width) subtracted_image = image - bg ``` -------------------------------- ### Build a traced continuum source with background and noise Source: https://specreduce.readthedocs.io/en/latest/api/specreduce.utils.synth_data.SynthImage.html Build a synthetic spectroscopic image by chaining add_* methods and render it as a CCDData. The example sets a background, adds a Moffat1D source profile, applies Poisson and read noise, and uses a fixed seed for reproducibility. ```python from astropy.modeling import models from specreduce.utils.synth_data import SynthImage image = ( SynthImage(nx=1024, ny=400, seed=42) .add_background(5) .add_source(profile=models.Moffat1D(amplitude=20, alpha=0.1)) .add_poisson_noise() .add_read_noise(3) .to_ccddata() ) ``` -------------------------------- ### Import libraries and specreduce modules Source: https://specreduce.readthedocs.io/en/latest/getting_started/quickstart.html Imports the necessary libraries and specreduce modules for spectrum extraction and calibration. Also imports helper functions from the quickstart module and sets matplotlib to use constrained layout. ```python import warnings import numpy as np import matplotlib.pyplot as plt import astropy.units as u from astropy.modeling import models from specreduce.tracing import FitTrace from specreduce.background import Background from specreduce.extract import BoxcarExtract, HorneExtract from specreduce.wavecal1d import WavelengthCalibration1D from quickstart import make_science_and_arcs, plot_2d_spectrum plt.rcParams['figure.constrained_layout.use'] = True ``` -------------------------------- ### Background.one_sided with integer center Source: https://specreduce.readthedocs.io/en/latest/getting_started/quickstart.html Equivalent to the previous example but passes an integer (15) as the center instead of a trace. The center can be a float, integer, or trace. ```python bg = Background.one_sided(sci, 15, separation=5, width=2) ``` -------------------------------- ### Generate synthetic science and arc spectra Source: https://specreduce.readthedocs.io/en/latest/getting_started/quickstart.html Creates synthetic science and arc spectra using the quickstart utility function. Returns the science frame and two arc frames as CCDData objects with uncertainties. ```python sci2d, (arc2d_he, arc2d_ne) = make_science_and_arcs(1000, 300) ``` -------------------------------- ### Instantiate WavelengthCalibration1D Source: https://specreduce.readthedocs.io/en/latest/getting_started/quickstart.html Instantiates a WavelengthCalibration1D object with the extracted arc spectra and catalog line lists. The line list bounds (500-1000 nm) and the number of strongest lines (15) are set based on the instrument setup. ```python wc = WavelengthCalibration1D([arc1d_he, arc1d_ne], line_lists=["HeI", "NeI"], line_list_bounds=(500, 1000), n_strogest_lines=15, unit=u.nm) ``` -------------------------------- ### Convert pixel coordinates to wavelengths with pix_to_wav() Source: https://specreduce.readthedocs.io/en/latest/wavelength_calibration/wavelength_calibration.html Converts pixel coordinates to wavelengths using the stored wavelength solution. The example creates an array of pixel values and prints the corresponding wavelengths. ```python pixels = np.array([100, 500, 900]) wavelengths = ws.pix_to_wav(pixels) print(wavelengths) ``` -------------------------------- ### Build a synthetic image with SynthImage Source: https://specreduce.readthedocs.io/en/latest/_modules/specreduce/utils/synth_data.html Build a synthetic 2D spectroscopic image with a traced Moffat source, constant background, Poisson noise, and read noise, then render it to a CCDData object. Requires a seed for deterministic noise; the example uses nx=1024, ny=400, and a background level of 5 counts. ```python from astropy.modeling import models from specreduce.utils.synth_data import SynthImage image = ( SynthImage(nx=1024, ny=400, seed=42) .add_background(5) .add_source(profile=models.Moffat1D(amplitude=20, alpha=0.1)) .add_poisson_noise() .add_read_noise(3) .to_ccddata() ) ``` -------------------------------- ### Call extraction object with overridden parameters Source: https://specreduce.readthedocs.io/en/latest/extraction.html Call the extraction object to get the spectrum while temporarily overriding parameters. The first example overrides the width to 6, the second overrides the trace_object with a new trace. ```python spectrum2 = extract(width=6) ``` ```python spectrum2 = extract(trace_object=new_trace) ``` -------------------------------- ### Install specreduce with conda Source: https://specreduce.readthedocs.io/en/latest/getting_started/installation.html Installs specreduce from the conda-forge repository using conda. Requires conda to be installed and configured. ```bash conda install conda-forge::specreduce ``` -------------------------------- ### Initialize FitTrace with bins and Polynomial1D Source: https://specreduce.readthedocs.io/en/latest/trace.html Initializes a FitTrace with optional binning and a polynomial trace model. Suitable for typical spectra with smooth, continuous trace profiles. ```python trace = specreduce.tracing.FitTrace(image, bins=10, trace_model=Polynomial1D(3)) ``` -------------------------------- ### Guard for match_lines solution Source: https://specreduce.readthedocs.io/en/latest/_modules/specreduce/tilt_correction.html Checks that the solution has been calculated before matching lines; raises ValueError if not. This is the guard at the start of the match_lines method. ```python if self.solution is None: raise ValueError("The solution must be calculated before line matching.") ``` -------------------------------- ### Initialize WavelengthCalibration1D with observed line positions Source: https://specreduce.readthedocs.io/en/latest/wavelength_calibration/wavelength_calibration.html Initializes WavelengthCalibration1D using pre-identified observed line positions. Requires obs_lines as a NumPy array, pix_bounds as a tuple, and ref_pixel as the anchor for the polynomial fit. ```python obs_he = np.array([105.3, 210.8, 455.1, 512.5, 680.2]) pixel_bounds = (0, 1024) wc = WavelengthCalibration1D(ref_pixel=512, obs_lines=obs_he, line_lists=["HeI"], pix_bounds=pixel_bounds) ``` -------------------------------- ### WavelengthSolution1D class initialization Source: https://specreduce.readthedocs.io/en/latest/_modules/specreduce/wavesol1d.html Initializes a WavelengthSolution1D object with a pixel-to-wavelength transformation, pixel bounds, and unit. Converts the unit to LaTeX string representation and sets up caches. ```python def __init__( self, p2w: None | CompoundModel, bounds_pix: tuple[int, int], unit: u.Unit, wave_air: bool = False, ) -> None: """Class defining a one-dimensional wavelength solution. This class manages the mapping between pixel positions and wavelength values in a 1D spectrum, supporting both forward and reverse transformations. It provides methods for resampling spectra in the pixel-to-wavelength space while conserving flux, and integrates with GWCS for coordinate transformations. Initializes an object with pixel-to-wavelength transformation, pixel bounds, and measurement unit. Also, converts the unit to its LaTeX string representation. Parameters ---------- p2w The pixel-to-wavelength transformation model. If None, no transformation will be set. bounds_pix The lower and upper pixel bounds defining the range of the spectrum. unit The wavelength unit. wave_air Whether the solution maps pixels to air rather than vacuum wavelengths; by default `False`, meaning vacuum wavelengths. """ self.unit = unit self.wave_air = wave_air self._unit_str = unit.to_string("latex") self.bounds_pix: tuple[int, int] = bounds_pix self.bounds_wav: tuple[float, float] | None = None self._wcs_cache: dict[bool, tuple[tuple, float]] = {} self._p2w: None | CompoundModel = None self.p2w = p2w ``` -------------------------------- ### One-sided background example Source: https://specreduce.readthedocs.io/en/latest/_modules/specreduce/background.html Creates a one-sided background above or below an input trace. The trace is estimated with FitTrace, then Background.one_sided is called with the separation and width for the background region. ```python trace = FitTrace(image, guess=trace_pos) bg = Background.one_sided(image, trace, bkg_sep, width=bkg_width) ``` -------------------------------- ### Get extracted spectrum via spectrum property Source: https://specreduce.readthedocs.io/en/latest/extraction.html Retrieve the extracted 1D spectrum from an initialized extraction object. The spectrum is available via the spectrum property. ```python spectrum = extract.spectrum ``` -------------------------------- ### load_pypeit_calibration_lines() Source: https://specreduce.readthedocs.io/en/latest/api/specreduce.calibration_data.load_pypeit_calibration_lines.html Loads reference calibration lines from pypeit linelists, with options for lamp selection, air wavelength conversion, caching, and progress display. ```APIDOC ## load_pypeit_calibration_lines() ### Description Load reference calibration lines from `pypeit` linelists. The `pypeit` linelists are well-curated and have been tested across a wide range of spectrographs. The available linelists are defined by `PYPEIT_CALIBRATION_LINELISTS`. ### Method Function call ### Endpoint `specreduce.calibration_data.load_pypeit_calibration_lines(lamps: Sequence | None = None, wave_air: bool = False, cache: bool | Literal['update'] = True, show_progress: bool = False) -> QTable | None` ### Parameters - **lamps** (Sequence | None) - Optional - Lamp string, comma-separated list of lamps, or sequence of lamps to include in output reference linelist. The parlance of “lamp” is retained here for consistency with its use in `pypeit` and elsewhere. In several of the supported cases the “lamp” is the sky itself (e.g. OH lines in the near-IR). The available lamps are defined by `PYPEIT_CALIBRATION_LINELISTS`. - **wave_air** (bool) - Optional - If True, convert the vacuum wavelengths used by `pypeit` to air wavelengths. - **cache** (bool | Literal['update']) - Optional - Toggle caching of downloaded data. - **show_progress** (bool) - Optional - Show download progress bar. ### Returns - **linelist** (QTable | None) - Table containing the combined calibration line list. `pypeit` linelists have the following columns: `ion`, `wavelength`, `NIST`, `Instr`, `amplitude`, `Source`. ``` -------------------------------- ### Two-sided background example Source: https://specreduce.readthedocs.io/en/latest/_modules/specreduce/background.html Creates a two-sided background around a fitted trace. The trace is estimated with FitTrace, then Background.two_sided is called with the separation and width for the background regions. ```python trace = FitTrace(image, guess=trace_pos) bg = Background.two_sided(image, trace, bkg_sep, width=bkg_width) ``` -------------------------------- ### Background(image, traces, width, statistic, disp_axis, crossdisp_axis, mask_treatment, sigma) Source: https://specreduce.readthedocs.io/en/latest/api/specreduce.background.Background.html Constructor for the Background class. Initializes the background computation with the given image, traces, and parameters. ```APIDOC ## Background(image, traces, width, statistic, disp_axis, crossdisp_axis, mask_treatment, sigma) ### Description Initializes a Background object to determine the background from an image for subtraction. ### Parameters - **image** (ndarray | NDData | Quantity) - Required - Image with 2-D spectral image data. - **traces** (list) - Required - Individual or list of trace object(s) (or integers/floats to define FlatTraces) to extract the background. If None, a FlatTrace at the center of the image (according to disp_axis) will be used. - **width** (float) - Optional - Width of extraction aperture in pixels. Default: 5. - **statistic** (str) - Optional - Statistic to use when computing the background. 'average' will account for partial pixel weights, 'median' will include all partial pixels. Default: 'average'. - **disp_axis** (int) - Optional - Dispersion axis. Default: 1. - **crossdisp_axis** (int) - Optional - Cross-dispersion axis. Default: 0. - **mask_treatment** (Literal['apply', 'ignore', 'propagate', 'zero_fill', 'nan_fill', 'apply_mask_only', 'apply_nan_only']) - Optional - Specifies how to handle masked or non-finite values in the input image. Default: 'apply'. - **sigma** (None | float) - Optional - Number of standard deviations for sigma clipping outlier rejection. If None, no sigma clipping is performed. Default: 5.0. ### Example python trace = FlatTrace(image, trace_pos) bg = Background.two_sided(image, trace, bkg_sep, width=bkg_width) subtracted_image = image - bg ``` -------------------------------- ### Initialize FlatTrace with trace_pos Source: https://specreduce.readthedocs.io/en/latest/trace.html Initializes a FlatTrace with a fixed cross-dispersion pixel position. Use for well-aligned spectrographs with minimal optical distortion. ```python trace = specreduce.tracing.FlatTrace(image, trace_pos=6) ``` -------------------------------- ### Plot science and arc spectra Source: https://specreduce.readthedocs.io/en/latest/getting_started/quickstart.html Plots the science and arc spectra in a 3-panel figure for visual inspection. Uses the quickstart helper to display each 2D spectrum. ```python fig, axs = plt.subplots(3, 1, figsize=(6, 4), sharex='all') plot_2d_spectrum(sci2d, ax=axs[0], label='Science') for i, (arc, label) in enumerate(zip((arc2d_he, arc2d_ne), "HeI NeI".split())): plot_2d_spectrum(arc, ax=axs[i+1], label=label) plt.setp(axs[:-1], xlabel='') plt.setp(axs, ylabel='C.D. axis [pix]'); ``` -------------------------------- ### Initialize WavelengthCalibration1D with observed lines from multiple arcs Source: https://specreduce.readthedocs.io/en/latest/wavelength_calibration/wavelength_calibration.html Initializes WavelengthCalibration1D with observed line positions from multiple arcs. Each arc's observed lines are provided as a list of NumPy arrays, with corresponding line_lists and a shared pix_bounds. ```python obs_he = np.array([105.3, 210.8, 455.1, 512.5, 680.2]) obs_hg_ar = np.array([234.2, 534.1, 768.2, 879.6]) pixel_bounds = (0, 1024) wc = WavelengthCalibration1D(ref_pixel=512, obs_lines=[obs_he, obs_hg_ar], line_lists=[["HeI"], ["HgI", "ArI"]], pix_bounds=pixel_bounds) ``` -------------------------------- ### Resample spectrum with custom bin_edges using resample() Source: https://specreduce.readthedocs.io/en/latest/wavelength_calibration/wavelength_calibration.html Resamples a spectrum onto a custom wavelength grid defined by bin_edges. The example uses a geometric spacing from 4500 to 7500 with 1000 bins. ```python resampled_arc = ws.resample(arc_spectrum, bin_edges=np.geomspace(4500, 7500, 1000)) print(resampled_arc.spectral_axis) ``` -------------------------------- ### bkg_image(image=None) Source: https://specreduce.readthedocs.io/en/latest/api/specreduce.background.Background.html Expose the background tiled to the dimension of the input image. ```APIDOC ## bkg_image(image=None) ### Description Expose the background tiled to the dimension of `image`. ### Parameters - **image** (NDData-like or array-like, optional) - Image with 2-D spectral image data. Assumes cross-dispersion (spatial) direction is axis 0 and dispersion (wavelength) direction is axis 1. If None, will extract the background from `image` used to initialize the class. Default: None. ### Returns - **spec** (Spectrum) - Spectrum object with same shape as `image`, including uncertainty. ``` -------------------------------- ### to_asdf Source: https://specreduce.readthedocs.io/en/latest/api/specreduce.wavesol1d.WavelengthSolution1D.html Serializes the wavelength solution into an ASDF file. ```APIDOC ## to_asdf(path) ### Description Serialize the wavelength solution into an ASDF file. ### Parameters - **path** (str or Path) - Required - Destination file path. - **kwargs** - Additional keyword arguments passed to serialization. ``` -------------------------------- ### Load and plot a CALSPEC standard with load_MAST_calspec Source: https://specreduce.readthedocs.io/en/latest/specphot_standards.html Loads a CALSPEC standard star from MAST or a local file using load_MAST_calspec and plots its spectrum with matplotlib. The example uses the file 'agk_81d266_stisnic_007.fits' and sets a log scale for flux. Requires matplotlib and specreduce.calibration_data. ```python import matplotlib.pyplot as plt from specreduce.calibration_data import load_MAST_calspec spec = load_MAST_calspec("agk_81d266_stisnic_007.fits") fig, ax = plt.subplots() ax.step(spec.spectral_axis, spec.flux, where="mid") ax.set_yscale('log') ax.set_xlabel(f"Wavelength ({spec.spectral_axis.unit})") ax.set_ylabel(f"Flux ({spec.flux.unit})") ax.set_title("AGK+81 266") fig.show() ``` -------------------------------- ### to_asdf Source: https://specreduce.readthedocs.io/en/latest/_modules/specreduce/wavesol1d.html Serializes the wavelength solution into an ASDF file, storing the pixel-to-wavelength transformation as a GWCS object under the 'wavelength_solution' key. The transformation is written as an analytic model, so the solution read back is identical to the one written. ```APIDOC ## to_asdf ### Description Serializes the wavelength solution into an ASDF file, storing the pixel-to-wavelength transformation as a GWCS object under the 'wavelength_solution' key. The transformation is written as an analytic model, so the solution read back is identical to the one written. ### Method to_asdf ### Parameters - **path** (str | Path) - Required - The file path where the ASDF file will be written. - **kwargs** - Optional - Additional keyword arguments passed to the ASDF writer. ### Returns None ``` -------------------------------- ### WavelengthCalibration1D Source: https://specreduce.readthedocs.io/en/latest/api/specreduce.wavecal1d.WavelengthCalibration1D.html Documentation for the WavelengthCalibration1D class, including its constructor, attributes, and methods. ```APIDOC ## WavelengthCalibration1D ### Description A class for wavelength calibration of one-dimensional spectra. It supports both direct input of line lists and observed spectra, using a polynomial model for fitting the wavelength solution. ### Constructor `WavelengthCalibration1D(arc_spectra=None, obs_lines=None, line_lists=None, unit=Unit('Angstrom'), ref_pixel=None, pix_bounds=None, line_list_bounds=None, n_strogest_lines=None, wave_air=False)` ### Parameters - **arc_spectra** (Spectrum | Sequence[Spectrum] | None) - Optional - Arc spectra provided as `Spectrum` objects for wavelength fitting. Cannot be provided simultaneously with `obs_lines`. - **obs_lines** (ArrayLike | Sequence[ArrayLike] | None) - Optional - Pixel positions of observed spectral lines for wavelength fitting. Cannot be provided simultaneously with `arc_spectra`. - **line_lists** (ArrayLike | None) - Optional - Catalogs of spectral line wavelengths. Provide either an array of line wavelengths or a list of PypeIt catalog names. If `None`, no line lists are used. - **unit** (Unit) - Optional - The unit of the wavelength calibration, default `astropy.units.Angstrom`. - **ref_pixel** (float | None) - Optional - The reference pixel in which the wavelength solution will be centered. - **pix_bounds** (tuple[int, int] | None) - Optional - Lower and upper pixel bounds for fitting, defined as a tuple (min, max). If `obs_lines` is provided, this parameter is mandatory. - **line_list_bounds** (None | tuple[float, float]) - Optional - Wavelength bounds as a tuple (min, max) for filtering usable spectral lines from the provided line lists. - **n_strogest_lines** (None | int) - Optional - The number of strongest lines to be included from the line lists. If `None`, all are included. - **wave_air** (bool) - Optional - Boolean indicating whether the input wavelengths correspond to air rather than vacuum; default `False` (vacuum). The flag is stored in the wavelength solution. ### Attributes - **catalog_line_amplitudes** - Amplitudes of the catalog lines as a list of masked arrays. - **catalog_line_locations** - Pixel positions of the catalog lines as a list of masked arrays. - **catalog_lines** - Catalog line wavelengths as a list of masked arrays. - **degree** - (No description provided) - **observed_line_amplitudes** - Amplitudes of the observed lines as a list of masked arrays. - **observed_line_locations** - Pixel positions of the observed lines as a list of masked arrays. - **observed_lines** - Pixel positions and amplitudes of the observed lines as a list of masked arrays. ### Methods - **find_lines(fwhm, noise_factor=None)** - Find lines in the provided arc spectra. - **fit_dispersion(wavelength_bounds, ...)** - Calculate a wavelength solution using all the catalog and observed lines. - **fit_lines(pixels, wavelengths, degree=None, ...)** - Fit the pixel-to-wavelength model using provided line pairs. - **match_lines(max_distance=None)** - Match the observed lines to theoretical lines. - **plot_catalog_lines(frames=None, axes=None, figsize=None, ...)** - Plot the catalog lines. - **plot_fit(frames=None, figsize=None, plot_labels=None, ...)** - Plot the fitted catalog and observed lines for the specified arc spectra. - **plot_observed_lines(frames=None, axes=None, figsize=None, ...)** - Plot observed spectral lines for the given arc spectra. - **plot_residuals(ax=None, space=None, figsize=None)** - Plot the residuals of pixel-to-wavelength or wavelength-to-pixel transformation. - **refine_fit(degree=None, max_match_distance=None, ...)** - Refine the pixel-to-wavelength transformation fit. - **remove_unmatched_lines()** - Remove unmatched lines from observation and catalog line data. - **rms(space=None)** - Compute the RMS of the residuals between matched lines in the pixel or wavelength space. ```