        Function to extract the spectra of sourced from a SExtractor catalog
        :param sextractor_filename: str. Name of the SExtractor catalog
        :param flag_threshold: SExtractor flag threshold. Sources with a flag higher than this threshold will not be extracted
        :param redmonster_format: Set to True to save the output spectra in a format redeable for Redmonster software.
        :param a_min: Minimim value for the semi-major axis of the elliptical regions. The values smaller than this will be enlarged, keeping the same a/b ratio. (Values smaller than 1 can fail, since it may be an empty (no spaxels) region)
        :param n_figure: Figure to display the extracted spectra
        :param wcs_coords: Boolean. Default: False. Set to true to use coordinates instead of pixels in the SExtractor catalog.
        :param mode: Mode of spectral extraction
        :param mag_kwrd: Keyword to save the SExtractor photometry in the header of the saved spectra
        :param npix: extraction parameter (see methods above)
        :param frac: extraction parameter (see methods above)
        :param mag_sex: SExtractor photometry to save in the header of saved spectra. Default: "MAG_AUTO"
        :param border_thresh: Minimum distance to an edge for a source to be extracted
        :param origin: Set the origin in (0,0) or (1,1). Default: 0
        :return:


        Mask, replacing with a nan, all the spaxels at distances lower than 'min_dist_to_nan_allowed' (in spaxels) to the next nan in the white_image
        :param min_dist_to_nan_allowed: Int. All spaxels at a distance (in spaxels) lower than this value to the next nan, will be masked
        :param fitsname: Str. Name of the new fits file created
        ;param reference_image: np.array(). A matrix with the same dimensions of the white image. If given, this image will be used to determine the positions to mask instead of the white.
        :return:


        Trim the edges of the cube, and creates a smaller cube. This function calls the more general function get_subsection_cube()
        :param dx: int. Number of pixels to trim in the X dimension
        :param dy: int. Number of pixels to trim in the Y dimension
        :param output_fitsname: str. Name of the new cube that will be created.
        :return:


        Returns a cube-like object with fewer wavelength elements

        :param wv_input: tuple or np.array, to define a range of wavelengths or a set of discrete wavelengths.
        :param stat: Default = False. If true, the new sub_cube will be constructed using the stat extension of the cube.
        :return: sub_cube


        Function that collapses all wavelengths available to produce a new white image
        :param new_white_fitsname: Name of the new image
        :param stat. Default = False. If True, the new white image will be done using the stat extension of the cube.
        :param Save. Default = True. If False, the new returned image will not be saved in the hard disk
        :return: white_image.


        Function to create a film, colapsing diferent wavelength ranges in which some strong emission lines would fall at certain redshifts
        :param z_ini: initial redshift
        :param z_end: final redshift
        :param dz: delta redshift
        :param outvid: name of the final video
        :param width: width of the lines that will be collapsed, in Angstroms
        :param erase: If true, the individual frames to make the video will be erased after the video is produced
        :return:


Plot two spectra for comparison purposes


    Function used to create a spectrum in the REDMONSTER software format
    :param spec: XSpectrum1D object
    :param mag: List containing 2 elements, the first is the keyword in the header that will contain the magnitud saved in the second element
    :param fitsname:  Name of the fitsfile that will be created
    :return:


Filters all pixels with values consistent with nsig*std of fluxes below floor_input
    (interpreted as being sky), and replace them with a floor_output value


Collapses the full wavelength range, but only summing voxels with flux above
    a given S/N threshold to obtain a total flux (flux) per spaxel. Each spaxel
    is then normalized by the number of wavelength pixels used (npix)

    Returns
    -------
    flux/npix, flux, npix : three images as described above


    Convert a set of PyMUSE spectra in a given directory, to the
    MARZ format: single .fits file with all the spectra in it.

    :param specdir: str, directory containing the spectra
    :param output: str, filename for MARZ output
    :return:


        Convolves an input spectrum by the spectral resolution.

        Parameters
        ----------
        wave
            Wavelength array of input spectrum
        flux
            Flux array of input spectrum
        dsig
            Optional. Native dispersion of the input spectrum. If not specified,
            the input spectrum is assumed to have perfect resolution.
            Default is None.
        wavecen
            Optional. Central wavelength of a spectral feature, to check if it falls
            in the range of a grating. Default is None, which means no check is performed.
        oversample
            Optional. Oversample the spectrum by this factor before convolution. Default
            is 1, which means no oversampling is performed. Passed to
            :py:func:`~ppxf.ppxf_util.varsmooth`.

        Returns
        -------
        np.ndarray
            Convolved spectrum.


        Make a list of instrument/grating combinations to use for convolution.
        If wavecen is not specified, all instrument/grating combinations are
        used. The length of the output list must be 1 or 2.

        If it's 2, the gratings may need to have some overlap in wavelength.
        (See get_InstGrat_waveDlam for more details.) Should probably do a check
        for this ...

        Parameters
        ----------
        wavecen
            Optional. Wavelength to check. Default is None, which means all
            instrument/grating combinations are used.

        Returns
        -------
        list
            Inst/grat objects to use for convolution. Must have a length of 1 or 2.

        Raises
        ------
        SystemExit


        Convenience method to check if the dispersion object is for MRS.

        Parameters
        ----------
        InstGratObj
            Instrument/grating to check.
        Returns
        -------
        bool
            True if the instrument/grating is MRS, False otherwise.


        Get dispersion data from a dispersion file(s). The file must be in
        FITS format. The dispersion file must have a wavelength array and
        a dispersion array. The dispersion array can be either R, dlambda,
        or dvel (delta velocity). The method chooses from these in order
        of preference dvel, R, dlambda, if more than one is present.
        It then computes R and dlambda and adds these to the object.

        The method also checks the wavelength unit in the file
        header and converts the wavelength and dispersion arrays to the
        object's wavelength unit, if necessary.

        Parameters
        ----------
        filename
            Filename and path of the dispersion file to load.

        Raises
        ------
        SystemExit


        Write dispersion file from dispersion data. Can specify the
        dispersion quantity (disp) and type (type) to write. If not
        specified, the method uses the dispersion data in the object,
        starting with R, then dlambda.

        Parameters
        ----------
        filename
            Filename and full path of the output dispersion file.
        wave
            Optional. Wavelength array. Default is None, which
            means take from the object.
        waveunit
            Optional. Wavelength unit, either 'micron' or 'Angstrom'.
            Default is None, which means use the object's wavelength unit.
        disp
            Optional. Dispersion array. Default is None, which means
            use the dispersion data in the object.
        type
            Optional. Type of dispersion. Options are 'R', 'DVEL', or 'DLAMBDA'.
            Default is 'R'.
        overwrite
            Optional. Overwrite existing dispersion file. Default is False.

        Raises
        ------
        SystemExit


        Compute R and dlam for the dispersion curve from dispersion
        value(s). If wave is not given, and the object does not have
        a wavelength array, the method uses a default wavelength array.

        The attributes R, dlam, and wave are updated.

        Parameters
        ----------
        disp : float or array
            Dispersion values.
        type : str, optional
            Type of dispersion. Options are 'R', 'DVEL', or 'DLAMBDA'.
        wave : array, optional
            Wavelength array.

        Returns
        -------
        None


Read the dispersion file.


        Write the dispersion file.

        Parameters
        ----------
        wave
            Optional. Wavelength array. Default is None, which means the object's
            wavelength array is used.
        waveunit
            Optional. Wavelength unit, either 'micron' or 'Angstrom'.
            Default is None, which means the object's wavelength unit is used.
        disp
            Optional. Dispersion array. Default is None, which means the object's
            dispersion array is used.
        type
            Optional. Type of dispersion. Default is 'R'. Options are 'R', 'DVEL',
            or 'DLAMBDA'.
        overwrite
            Optional. Overwrite existing dispersion file. Default is False.


        Write the flat dispersion file.

        Parameters
        ----------
        dispdir
            Optional. Directory to write the dispersion file. Default is None.
        wave
            Optional. Wavelength array. Default is None, which means the object's
            wavelength array is used.
        waveunit
            Optional. Wavelength unit, either 'micron' or 'Angstrom'.
            Default is None, which means the object's wavelength unit is used.
        overwrite
            Optional. Overwrite existing dispersion file. Default is False.


    Calculate resolution vs. wavelength from Jones et al. 2023
    https://ui.adsabs.harvard.edu/abs/2023MNRAS.523.2519J/abstract
    https://jwst-docs.stsci.edu/jwst-mid-infrared-instrument/miri-observing-modes/miri-medium-resolution-spectroscopy#MIRIMediumResolutionSpectroscopy-wavelengthMRSwavelengthcoverageandspectralresolution

    Assumes waveunit is 'micron', but doesn't check for it.

    Parameters
    ----------
    wave
        Wavelength array.

    Returns
    -------
    np.ndarray
        Resolving power
    np.ndarray
        Delta lambda


Generates an astropy Table of lines from the master files provided in
/data/linelist. No required parameters; by default the entire tables are read from
the linelist_air.tbl and linelist_vac.tbl, recomputed into vacuum and returned

Parameters
----------
inlines
    Optional. A list of strings to match against the 'name' part of the
    master list to return only the lines requested. Default is None, which returns all
    lines in the master list.
linelab
    Optional. Whether to return the Tex-friendly labels for the lines. Default is True.
vacuum
    Optional. Whether to return wavelengths in vacuum (returns air wavelengths if false);
    conversion is equation 3 from Morton et al. 1991 ApJSS 77 119. Default is True.
waveunit
    Optional. Output wavelength unit of 'Angstrom' or 'micron'. Default is 'micron'.

Returns
-------
Table
    Columns 'name', 'linelab', 'lines'. 'name' is the name of the line,
    'linelab' is the LaTeX-friendly label, and 'lines' is the central
    wavelength in the units requested.
    Example: 'Lyalpha', 'Ly$\\alpha$', 1215.67

Examples
--------

To get the central wavelengths in microns of all lines in Table 2 of
Smith et al. 2007 ApJ 656 770 (PAHFIT paper) plus the high-ionization
[NeVI] line typical of AGN:

>>> mylist=['H2_00_S7','H2_00_S6','H2_00_S5','[ArII]6.99','[NeVI]7.65','H2_00_S4',
...        '[ArIII]8.99','H2_00_S3','[SIV]10.51','H2_00_S2','[NeII]12.81',
...        '[NeIII]15.56','H2_00_S1','[SIII]18.71','[OIV]25.89','[FeII]25.99',
...        'H2_00_S0','[SIII]33.48','[SiII]34.82']
>>> u=linelist(mylist)

To get the central wavelengths in microns of the strongest lines in
Storchi-Bergmann et al. 2009 MNRAS 394, 1148 (NIFS spectra of AGN):

>>> mylist=['Pae','[SIII]0.9533','HeII1.0126','HeI1.0833','Pag', '[SIX]1.2524',
...        '[FeII]1.2570', 'Pab', '[FeII]1.6440', 'Br11', 'Br10','Brg',
...        '[SiVII]2.4833']
>>> u=linelist(mylist)

Will return all lines in the catalog with labels and central wavelengths
in vacuum in microns:

>>> u=linelist()

Will produce a table of vacuum wavelengths in microns for three lines
in the same order as given, and a warning there is a duplicated line
in mylist:

>>> mylist=['Paa', 'Halpha', 'Paa']
>>> u=linelist(inlines=mylist)

Will produce a table of air wavelengths in Angstroms for three lines, report
that line 'junk' is not in the line list, convert to air wavelengths and
to microns, complain that H2_00_S0 is outside the validity of the Morton's
formula for vacuum to air conversion, and remove the line lables.

>>> mylist=['Paa', 'Halpha', 'junk', 'H2_00_S0']
>>> u=linelist(inlines=mylist,vacuum=False,waveunit='Angstrom',linelab=False)

To get the central wavelength for an individual feature by name:

>>> wv=np.array(linelist(['Halpha'])['lines'])

OR

>>> u=linelist()
>>> wv=np.array(u['lines'][(u['name']=='Halpha')])


        Plot maps of properties of an emission line.

        Parameters
        ----------
        line
            Name of the line for which to create plots.
        compSort
            Optional. The 'sort_by' key
            must take one of the following values, which are keys of the dictionary output by
            :py:meth:`~q3dfit.q3dpro.Q3Dpro.get_linemap`: 'Ftot', 'Fci', 'Sig', 'v50', or 'w80'.
            The 'sort_range' key is optional and is a tuple of lists. Each list contains two
            values that define the range of the component values to be used in the sorting.
            For the nth element of the tuple, the last existing component that lies in the range
            will be the nth component in the re-sorted line maps. If 'sort_range' is not provided,
            the components will be sorted based on the absolute value of the 'sort_by' parameter.
            Default is None, which means no sorting.
        xyCenter
            Optional. Center of the plot in 0-offset spaxel coordinates. Default is None, which means
            the center is the spatial middle of the FOV.
        xyStyle
            Optional. Set this to 'kpc' to label the axes in kpc from xyCenter. Set to any other
            string to label the axes in pixels from xyCenter. Default is None, which means the axes are
            labeled in pixels from the lower left corner.
        fluxcmap
            Optional. Color palette for the flux maps. Default is 'YlOrBr_r'.
        fluxlog
            Optional. If True, plot the flux maps with a log scale. Default is False.
        ranges
            Optional. Dictionary with one or more of the following keys: 'Ftot', 'Fci', 'Sig', 'v50', 'w80'.
            The values of each key are lists of two values that define the range of the parameter to be plotted.
            Default is None, which means the full range of the parameter is plotted.
        saveData
            Optional. If True, save the plots to a file. Default is False.
        saveFormat
            Optional. Format for saving the plots. Default is 'png'.
        dpi
            Optional. Dots per inch for the saved plots. Default is 100.


        Plot map of the line ratio of two emission lines.

        Parameters
        ----------
        lineA
            Name of the first line for the line ratio.
        lineB
            Name of the second line for the line ratio.
        snrcut
            Optional. Signal-to-noise ratio cut for the line maps. Default is 3.
        vminmax
            Optional. List of two values that define the range of the line ratio to be plotted.
            Default is [None, None], which means the full range of the line ratio is plotted.
        kpc
            Optional. If True, label the axes in kpc from the galaxy center. Default is False.
        cmap
            Optional. Color palette for the line ratio map. Default is 'inferno'.
        saveData
            Optional. If True, save the plots to a file. Default is False.
        saveFormat
            Optional. Format for saving the plots. Default is 'png'.
        dpi
            Optional. Dots per inch for the saved plots. Default is 100.


        Plot usual BPT diagrams.

        Parameters
        ----------
        snrcut
            Optional. Signal-to-noise ratio cut for the line maps. Default is 3.
        kpc
            Optional. If True, label the axes in kpc from the galaxy center. Default is False.
        cmap
            Optional. Color palette for the line ratio map. Default is 'inferno'.
        saveData
            Optional. If True, save the plots to a file. Default is False.
        saveFormat
            Optional. Format for saving the plots. Default is 'png'.
        dpi
            Optional. Dots per inch for the saved plots. Default is 100.


        Re-sort the line components based on the values of a given line parameter.

        Parameters
        ----------
        linemaps
            Line maps. This equals the third output of the :py:meth:`~q3dfit.q3dpro.get_linemap`
            method.
        sort_pars
            Parameters for sorting components. See `compSort` parameter of
            :py:meth:`~q3dfit.q3dpro.make_linemap` for more information.

        Returns
        -------
        dict
            The re-sorted line maps. This is the same as the input linemaps, but with the components
            re-ordered based on the sort_by parameter.


        Load compressed file archive.

        Parameters
        ----------
        file
            Name of the .npz file to read.

        Returns
        -------
        numpy.lib.npyio.NpzFile


        Compute cumulative velocity distribution function for this line, for each spaxel.

        Parameters
        -----------
        zref
            Reference redshift for computing velocities.
        vlimits
            Limits for model velocities, in km/s.
        vstep
            Step size for model velocities, in km/s.


        Compute a velocity at % pct from one side of the CVDF.

        Parameters
        -----------
        pct
            Percentage at which to calculate velocity. Must be between 0 and 100.
        calc_from_posvel
            Optional. If True, the zero-point is at positive velocities. Default is True.

        Returns
        -------
        numpy.ndarray
            Array of size (ncols, nrows) containing the velocity at the given percentile.


        Make a map of the cumulative velocity distribution function at a given percentile.

        Parameters
        ----------
        pct
            Percentile to plot. Must be between 0 and 100.
        velran
            Optional. Range of velocities to plot, in km/s. Default is [-3e2, 3e2].
        calc_from_posvel
            Optional. If True, the zero-point is at positive velocities. Default is True.
        cmap
            Optional. Colormap to use. Default is 'RdYlBu_r'.
        center
            Optional. Location, in zero-offset spaxel coordinates, from which to compute
            axis offsets. Default is [0., 0.].
        markcenter
            Optional. Location, in axes coordinates, to mark with a star.
            Default is None.
        outfile
            Optional. Name of file to save the plot. Default is None.
        outformat
            Optional. Format of the output file. Default is 'png'.
        outdpi
            Optional. DPI of the output file. Default is 100.


Load numpy save file.


    Adapted from v1.1.7 version (circa 2017) of a routine by Michele Cappellari,
    by Weizhe Liu and Yuzo Ishikawa.

    Display vectors of square pixels at coordinates (x,y) coloured with "val".
    An optional rotation around the origin can be applied to the whole image.

    The pixels are assumed to be taken from a regular cartesian grid with
    constant spacing (like an axis-aligned image), but not all elements of
    the grid are required (missing data are OK).

    This routine is designed to be fast even with large images and to produce
    minimal file sizes when the output is saved in a vector format like PDF.

    Parameters
    ----------
    x
        2D array with the x-coordinates of the pixels.
    y
        2D array with the y-coordinates of the pixels.
    datIN
        2D array with the values of the pixels.
    AX
        The matplotlib axes to plot the image.
    VMIN
        Optional. Minimum value of the color scale. Default is np.nanmin(datIN).
    VMAX
        Optional. Maximum value of the color scale. Default is np.nanmax(datIN).
    XRAN
        Optional. Range of the x-axis: [xmin, xmax]. Default is [np.min(x), np.max(x)].
    YRAN
        Optional. Range of the y-axis: [ymin, ymax]. Default is [np.min(y), np.max(y)].
    PLOTLOG
        Optional. If True, plot the logarithm of the data. Default is False.
    CMAP
        Optional. Colormap. Default is 'RdYlBu'.
    COLORBAR
        Optional. If True, plot a colorbar. Default is False.
    TICKS
        Optional. List of ticks for the colorbar. Default is None. If None, the
        ticks are automatically determined using NTICKS.
    NTICKS
        Optional. Number of ticks for the colorbar. Default is 3. Ignored if TICKS is not None.
    AUTOCBAR
        Optional. If True, and TICKS is None, the colorbar ticks are determined using
        :py:class:`matplotlib.ticker.MaxNLocator'. If False, :py:class:`matplotlib.ticker.LinearLocator`
        is used. Default is False.
    SKIPTICK
        Optional. If True, do not plot ticks. Default is False.


    Estimate the lower- and upper-errors in the base-10 log of the ratio of two numbers x1 and x2 from
    linear errors.


Create a mask for bad pixels in an array. Set good pixels to 1 and bad pixels to BAD.


    Apply a signal-to-noise ratio cut to data. Pixels with SNR < SNRCUT are set to np.nan.

    Returns
    -------
    numpy.ndarray
        Data with bad pixels set to np.nan.
    numpy.ndarray
        Indices of good pixels.
    numpy.ndarray
        Indices of bad pixels.


Save data to a FITS file.


    Set the size of a figure based on the dimensions of the data and the desired plot size.

    Parameters
    ----------
    dim
        A 2-element ArrayLike giving the dimensions of the data.
    plotsize
        A 2-element ArrayLike giving the desired size of the plot in units of ...?

    Returns
    -------
    numpy.ndarray
        A 2-element array giving the size of the figure in units of ...?


    Handle the FITLOOP execution. In its own function due to commonality between
    single- and multi-threaded execution

    Parameters
    ----------
    nspax
        Number of spaxels to be fitted.
    colarr
        Array of column #s of spaxels to be fit (0-offset).
    rowarr
        Array of row #s of spaxels to be fit (0-offset).
    cube
        :py:class:`~q3dfit.readcube.Cube` object containing data to be fit.
    q3di
        :py:class:`~q3dfit.q3din.q3din` object containing fitting parameters.
    linelist
        Emission line labels and rest frame wavelengths, as part of an astropy Table
        output by :py:func:`~q3dfit.linelist.linelist`.
    specConv
        Instance of :py:class:`~q3dfit.spectConvol.spectConvol` specifying
        the instrumental spectral resolution convolution.
    quiet
        If False, progress messages are written to stdout.
    onefit
        If True, only one fit is performed.
    core
        Optional. Core number for multi-threaded execution. Default is 1.
    nocrash
        Optional. If set, the routine will continue with the next spaxel in case
        of a crash. Default is False.


    :py:func:`~q3dfit.q3df.q3dfit` calls this function for single-threaded execution.
    The parameters are passed through from :py:func:`~q3dfit.q3df.q3dfit` and on
    to :py:func:`~q3dfit.fitloop.fitloop`.

    Parameters
    ----------
    inobj
        Either a string with the path to the numpy save file containing the
        input initialization object :py:class:`~q3dfit.q3din.q3din`,
        or the object itself.
    cols
        Optional. Column values for spaxels to be fitted. Default is None, which means
        all columns will be fitted. If a scalar, only that column will be fitted. If a
        2-element list or array, the elements are the starting and ending columns to be
        fitted. Unity-offset values assumed.
    rows
        Optional. Row values for spaxels to be fitted. Default is None, which means
        all rows will be fitted. If a scalar, only that row will be fitted. If a
        2-element list or array, the elements are the starting and ending rows to be
        fitted. Unity-offset values assumed.
    onefit
        Optional. If set, only one fit is performed in :py:func:`~q3dfit.fitloop.fitloop`.
        Default is False.
    quiet
        Optional. If False, progress messages are written to stdout.
        Default is True.
    nocrash
        Optional. If set, the routine will continue with the next spaxel in case
        of a crash. Default is False.


    Run :py:mod:`~q3dfit.fitloop.fitloop` on a single core in a multi-core environment.
    This function is called by :py:mod:`~q3dfit.q3df_helperFunctions` when run externally.
    :py:func:`~q3dfit.q3df.q3dfit` calls :py:mod:`~q3dfit.q3df_helperFunctions`
    externally when running in a multi-core environment.

    Parameters
    ----------
    rank
        Rank of this core for MPI execution.
    size
        Number of cores available for MPI execution.
    inobj
        Either a string with the path to the numpy save file containing the
        input initialization object :py:class:`~q3dfit.q3din.q3din`,
        or the object itself.
    cols
        Optional. Column values for spaxels to be fitted. If a single-element list, only that
        column will be fitted. If a 2-element list, the elements are the starting and
        ending columns to be fitted. Unity-offset values assumed. Default is None, which
        means all columns will be fitted.
    rows
        Optional. Row values for spaxels to be fitted. If a single-element list, only that row
        will be fitted. If a 2-element list, the elements are the starting and ending
        rows to be fitted. Unity-offset values assumed. Default is None, which means
        all rows will be fitted.
    onefit
        Optional. If True, only one fit is performed in :py:func:`~q3dfit.fitloop.fitloop`,
        instead of two. Default is False.
    quiet
        Optional. If False, progress messages are written to stdout. Default is True.


    Convert a string of the form "[1, 2, 3, ...]" to a list of integers.

    Parameters
    ----------
    strArray
        The string to be converted. The string is expected to be
        a list of integers in square brackets, separated by commas; a
        single integer; or a value starting with 'N' to indicate None.

    Returns
    -------
    intList
        A list of integers, or None if the input string started with 'N'.


    Collate spaxel information together. As input, it requires a
    :py:class:`~q3dfit.q3din.q3din' object and the :py:class:`~q3dfit.q3dout.q3dout`
    objects output by the fit.

    Nothing is returned, but the result is saved to the location :py:attr:`~q3dfit.q3di.q3di.outdir'
    with the filenames :py:attr:`~q3dfit.q3di.q3di.label`.line.npz and
    :py:attr:`~q3dfit.q3di.q3di.label`.cont.npy.
    The :py:attr:`~q3dfit.q3di.q3di.label`.line.npz file contains the following
    dictionaries: emlwav, emlwaverr, emlsig, emlsigerr, emlflx, emlflxerr, emlweq, and emlncomp;
    and the values ncols, nrows. The :py:attr:`~q3dfit.q3di.q3di.label`.cont.npy file contains
    the contcube dictionary.

    Parameters
    ----------
    q3di
        :py:class:`~q3dfit.q3din.q3din` object or file name.
    cols
        Optional. Column values for spaxels to be collated. Default is None, which means
        all columns will be collated. If a scalar, only that column will be collated. If a
        2-element list, the elements are the starting and ending columns to be
        collated. Unity-offset values assumed.
    rows
        Optional. Column values for spaxels to be collated. Default is None, which means
        all columns will be collated. If a scalar, only that column will be collated. If a
        2-element list, the elements are the starting and ending columns to be
        collated. Unity-offset values assumed.
    quiet
        Optional. If True, suppresses output to stdout. Default is True.
    compsortpar
        Optional. Parameter by which to sort components. Options are 'sigma', 'flux',
        'wave'. Default is 'sigma'.
    compsortdir
        Optional. Direction in which to sort components. Options are 'up' and 'down'.
        Default is 'up'.
    ignoreres
        Optional. Parameter passed to :py:meth:`~q3dfit.q3dout.q3dout.sepfitpars`.
        If True, ignore spectral resolution in computing observed sigmas and peak fluxes.
        This is mainly for backward compatibility with old versions, which did not store the
        spectral resolution in an easily accessible way in the specConv object.
        Default is False.


    Initialize parameters for emission-line fitting.

    Parameters
    ----------
    linelist
        Emission lines to fit.
    linelistz
        Initial guess for line redshifts.
    linetie
        Line to which to tie each line.
    initflux
       Initial guess for line fluxes.
    initsig
        Initial guess for line sigmas.
    siglim
        Lower and upper limits for line sigmas.
    ncomp
        Number of components for each line.
    linevary
        Optional. Line parameter vary flags (fix/free). If set to None,
        all parameters are set to vary=True. The default is None.
    specConv
        Optional. Spectral resolution object. If set to None, no convolution
        will be performed. The default is None.
    lineratio
        Optional. Table of line ratio constraints, beyond those in the doublets table,
        https://github.com/Q3D/q3dfit/blob/main/q3dfit/data/linelists/doublets.tbl.
        The default is None. The table must contain the columns `line1`, `line2`,
        `comp`, and optionally `value`, `fixed`, `lower`, and `upper`.\n
        - `line1`/`line2`: the names of the two lines to which the ratio `line1`/`line2` applies. These are the labels found in the linelist Table.
        - `comp`: an array of velocity components (zero-indexed) on which to apply the constraints, one array for each pair of lines.
        - `value`: the initial value of `line1`/`line2`. Presently, if `value` is specified for one pair of lines, it must be specified for all. Otherwise, the initial value is determined from the data.
        - `fixed`: The ratio can be `fixed` to the initial value. Presently, if `fixed` is defined, it must be set to `True` or `False` for all pairs of line.
        - `lower`/`upper`: If the ratio is not `fixed`, `lower` and `upper` limits can also be specified. (If they are not, and the line pair is a doublet in the doublets.tbl file, then the lower and upper limits are set using the data in that file.) Presently, if `lower` or `upper` is defined here for one set of lines, it must be defined here for every pair of lines.
    waves
        Optional. Wavelength array for determining if a line is in the fit range.
        The default is None.

    Returns
    -------
    tuple[Model, Parameters]
        A tuple containing the LMFIT Model and the fit parameters.


    Generate a Gaussian model for a given set of parameters.

    Parameters
    ----------
    x
        Wavelength array.
    flx
        Flux array.
    cwv
        Central wavelength.
    sig
        Sigma.
    SPECRES
        Spectral resolution object, for convolving the Gaussian with the spectral
        resolution. The default is None.

    Returns
    -------
    numpy.ndarray
        Gaussian model.


        Initialize output line fit parameters.

        Parameters
        ----------
        linelist
            Emission line labels and rest frame wavelengths, as part of an astropy Table
            output by :py:func:`~q3dfit.linelist.linelist`. Passed directly from
            the `listlines` parameter of :py:func:`~q3dfit.fitspec.fitspec` to this function.
        linelabel
            List of lines to fit. Copy of :py:attr:`~q3dfit.q3din.q3din.lines`
            from :py:class:`~q3dfit.q3din.q3din`.
        maxncomp
            Maximum number of components. Copy of :py:attr:`~q3dfit.q3din.q3din.maxncomp`.
        line_dat
            Continuum-subtracted fluxes for emission line fit,
            from :py:func:`~q3dfit.fitspec.fitspec`. Includes data
            within the fit range.
        parinit
            Initial parameters, output from the line initialization routine.
        param
            Dictionary with parameter names as keys, and best-fit values as values.
            Copy of :py:attr:`~lmfit.model.ModelResult.best_values`.
        perror
            Parameter errors. Dictionary with parameter names as keys, and
            errors as values. Values are copies of :py:attr:`~lmfit.Parameters.stderr`.
            If there is no error in the peak flux values, or it is a NaN,
            it is set to the value computed from the error spectrum (see below).
            If `~q3dfit.q3din.q3din.perror_useresid` is set to True and
            the error from the flux residual is greater than the
            error from the covariance matrix, then the error is set to the
            value computed from the residuals (see below).
        perror_resid
            Copy of perror, but with peak flux errors computed from the
            residuals of the fit, rather than from the covariance matrix.
            The error is the standard deviation of the residuals
            in a window around the line, with the window size in pixels set by
            :py:attr:`~q3dfit.q3din.q3din.perror_residwin`.
        perror_errspec
            Copy of perror, but with peak flux errors computed from the
            error spectrum, rather than from the covariance matrix.
            The error is the median of the error spectrum
            in a window around the line, with the window size in pixels set by
            :py:attr:`~q3dfit.q3din.q3din.perror_errspecwin`.
        fitstatus
            Fit status, passed from the fitting routine. If method is set
            to 'least_squares' by :py:attr:`~q3dfit.q3din.q3din.argslinefit`, then
            this is described by the status attribute of
            :py:func:`~scipy.optimize.least_squares`. If the method is set
            to `leastsq`, then this is the `ier` integer return code from
            :py:func:`~scipy.optimize.leastsq`.
        dof
            Degrees of freedom. Copy of :py:attr:`~lmfit.model.ModelResult.nfree`.
        redchisq
            Reduced chi-squared. Copy of :py:attr:`~lmfit.model.ModelResult.redchi`.
        nfev
            Number of function evaluations. Copy of :py:attr:`~lmfit.model.ModelResult.nfev`.
        covar
            Covariance matrix. Copy of :py:attr:`~lmfit.model.ModelResult.covar`.
        errorbars
            If True, then no errors are computed for the line fit. Copy of
            :py:attr:`~lmfit.model.ModelResult.errorbars`.


        Initialize continuum fit parameters.

        Parameters
        ----------
        ct_method
            Method for continuum fit. Default is 'subtract'. Set on
            initialization of :py:class:`~q3dfit.q3din.q3din` by
            :py:attr:`~q3dfit.q3din.q3din.dividecont`.
        cont_dat
            Fluxes minus any best-fit emission-line model. Includes data
            within the fit range. Set to None until assigned by
            :py:func:`~q3dfit.fitspec.fitspec`.
        ct_indx
            Indices to cont_dat that are used for the continuum fit; i.e.,
            emission lines are masked out. Set to None until assigned by
            :py:func:`~q3dfit.fitspec.fitspec`.
        cont_fit
            Best-fit continuum model, over the fit range. Set to None until
            assigned by :py:func:`~q3dfit.fitspec.fitspec`.
        ct_coeff
            Parameters of the continuum fit. Set to None until
            assigned by :py:func:`~q3dfit.fitspec.fitspec`.  Exact form depends
            on the continuum fit function used. See module
            :py:mod:`~q3dfit.contfit` for details.
        ct_rchisq : float
            Reduced chi-squared from continuum fit. Set to None until
            assigned by :py:func:`~q3dfit.fitspec.fitspec`.
        zstar : float
            Best-fit zstar. Set to None until assigned by
            :py:func:`~q3dfit.fitspec.fitspec`.
        zstar_err : float
            Error in best-fit zstar. Set to None until assigned by
            :py:func:`~q3dfit.fitspec.fitspec`.


        Return the model flux for all fitted wavelengths in a given line and component,
        from the best-fit parameters in :py:attr:`~q3dfit.q3dout.q3dout.param`.

        Parameters
        ----------
        line
            Emission line for which to compute flux.
        comp
            Component (0-indexed) for which to compute flux.

        Returns
        -------
        np.ndarray
            Model flux evaluated at the wavelengths in :py:attr:`~q3dfit.q3dout.q3dout.wave`.


        Convert output of LMFIT, with best-fit line parameters in a single
        array, into a dictionary with separate arrays for different line
        parameters. Compute total line fluxes from the best-fit line
        parameters.

        This routine sets :py:attr:`~q3dfit.q3dout.q3dout.line_fitpars`.

        Parameters
        ----------
        waveran
            Set to upper and lower limits to return line parameters only
            for lines within the given wavelength range. Lines outside this
            range have fluxes set to 0.
        doublets
            Dictionary of doublet lines for which to combine fluxes.
        ignoreres
            Ignore spectral resolution in computing observed sigmas and peak
            fluxes. This is mainly for backward compatibility with old versions,
            which did not store the spectral resolution in an easily accessible
            way in the specConv object.


            Compute total Gaussian flux and error from normalization
            and sigma.


        Separate continuum fit parameters into individual components.

        Parameters
        ----------
        q3di
            :py:class:`~q3dfit.q3din.q3din` object with input parameters.
        decompose_qso_fit
            Optional. Decompose QSO fit if continuum fit method is
            :py:func:`~q3dfit.contfit.fitqsohost`. Default is None,
            which means True if the continuum fit method is
            :py:func:`~q3dfit.contfit.fitqsohost`, and False otherwise.
        decompose_ppxf_fit
            Optional. Decompose pPXF fit if continuum fit method
            is :py:mod:`~ppxf.ppxf`. Default is None,
            which means True if the continuum fit method is
            :py:mod:`~ppxf.ppxf`, and False otherwise.


        Line plotting function.

        Parameters
        ----------
        q3di
            :py:class:`~q3dfit.q3din.q3din` object with input parameters.
        fcn
            Name of the plotting function to use. Default is
            :py:func:`~q3dfit.plot.plotcont`.
        savefig
            If True, save the figure to a file. Default is False.
        outfile
            If savefig is True, the name of the output file to save the figure.
            Default is None, which means the output file will be named
            `<filelab>_cnt` where `<filelab>` is the path+filename set
            by :py:meth:`~q3dfit.q3dout.q3dout.load_q3dout`.
        argssavefig
            Optional. Dictionary of arguments to pass to
            :py:meth:`~matplotlib.pyplt.savefig()`. Defaults to
            {'bbox_inches': 'tight', 'dpi': 300}.
        plotargs
            Additional keyword arguments to pass to the plotting function.


        Continuum plotting function.

        Parameters
        ----------
        q3di
            :py:class:`~q3dfit.q3din.q3din` object with input parameters.
        fcn
            Name of the plotting function to use. Default is
            :py:func:`~q3dfit.plot.plotcont`.
        savefig
            If True, save the figure to a file. Default is False.
        outfile
            If savefig is True, the name of the output file to save the figure.
            Default is None, which means the output file will be named
            `<filelab>_cnt` where `<filelab>` is the path+filename set
            by :py:meth:`~q3dfit.q3dout.q3dout.load_q3dout`.
        argssavefig
            Optional. Dictionary of arguments to pass to
            :py:meth:`~matplotlib.pyplt.savefig()`. Defaults to
            {'bbox_inches': 'tight', 'dpi': 300}.
        plotargs
            Additional keyword arguments to pass to the plotting function.


        Recover the QSO-host decomposition after running questfit.

        Parameters
        ----------
        q3di
            :py:class:`~q3dfit.q3din.q3din` object.

        Returns
        -------
        numpy.ndarray
            QSO component of the fit, extincted.
        numpy.ndarray
            Host component of the fit, extincted.
        numpy.ndarray
            QSO component of the fit, intrinsic.
        numpy.ndarray
            Host component of the fit, intrinsic.


Print stellar fit parameters.


    Load :py:class:`~q3dfit.q3dout.q3dout` after it's been saved to a file. It will
    set the `<filelab>` attribute as follows, where `<outdir>` and `<label>` are the
    attributes from :py:class:`~q3dfit.q3din.q3din`, `<col>` is the column index,
    and `<row>`is the row index.\n
    - If the data are 1D, then `<filelab>` = `<outdir>/<label>.npy`.
    - If the data are 2D, then `<filelab>` = `<outdir>/<label>_<col>.npy`.
    - If the data are 3D, then `<filelab>` = `<outdir>/<label>_<col>_<row>.npy`.

    Parameters
    ----------
    q3di
        :py:class:`~q3dfit.q3din.q3din` object or file name.
    col
        Optional. Column index. None assumes 1D spectrum fits input.
        If None and cubedim > 1, will throw ValueError. Default is None.
    row
        Optional. Row index. None assumes 1D or 2D spectrum fits input.
        If None and cubedim > 2, will throw ValueError. Default is None.
    cubedim
        Optional. Dimension of cube (1, 2, or 3). If None, will try to get from q3di or
        cube itself. Default is None.
    quiet
        Optional. Suppress messages. Default is False.

    Returns
    -------
    q3dout


    This function is the core routine to fit the continuum and emission
    lines of a spectrum.

    Parameters
    ----------

    wlambda
        Spectrum, observed-frame wavelengths.
    flux
        Spectrum, fluxes.
    err
        Spectrum, flux errors.
    q3di
        Instance of :py:class:`~q3dfit.q3din.q3din` initializing the fit.
    zstar
        Optional. Initial guess for stellar redshift. Use None if no continuum
        fit is done.
    siginit_stars
        Optional. Initial guess for stellar line widths for fitting. It is created
        by :py:func:`~q3dfit.q3din.init_contfit` or specified on input. Set to None
        if no continuum fit is done.
    listlines
        Optional. Emission line labels and rest frame wavelengths, as part of an astropy
        Table output by :py:func:`~q3dfit.linelist.linelist`. Use None if no emission-line
        fit is done.
    listlinesz
        Optional. Initial guess for emission line observed frame wavelengths. Use
        None if no emission-line fit is done.
    ncomp
        Optional. Number of components fit to each line. Use None if no emission-line
        fit is done.
    linevary
        Optional. Dictionary specifying which parameters to vary for each line.
        Nested dictionary with line names as keys, and dictionaries as values.
        This is passed to :py:mod:`~q3dfit.lineinit.lineinit`, or another
        function specified in :py:attr:`~q3dfit.q3din.q3din.fcnlineinit`.
        These dictionaries have keys 'flx', 'cen', and 'sig', with boolean arrays
        as values. Default is None.
    maskwidths
        Optional. Widths, in km/s, of emission-line regions to mask from continuum fit.
        If set to None, routine will look for `maskwidths` attribute in
        :py:class:`~q3dfit.q3din.q3din`. If this is None and both continuum and emission-
        line fits are attempted, routine defaults to value
        set in `maskwidths_def` attribute of :py:class:`~q3dfit.q3din.q3din`.
    peakinit
        Optional. Initial guess for peak emission-line flux densities. If set to
        None, routine will look for `peakinit` attribute in
        :py:class:`~q3dfit.q3din.q3din`. If this is None and line fit is done,
        routine estimates from data.
    siginit_gas
        Optional. Initial guess for emission line widths for fitting. It is created
        by :py:func:`~q3dfit.q3din.init_linefit` or specified on input. Set to None
        if no emission-line fit is done.
    siglim_gas
        Optional. Sigma limits for line fitting. It is created by
        :py:func:`~q3dfit.q3din.init_linefit` or specified on input. Set to None
        if no emission-line fit is done.
    specConv
        Optional. Instance of :py:class:`~q3dfit.spectConvol.spectConvol` specifying
        the instrumental spectral resolution convolution. If None, no convolution
        is done.
    fluxunit
        Optional. Units of flux density defined in :py:class:`~q3dfit.readcube.Cube`.
        Default is None.
    waveunit
        Optional. Units of wavelength defined in :py:class:`~q3dfit.readcube.Cube`.
        Default is None.
    quiet
        Optional. If False, some progress messages are written to stdout.
        Default is True.

    Returns
    -------
    q3dout.q3dout
        Instance of :py:class:`~q3dfit.q3dout.q3dout` containing the fit results.


    Takes an array of wavelengths in air and converts them to vacuum
    using eq. 3 from Morton et al. 1991.

    Parameters
    ----------
    wv
        Input wavelengths.
    waveunit
        Optional. Wavelength unit. Default is Angstrom.

    Returns
    -------
    ndarray
        An array of the same dimensions as the input and in the same units
        as the input

    References
    ----------
    Morton 1991, ApJSS, 77, 119

    Examples
    --------
    >>> wv=np.arange(3000,7000,1)
    >>> vac_wv=airtovac(wv)
    array([3000.87467224, 3001.87492143, 3002.87517064, ..., 6998.92971915, 6999.92998844, 7000.93025774])


    Masks emission lines from the spectrum for continuum fitting

    Parameters
    ----------
    llambda
        Wavelengths of the spectrum.
    linelambda
        Dictionary with line names as keys and arrays of central wavelengths as values,
        one value per component.
    halfwidth
        Dictionary with line names as keys and arrays of half widths as values, one
        value per component; or a Table with the same structure.
    nomaskran
        Optional. Set of lower and upper wavelength limits of regions not to mask. If
        None, no regions are excluded.

    Returns
    -------
    numpy.ndarray
        Array of llambda-array indices indicating non-masked wavelengths.

    Examples
    --------
    1.  from masklin import masklin

        Generate linelist:

        from linelist import linelist
        mylist=['Halpha','Hbeta','Hgamma']
        u=linelist(inlines=mylist)

        Generate wavelength array:

        import numpy as np
        llambda=np.arange(3000.,8000.,1.)

        Generate half widths for masking:
        from astropy.table import Table
        # https://docs.astropy.org/en/stable/table/construct_table.html
        halfwidth=Table([u['name']])
        # populate another column
        # https://docs.astropy.org/en/stable/table/modify_table.html
        halfwidth['halfwidths']=6000.0
        # I have chosen a huge masking width for better visual eff
        #now use the masking function
        ind=masklin(llambda, u, halfwidth, 60.)

    # plot the spectrum without and with the masking
    from matplotlib import pyplot as plt
    plt.interactive(True)
    fig=plt.figure(1, figsize=(8,8))
    plt.clf()
    spec=1.+(llambda-3000.0)*1e-3
    plt.plot(llambda, spec, color='grey',alpha=0.3)
    plt.scatter(llambda[ind],spec[ind]+0.05,color='red',alpha=0.1,s=2)
    plt.show()

    # now let's define a no-masking array
    dontmask=np.array([[3000,4000,5000],[4000,5000,6000]])
    ind1=masklin(llambda, u, halfwidth, 60., nomaskran=dontmask)
    plt.scatter(llambda[ind1],spec[ind1]-0.05,color='blue',alpha=0.03,s=2)
    plt.show()


    This is the core routine to fit the continuum and emission lines of
    a spectrum. For single-threaded processing, the routine calls
    :py:mod:`~q3dfit.q3df_helperFunctions.q3df_oneCore`. For multi-threaded
    processing, the routine runs `:py:mod:`~q3dfit.q3df_helperFunctions`
    as a script through MPI. This in turn calls
    :py:mod:`~q3dfit.q3df_helperFunctions.q3df_multiCore`.

    Parameters
    ----------
    q3din
        Either a string with the path to the numpy save file containing the
        input initialization object :py:class:`~q3dfit.q3din.q3din`,
        or the object itself.
    cols
        Optional. Column values for spaxels to be fitted. Default is None, which means
        all columns will be fitted. If a scalar, only that column will be fitted. If a
        2-element list, the elements are the starting and ending columns to be
        fitted. Unity-offset values assumed.
    rows
        Optional. Row values for spaxels to be fitted. Default is None, which means
        all rows will be fitted. If a scalar, only that row will be fitted. If a
        2-element list, the elements are the starting and ending rows to be
        fitted. Unity-offset values assumed.
    onefit
        Optional. If set, only one fit is performed in :py:mod:`~q3dfit.fitloop.fitloop`.
        Default is False.
    ncores
        Optional. Number of cores for parallel processing. Default is 1.
    quiet
        Optional. If False, some progress messages are written to stdout.
        Default is True. If a logfile is specified in :py:class:`~q3dfit.q3din.q3din`,
        these messages are written to the logfile as well. Some messages appear only
        in the logfile.
    mpipath
        Optional. Path to the MPI executable. Default is None.
    nocrash
        Optional. If set, the routine will continue with the next spaxel in case
        of a crash. Default is False.


    Created on Tue Jun  1 13:32:37 2021
    @author: annamurphree

    Plots continuum fit of optical data (fit by fitqsohost or ppxf)
    or IR data (fit by questfit).

    Parameters
    ----------
    q3do
        :py:class:`~q3dfit.q3dout.q3dout` object containing results of fit.
    savefig
        Optional. If True, saves the plot to a file. Defaults to False.
    outfile
        Optional. Full path and name of output plot. Defaults to None, which
        means no output file is created.
    argssavefig
        Optional. Dictionary of arguments to pass to
        :py:meth:`~matplotlib.pyplt.savefig()`. Defaults to
        {'bbox_inches': 'tight', 'dpi': 300}.
    questfit
        Optional. If True, indicates that the fit is an IR spectrum fit by
        questfit. Defaults to False.
    q3di
        Optional. :py:class:`~q3dfit.q3din.q3din` object containing fit initialization.
        Only needed for IR spectra fit by questfit. Defaults to None.
    compspec
        Optional. Array of component spectra to overplot on continuum data.
        If None, no components are overplotted.
    complabs
        Optional. List of labels for component spectra. Defaults to None, which
        means labels are automatically generated as 'Component 1', 'Component 2', etc.
    compcols
        Optional. List of colors for component spectra. Defaults to None, which
        means colors are automatically generated as 'C0', 'C1', etc.
    title
        Optional. Title for the plot. Defaults to None.
    xran
        Optional. Range of x-axis (wavelength) to plot. If None, applies the
       `fitrange` attribute of :py:class:`~q3dfit.q3dout.q3dout`.
    yran
        Optional. Range of y-axis (flux) to plot. If None, the y-axis limits
        are determined automatically based on the data.
    zeroymin
        Optional. If True, sets the minimum y-axis value to 0. Defaults to False.
    xstyle
        Optional. Style of x-axis scale, either 'log' or 'lin'. Defaults to 'lin'.
    ystyle
        Optional. Style of y-axis scale, either 'log' or 'lin'. Defaults to 'lin'.
    figsize
        Optional. Size of the figure in inches, specified as a tuple (width, height).
        Defaults to (10, 5).
    mode
        Optional. Plot style, either 'dark' or 'light'. Defaults to 'dark'.
        This affects the background color and text color of the plot.
    waveunit_in
        Optional. Input wavelength unit, either 'micron' or 'Angstrom'.
        Defaults to 'micron'.
    waveunit_out
        Optional. Output wavelength unit, either 'micron' or 'Angstrom'.
        If None, defaults to waveunit_in.
    fluxunit_out
        Optional. Output flux unit, either 'flambda', 'lambdaflambda', or 'fnu'.
        Defaults to 'flambda'. The input flux unit is always 'flambda'. Choosing
        'lambdaflambda' multiplies the flux by wavelength (in the units of
        waveunit_out), and 'fnu' multiplies the flux by wavelength^2/c,
        where c is the speed of light in the units of waveunit_out.


    Plot emission line fit and output to JPG

    Parameters
    ----------
    q3do
        :py:class:`~q3dfit.q3dout.q3dout` object containing the output of the
        fit.
    nx
        Number of columns in the plot grid. Defaults to 1.
    ny
        Number of rows in the plot grid. Defaults to 1.
    figsize
        Size of the figure in inches, specified as a tuple (width, height).
    line
        Optional. List of lines in which to center the subplots. If None,
        the center of the plot window is determined from center_obs or
        center_rest.
    center_obs
        Optional. List of wavelengths in the observed frame to center the
        subplots. If None, the center of the plot window is determined from
        line or center_rest.
    center_rest
        Optional. List of wavelengths in the rest frame to center the
        subplots. If None, the center of the plot window is determined from
        line or center_obs.
    waveunit_in
        Optional. Input wavelength unit, either 'micron' or 'Angstrom'.
        Defaults to 'micron'.
    waveunit_out
        Optional. Output wavelength unit, either 'micron' or 'Angstrom'.
        If None, defaults to waveunit_in.
    specConv
        Optional. :py:class:`~q3dfit.spectConvol.spectConvol` object for
        spectral convolution. If None, no convolution is applied.
    size
        Optional. Size of the plot window in Angstroms. If a single float is
    savefig
        Optional. If True, saves the plot to a file. Defaults to False.
    outfile
        Optional. Full path and name of output plot. Defaults to None, which
        means no output file is created.
    argssavefig
        Optional. Dictionary of arguments to pass to
        :py:meth:`~matplotlib.pyplt.savefig()`. Defaults to
        {'bbox_inches': 'tight', 'dpi': 300}.


        CB: Function defined to adjust the sizes of xlabel, ylabel, and the
        ticklabels (in an inelegant way for the latter).

        Presently just a utility function to be used in plotquest.

        Further documentation pending more testing and development.

        Parameters
        -----
        ax: matplotlib axis object
        ax object of the plot you want to adjust

        fig: matplotlib fig object
        fig object that contains the ax object

        returns
        -------
        Nothing


    Calls plotquest to plot the quasar-host galaxy decomposition. Not sure what
    the difference is between this and plotquest.

    Further documentation pending more testing and development.


    Plot the fit to the residual of the quasar-host galaxy decomposition, if
    refit is done with questfit. This function is presently only called
    internally by :py:func:`~q3dfit.contfit.fitqsohost`.

    Further documentation pending more testing and development.


    Blackbody model function

    Parameters
    -----
    wave
        1-D array of the wavelength to be fit, in microns.
    a
        Scale factor for blackbody model after it is normalized to its maximum value.
    T
        Temperature of the blackbody in Kelvin.

    returns
    -------
    BB_model: array


    Powerlaw model

    Parameters
    ----------
    wave
        1-D array of the wavelength to be fit.
    a
        Scale factor the powerlaw model.
    b
        Exponent for powerlaw.

    returns
    -------
    np.ndarray


    Scale a model by a factor a.

    Parameters
    -----
    model
        The model to be scaled.
    a
        Scale factor.

    Returns
    -------
    np.ndarray


    Automatically search for "good" components.

    Parameters
    ----------
    linepars
        :py:attr:`~q3dfit.q3dout.q3dout.line_fitpars` attribute of
        :py:class:`~q3dfit.q3dout.q3dout`
    linetie
        :py:attr:`~qrdfit.q3din.q3din.linetie` attribute of
        :py:class:`~q3dfit.q3din.q3din`
    ncomp
        # of components for each fitted line.
    siglim
        Sigma limits for emission lines.
    sigcut
        Optional. Sigma threshold in flux for rejection of a component.
        Default is 3.
    subone
        Optional. If True, remove only one component if multiple lines are found to be
        insignificant. Useful when degeneracy between components
        lowers significance for all components, but some components
        still exist. Default is False.
    ignore
        Optional. Array of lines to ignore in looking for good copmonents,
        array of string-typed elements. Default is empty list.

    Returns
    -------
    dict[str, int]
        # of good components for each unique linetie anchor. The input ncomp is also
        updated to reflect correct new # of components.


    (Linearly) interpolate templates from template wavelength grid to data
    wavelength grid.

    Parameters
    ----------
    spec_lam
        Wavelengths of data arrays.
    temp_lam
        Wavelengths of template arrays.
    template
        Model fluxes from templates. Second dimension is the number of
        templates.

    Returns
    -------
    ArrayLike
        The interpolated templates.


    This function samples a single template or list of templates onto
    the wavelength array of the input observed spectrum.  The output is
    padded with NaN values instead of extrapolating beyond any template's
    wavelength range.

    Parameters
    ----------
    spec_lam
        reference wavelength array onto which the templates(s) are interpolated
    temp_lam_lis
        Template wavelength array or list containing the wavelength arrays of the
        different templates (not required to be at same length). (Also accepts 1D list,
        list containing a 1D array, or list of lists)
    template_lis
        Template flux array or list containing the flux arrays of the different templates
        (not required to be at same length). (Also accepts 1D list, list containing a 1D
        array, or list of lists)

    Returns
    -------
    numpy.ndarray
        Array containing the flux of the templates interpolated onto the spec_lam input
        array.
        If 2D, the 2nd dimension corresponds to the flux arrays of individual templates,
        i.e. the newly sampled flux of template 0 can be accessed as new_temp[:,0], while
        for template 1 this is new_temp[:,1], etc. The new_temp array is padded with NaN
        values where the wavelength range of the respective template was more narrow than
        the observed spectum.


    This function removes any NaN values from the output of the interp_lis() function.

    Parameters
    ----------
    spec_lam
        reference wavelength array onto which the templates(s) are interpolated
    new_temp
        1D or 2D array with newly interpolated template fluxes, corresponding to the
        output of interp_lis()

    Returns
    -------
    new_temp_NoNan
        Same as new_temp, but without any NaN elements / rows containing at least one NaN
        value


    Write message to log file and/or :py:func:`~sys.stdout`.

    Parameters
    ----------
    message
        Message to be written
    logfile
        Optional. Filename for progress messages. Default is None, which
        means no message is written to a file.
    quiet
        Optional. Suppress progress messages to stdout. Default is True.


    Model exponentials for qso template multiplier

    Parameters
    -----
    wave
        1-D array of wavelengths
    qsotemplate
        1-D array of the quasar spectrum to be fit
    a
        scale factor for constant term
    b
        scale factor for exponential decay
    c
        exponential decay constant
    d
        scale factor for exponential decay in reverse
    e
        exponential decay constant in reverse
    f
        scale factor for exponential rise
    g
        exponential rise constant
    h
        scale factor for exponential rise in reverse
    i
        exponential rise constant in reverse

    Returns
    -------
    np.ndarray
        Multiplicative factor times the quasar spectrum


    Model legendre polys for qso template multiplier

    Parameters
    ----------
    wave
        1-D array of wavelengths
    qsotemplate
        1-D array of the quasar spectrum to be fit
    i,j,k,l,m,n,o,p,q,r
        scale factors for 1-10 order legendre polynomials. 0th order
        is the constant term and is set to 0.

    Returns
    -------
    np.ndarray
        Multiplicative factor times the quasar spectrum


    Model legendre for additive starlight continuum

    Parameters
    ----------
    wave
        1-D array of wavelengths
    i,j,k,l,m,n,o,p,q,r
        scale factors for 1-10 order legendre polynomials. 0th order
        is the constant term and is set to 0.

    Returns
    -------
    np.ndarray
        Polynomial model for the additive starlight continuum


    Model exponentials for additive starlight continuum

    Parameters
    ----------
    wave
        1-D array of the wavelength to be fit
    a
        scale factor for constant term
    b
        scale factor for exponential decay
    c
        exponential decay constant
    d
        scale factor for exponential decay in reverse
    e
        exponential decay constant in reverse
    f
        scale factor for exponential rise
    g
        exponential rise constant
    h
        scale factor for exponential rise in reverse
    i
        exponential rise constant in reverse

    Returns
    -------
    np.ndarray
        Exponential model for the additive starlight continuum


    Set up or evaluate the model for the QSO and host galaxy featureless
    continuum fit.

    Parameters
    ----------
    wave
        1-D array of wavelengths
    params_fit
        Optional. Dictionary of parameters to evaluate the model. If None,
        the function returns the lmfit model object and parameter object for fitting.
        If not None, the function returns the model evaluated at the
        parameters in params_fit.
    qsoflux
        Optional. 1-D array of the quasar template flux. Only needed if
        params_fit is not None.
    qsoonly
        Optional. Fit/evaluate only the QSO component. Default is False.
    qsoord
        Optional. Order of the Legendre polynomial for the QSO template multiplier.
        Default is None, which means no Legendre polynomial is used. The maximum
        order is 10.
    hostonly
        Optional. Fit/evaluate only the host galaxy component. Default is False.
    hostord
        Optional. Order of the Legendre polynomial for the host galaxy template
        multiplier. Default is None, which means no Legendre polynomial is used.
        The maximum order is 10.
    blronly
        Optional. Fit/evaluate only the scattered-light broad line region component.
        Default is False.
    blrpar
        Optional. Array of parameters for the broad line region model. Only needed
        if scattered light broad line region component is included. Default is None.
        Must be in the form [amplitude, center, sigma, amplitude, center, sigma, ...],
        where each set of three parameters is for a single Gaussian component.
        The center is not varied in the fit, and the bounds on the sigma are set to
        2000 and 6000 km/s.
    medflux
        Optional. Estimate for the continuum level for setting initial guesses.
        Default is None, which sets the continuum level to 1.

    Returns
    -------
    tuple
        If params_fit is not None, returns a tuple of the evaluated model,
        None, None. If params_fit is None, returns a tuple of None, the lmfit
        model object, and the lmfit parameters object.


    Creates a table of emission lines expected to be found in a given
    instrument configuration for JWST. The 'observed' column displays a
    redshifted emission line center calculated using the input z value.
    Therefore, it is only as precise as the known z value.

    References stored under q3dfit/data/linelists are .tbl of filenames:

    lines_H2.tbl
    lines_DSNR_micron.tbl
    lines_TSB.tbl
    lines_ref.tbl
    lines_PAH.tbl

    Data for instrument configurations in microns can be found in
    q3dfit/data/jwst_tables in the files:

    miri.tbl
    nirspec.tbl

    String inputs are not case sensitive, but must be entered with exact
    spelling. Otherwise, the function will return errors.

    Parameters
    ----------
    z
        Galaxy, systemic redshift. Used for redshifting emission lines
        for 'observed' column.
    gal
        Galaxy name for filenaming.
        Can also be customized for any other desired filename designations
    instrument
        JWST instrument. Inputs: NIRSpec, MIRI
        Used to grab the right table for each instrument.
    mode
        Instrument mode.
        NIRSpec Inputs: IFU, MOS, FSs, BOTS
        MIRI Inputs: MRS
    grat_filt
        Grating and filter combination for NIRSpec or channel for MIRI.
        NIRSpec Inputs:
        G140M_F0701P, G140M_F1001P, G235M_F1701P, G395M_F2901P,
        G140H_F0701P, G140H_F1001P, G235H_F1701P, G395H_F2901P, Prism_Clear
        MIRI Inputs:
        Ch1_A, Ch1_B, Ch1_C, Ch2_A, Ch2_B, Ch2_C, Ch3_A, Ch3_B, Ch3_C,
        Ch4_A, Ch4_B, Ch4_C
    waveunit
        Optional. Determines the unit of input wavelengths and output table.
        Inputs are 'micron' or 'Angstrom'. Default is 'micron'.
    outdir
        Optional. Output directory. Default is None, meaning no output file is saved.

    Returns
    --------
    Table
        An astropy table of emission lines with keywords 'name', 'lines',
        'linelab', 'observed'.
        Example Row: H2_43_Q6, 2.98412, H$_2$(4-3) Q(6), 4.282212
        Internally, everything is processed in microns, so filename inclues
        range values in microns.
        The units of the table can be Angstroms or microns, depending on the
        entered value of waveunit.
        Output table contains comments descring data sources


    Similar to jwstline(), observedlinez() produces a table with emission lines
    in the provided range.
    Unlike jwstline(), this function can solve for a user-specified range of
    wavelengths and can account for air wavelength conversions.
    The column 'observed' accounts for both redshifting and air refraction.
    It reports an expected center for an emission distribution and can be used
    to identify unknown emission lines for fitting.

    All input wavelengths are assumed to be REDSHIFTED!

    References stored under q3dfit/data/linelists are .tbl of filenames:

        lines_H2.tbl
        lines_DSNR_micron.tbl
        lines_TSB.tbl
        lines_ref.tbl
        lines_PAH.tbl

    More tables can be added manually if saved in the linelists folder and
    called in this function definition.

    Parameters
    ----------

    z
        Galaxy redshift
    gal
        Galaxy name for filenaming.
        Can also be customized for any other desired filename designations
    lamb_min
        minimum <OBSERVED> wavelength value of instrument, units determined by
        waveunit value
    lamb_max
        maximum <OBSERVED> wavelength of instrument, units determined by waveunit
        value
    vacuum
        Optional. If false, enables conversion to air wavelengths.
        Default is True, meaning all wavelengths are in vacuum.
    waveunit
        Optional. Determines the unit of input wavelengths and output table.
        Inputs are 'micron' or 'Angstrom'. Default is 'micron'.
    outdir
        Optional. Output directory. Default is None, meaning no output file is saved.

    Returns
    --------
    Table
        An astropy table of emission lines with keywords 'name', 'lines',
        'linelab', 'observed'
        Example Row: H2_43_Q6, 2.98412, H$_2$(4-3) Q(6), 4.282212
        Interanlly, everything is processed in microns, so filename inclues
        range values in microns.
        The units of the table can be Angstroms or microns, depending on the
        entered value of waveunit.

        Output table contains comments descring data sources


    Similar to jwstlinez() and  observedlinez(), restline() produces a table
    with emission lines in the provided range.
    Unlike the other 2 linelist functions, this function has REST wavelength
    lamb_min and lamb_max inputs.
    This function is useful for identifying various emissions in a rest
    spectrum for fitting and analysis.
    In this way, the funtion operates a lot like a search function.

    All input wavelengths are assumed to be in the REST FRAME!

    References stored under q3dfit/linelists are .tbl of filenames:

        lines_H2.tbl
        lines_DSNR_micron.tbl
        lines_TSB.tbl
        lines_ref.tbl

    More tables can be added manually if saved in the linelists folder and
    called in this function definition.

    Parameters
    ----------
    gal
        Galaxy name for filenaming.
        Can also be customized for any other desired filename designations
    lamb_min
        minimum <REST> wavelength value of instrument, units determined by
            waveunit value
    lamb_max
        maximum <REST> wavelength of instrument, units determined by waveunit value
    waveunit
        Optional. Determines the unit of input wavelengths and output table.
        Inputs are 'micron' or 'Angstrom'. Default is 'micron'.
    outdir
        Optional. Output directory. Default is None, meaning no output file is saved.

    Returns
    --------
    Table
        An astropy table of emission lines with keywords 'name', 'lines',
        'linelab'
        Example Row: H2_43_Q6, 2.98412, H$_2$(4-3) Q(6), 4.282212
        Interanlly, everything is processed in microns, so filename inclues
        range values in microns.
        The units of the table can be Angstroms or microns, depending on the
        entered value of waveunit.
        Output table contains comments descring data sources


    Read the BPASS templates into a dictionary. Templates located
    here: https://bpass.auckland.ac.nz/14.html. Download the gzipped
    tarball of the desired version and alpha-enhancement. Unpack it
    into a directory, and pass the path to the directory to this function.

    From p 14 of the v2.3 manual:
    These files contain the primary output of BPASS, which is the stellar spectral
    energy distribution (SED). Flux values are given every 1 Angstrom in the
    range 1 - 100,000 A. Most users will wish to resample to lower resolution,
    depending on their use case. We caution that some of the stellar atmospheres
    we use also have slightly lower spectral resolution.
    Each file has 52 columns and 105 rows. The first column lists a wavelength
    in angstroms, and each remaining column n (n>1) holds the model flux for the
    population at an age of 10^(6+0.1*(n-2)) years at that wavelength.
    The units of flux are Solar Luminosities per Angstrom, normalised for a
    cluster of 1e6 Msun formed in a single instantaneous burst. The total
    luminosity of the SED can be simply calculated by summing all the rows
    together. Or the flux over the wavelength range from, for example, 2000 to
    3000 Angstroms can be calculated by summing the 2000th to 3000th rows.

    Parameters
    ----------
    infile
        The path to the BPASS template files.
    outfile
        The path to the output file where the numpy save file
        will be written. Should have a .npy extension.
    waverange
        Optional. The wavelength range to use for the templates, expressed in
        Angstroms. Defaults to [1., 100000.].
    binary
        Optional. If True, the models with binary star evolution will be used.
        Defaults to False.
    zs
        Optional. The metallicities to include. The options are
        [0.001,0.002,0.003,0.004,0.006,0.008,0.010,0.014,0.020,0.030,0.040].
        Defaults to all metallicities.


    Fit the continuum as a polynomial.

    Parameters
    ----------
    wave
        Wavelengths
    flux
        Fluxes
    weight
        Weights
    index
        Points used in the fit.
    logfile
        Optional. Name of the log file. Default is None.
    quiet
        Optional. Suppress output to stdout? Default is True.
    fitord
        Optional. Order of the polynomial. Default is 3.
    refit
        Optional. Refit with a different polynomial order? If so, set to dictionary
        with keys 'ord' and 'ran' for the order and range of the
        refit, respectively. Can specify multiple ranges and orders as
        array_like. Default is None.

    Returns
    -------
    np.ndarray
        best fit continuum model
    dict[str, ArrayLike]
        Dictionary with single key-value pair, 'poly' and the polynomial coefficients.
    None
        Unused
    None
        Unused


    Fit the continuum using a quasar template and a stellar template. Calls
    :py:func:`~q3dfit.qsohostfcn.qsohostfcn` to jointly fit the quasar and host
    galaxy components. Calls :py:func:`~ppxf.ppxf` or :py:func:`~q3dfit.contfit.questfit`
    to refit the residual after subtracting the quasar component.

    Additional keywords can be passed to :py:meth:`~lmfit.model.Model.fit` by passing
    them as keyword arguments to this function. Arguments to the :py:mod:`~scipy.optimize`
    functions can be passed by setting the keyword argument `argslmfit` to a dictionary of
    parameter names and values as keys and values. Arguments to
    :py:func:`~q3dfit.contfit.questfit` for the `refit` can be passed by setting the
    keyword argument `args_questfit` to a dictionary of parameter names and values as
    keys and values.

    Parameters
    -----
    wave
        Wavelengths
    flux
        Fluxes
    weight
        Weights
    index
        Points used in the fit.
    logfile
        Optional. Name of the log file. Default is None.
    quiet
        Optional. Suppress output to stdout? Default is True.
    fitran
        Optional. Wavelength range to fit. Default is None, to fit all wavelengths.
    qsoord
        Optional. Order of the polynomial added to the quasar multiplier.
        Default is None.
    hostord
        Optional. Order of the polynomial model for the host galaxy.
        Default is None.
    blrpar
        Optional. Parameters of the broad line region scattering model. If set,
        fit this part of the model. Set to array_like Default is None.
    qsoonly
        Optional. Fit only the quasar template. Default is False.
    hostonly
        Optional. Fit only the host galaxy. Default is False.
    blronly
        Optional. Fit only the broad line region scattering model. Default is False.
    refit
        Optional. Refit the continuum residual after subtracting the quasar.
        Options are 'ppxf' or 'questfit'. Default is None, which means no refit.
    template_wave
        Optional, but must be set if refit='ppxf'. Wavelength array of the stellar
        template used as model for stellar continuum.
    template_flux
        Optional, but must be set if refit='ppxf'. Flux array of the stellar
        template used as model for stellar continuum.
    zstar
        Optional, but must be set if refit='ppxf'. Input guess for redshift of the
        stellar continuum. Default is None.
    flux_log
        Optional, but must be set if refit='ppxf'. Flux values for the log-rebinned
        pixels.
    err_log
        Optional, but must be set if refit='ppxf'. Error values for the log-rebinned
        pixels.
    index_log
        Optional, but must be set if refit='ppxf'. Pixels used in the fit for the
        pPXF fit, as log-rebinned.
    siginit_stars
        Optional. Initial guess for the stellar velocity dispersion in km/s, used
        in the pPXF fit. Default is 50. km/s.
    add_poly_degree
         Optional. Degree of the additive polynomial for the pPXF fit. Default is
         30.
    mult_poly_degree
         Optional. Degree of the multiplicative polynomial for the pPXF fit. Default is
         0.
    av_star
        Optional. Initial guess for stellar reddening, used in the pPXF fit.
        Default is None, which means no reddening is applied.
    qsoxdr
        Path and filename for the quasar template.
    fluxunit
        Optional. Units of the flux, as defined by :py:class:`~q3dfit.readcube.Cube`.
        Default is None. Passed to :py:func:`~q3dfit.contfit.questfit` if refit='questfit'.
    waveunit
        Optional. Units of the wavelength, as defined by :py:class:`~q3dfit.readcube.Cube`.
        Default is None.

    Returns
    -------
    numpy.ndarray
        Best fit continuum model.
    dict[str, Any]
        Best fit parameters. It contains a the key 'qso_host', which contains the
        parameters as a :py:class:`~lmfit.Parameters` object. If `refit` is also set
        to True in :py:func:`~q3dfit.q3din.q3din`, then it also contains the key
        'ppxf', which contains the best fit parameters from the pPXF fit as
        another dictionary with keys 'stelmod', 'polymod', 'stelweights',
        'polyweights', 'sigma', 'sigma_err', and 'av'. If `refit` is set to
        'questfit', it will contain the best fit parameters with keys set
        by the :py:func:`~q3dfit.contfit.questfit` function.
    Optional[float]
        Best fit stellar redshift if refit='ppxf'. Otherwise, the input redshift
        or None if not set.
    Optional[float]
        Best fit stellar redshift error if refit='ppxf'. Otherwise, None.


    Fit the MIR continuum. Calls :py:func:`~q3dfit.contfit.questfitfcn` to fit the
    continuum using the templates specified in the configuration file.

    Parameters
    -----
    wave
        Wavelengths
    flux
        Fluxes
    weight
        Weights
    index
        Points used in the fit.
    quiet
        Optional. Suppress output? Default is True.
    z
        Optional. Redshift of the source, for redshifting the templates.
        Default is None.
    fluxunit
        Optional. Units of the flux, as defined by :py:class:`~q3dfit.readcube.Cube`.
        Default is None. The templates are assumed to be in f_nu. If this
        unit contains 'micron' or 'Angstrom', the flux is assumed to be in f_lambda.
        The templates are then converted to f_lambda. If None, the templates are not
        converted.
    tempdir
        Optional. Directory containing the templates, to search if default
        directory does not contain template. Default is None.
    config_file
        Configuration file for the fit.

    Returns
    -------
    numpy.ndarray
        Best fit continuum model.
    dict[str, Any]
        Best fit parameters. Key 'MIRparams' is a :py:class:`~lmfit.Parameters` object
        containing the best fit parameters. Key 'comp_best_fit' is a dictionary
        containing with key/value pairs of the component names and their values
        evaluated at the best fit parameters.
    Optional[float]
        Input redshift, if set. Otherwise, None.
    Optional[float]
        None, as the redshift error is not calculated in this function.


    Fit the continuum as a superposition of a linear fit and
    an FeII template. Optical FeII template taken from Vestergaard & Wilkes (2001).
    UV FeII template follows the PyQSOFit code (Guo et al. 2018) which uses the
    template by Shen et al. (2019). Which is in turn a composite of VW01,
    Tsuzuki et al. (2006) and Salviander et al. (2007). The UV and optical FeII
    templates are scaled up/down separately from each other.

    Parameters
    ----------
    lam
        Wavelengths
    flux
        Fluxes
    weight
        Weights
    index
        Points used in the fit.
    logfile
        Optional. Name of the log file. Default is None.
    quiet
        Optional. Suppress output to stdout? Default is True.
    specConv
        Optional. Spectral resolution object. If set to None, no convolution
        will be performed. The default is None.
    Fe_z
        Optional. Redshift of the FeII template. Default is 0.
    Fe_FWHM_opt
        Optional. The smoothing kernel of the optical FeII template,
        in km/s. Default is None, which means no smoothing.
    Fe_FWHM_uv
        Optional. The smoothing kernel of the optical FeII template,
        in km/s. Default is None, which means no smoothing.
    tempdir
        Optional. Directory containing the templates, to search if default
        directory does not contain template. Default is None.

    Returns
    -------
    numpy.ndarray
        Best fit continuum model.
    dict[str, Any]
        Best fit parameters.


    Load the Vestergaard & Wilkes 2001 FeII template; redshift it;
    convolve it with intrinsic broadening;
    and convolve it with the instrumental resolution.

    Parameters
    ----------
    filename
        Name of the FeII template file.
    Fe_z
        Optional. Redshift to apply to the FeII template. Default is None, which
        means no redshift is applied.
    Fe_FWHM
        Optional. The Gaussian smoothing kernel for the FeII template in km/s.
        Default is None, which means no smoothing is applied.
    specConv
        Optional. Instance of :py:class:`~q3dfit.spectConvol.spectConvol` specifying
        the instrumental spectral resolution convolution. Default is None, which
        means no convolution is applied.
    wavecen
        Optional. Central wavelength for creating specConv instance, to find
        proper gratings. Default is None, which means no convolution is applied.
    tempdir
        Optional. Directory containing the templates, to search if default
        directory does not contain template. Default is None.

    Returns
    -------
    np.ndarray
        Flux array of the FeII template.
    np.ndarray
        Wavelength array of the FeII template.


    Read in the configuration file for fitting with questfit.

    Parameters
    ----------
    filename
        Name of, and path, to the configuration file.

    Returns
    -------
    dict
        Dictionary with the configuration file. Keys are the names of the
        components to be fitted, values are lists with the parameters for
        the components.


Print information about the cube to stdout.


        Spatially smooth a cube. Updates the data, variance, and error attributes.

        Parameters
        ----------
        refsize
            Pixel size for smoothing algorithm.
        wavescale
            Optional. Scale smoothing size with wavelength. Default is False.
        method
            Optional. Smoothing method. Options are 'circle', 'Gaussian', and
            'boxcar'. Default is 'circle'.


        Extract the quasar spectrum and save it to a numpy file.

        Parameters
        ----------
        outpy
            Name of the numpy save file for the resulting qso spectrum.
        col
            Optional. x value of aperture center, in unity-offset
            coordinates. Default is None, in which case the cube is median-
            collapsed in wavelength and the peak spaxel is used.
        row
            Optional.yx value of aperture center, in unity-offset
            coordinates. Default is None, in which case the cube is median-
            collapsed in wavelength and the peak spaxel is used.
        norm
            Optional. Factor by which to divide output spectrum. Default is 1.
        plot
            Optional. Plot extracted spectrum. Default is True.
        radius
            Optional. Radius for circular extraction. Must be > 0. Default is 1.


        Extract a spectrum in a single spaxel or a circular aperture.

        Parameters
        ----------
        col
            x value of aperture center, in unity-offset coordinates.
        row
            y value of aperture center, in unity-offset coordinates.
        radius
            Optional. Radius for circular extraction. If 0, extract single
            spaxel. Default is 1.
        norm
            Optional. Factor by which to divide output spectrum. Default is 1.
        plot
            Optional. Plot extracted spectrum.
        ylim
            Optional. Y-axis limits for plot. Default is None, in which case
            the plot will autoscale.

        Returns
        -------
        numpy.ndarray
            Array of size nwave x (1-3), including data and var and/or dq if
            present.


        Reproject cube onto a new WCS. Overwrites the data, variance, dq, and
        error attributes. Also updates the pixel area, nrows, ncols, and
        PIXEL_A2 keyword in the header.

        Parameters
        ----------
        newheader
            Header object containing new WCS information.
        new2dshape
            2-element array containing (nrows, ncols).
        newpixarea_sqas
            Pixel area in square arcseconds.
        parallel
            Optional. Use parallel processing when computing
            reprojection. Default is True.


        Write cube to file outfile. Assumes extension order empty phu (if
        present in original fits file), datext, varext, dqext, and wmapext.

        Parameters
        ----------
        outfile
            Name of output file.


        Write extracted spectrum to disk. Assumes extension order empty phu (if
        present in original fits file), datext, varext, dqext, and wmapext.

        Parameters
        ----------
        spec
            Array of size nwave x (1-3), including data and var and/or dq if
            present.
        outfile
            Name of output file.


        Initialize line fit.

        Parameters
        ----------
        lines
            Lines to fit.
        linetie
            Optional on input. As input:
            1. Set to None to fit all lines independently.
            2. Set to a single line to tie all lines together.
            3. Set to a list of strings to tie lines in groups.
            Default is None.
        maxncomp
            Optional. Maximum possible number of velocity components in any line.
            Default is 1. Also sets the attribute :py:attr:`~q3dfit.q3din.q3din.maxncomp`.
        siginit
            Optional. Uniform initial guess for emission-line velocity dispersion in km/s.
            Default is 50. This can be overridden by setting :py:attr:`~q3dfit.q3din.q3din.siginit_gas`
            for individual lines, spaxels, and components after initialization.
        siglim_gas
            Optional. Lower and upper limits for sigma in km/s for each line, spaxel,
            and component. Default is [5., 2000.]. This can be overridden by setting
            :py:attr:`~q3dfit.q3din.q3din.siglim_gas` for individual lines, spaxels,
            and components after initialization.
        zinit
            Optional. Initial redshift in km/s to apply to each line. If zinit
            is None, try to use :py:attr:`~q3dfit.q3din.q3din.zsys_gas`. Default is None.
            This can be overridden by setting :py:attr:`~q3dfit.q3din.q3din.zinit_gas` for
            individual lines, spaxels, and components after initialization.
        fcnlineinit
            Optional. Name of routine to initialize line fit. Default is
            :py:func:`~q3dfit.lineinit.lineinit`. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.fcnlineinit`.
        argslineinit
            Optional. Arguments for the line initialization function specified by
            `fcnlineinit`. Default is an empty dict. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.argslineinit`.
        argslinelist
            Optional. Arguments for :py:func:`~q3dfit.linelist.linelist`.
            Default is an empty dict. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.argslinelist`.
        argslinefit
            Optional. Arguments for :py:func:`~lmfit.Model.fit` or
            to the fitting method selected. Default is an empty dict.
            Also sets the attribute :py:attr:`~q3dfit.q3din.q3din.argslinefit`.
            Available arguments for
            :py:func:`~lmfit.Model.fit` are 'method', 'max_nfev', and 'iter_cb',
            which can be passed as key/value pairs. If 'method' is not set, it
            defaults to 'least_squares'. If the key 'max_nfev' is not set, it
            defaults to 200*(Nfitpars+1). If the key 'iter_cb' is not set, it
            defaults to None. Any other key/value pairs are passed as
            arguments to the fitting function through the 'fit_kws' argument
            to :py:func:`~lmfit.Model.fit`.
        checkcomp
            Optional. If True, reject components using
            :py:func:`~q3dfit.checkcomp.checkcomp`. Default is True.
            Also sets the attribute :py:attr:`~q3dfit.q3din.q3din.checkcomp`.
        fcncheckcomp
            Optional. Name of routine for component rejection. Default is
            'checkcomp'. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.fcncheckcomp`.
        argscheckcomp
            Optional. Arguments for the component rejection function fcncheckcomp.
            Default is an empty dict. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.argscheckcomp`.
        perror_errspecwin
            Optional. Parameter for calculating the error on the flux peak using
            the median of the error spectrum in a window of this width in pixels,
            centered on the best-fit peak. Default is 20 pixels.
            Also sets the attribute :py:attr:`~q3dfit.q3din.q3din.perror_errspecwin`.
        perror_residwin
            Optional. Parameter for calculating the error on the flux peak using
            the standard deviation of the fit residuals in a window of this width
            centered on the best-fit peak. Default is 200 pixels. Also sets the
            attribute :py:attr:`~q3dfit.q3din.q3din.perror_residwin`.
        perror_useresid
            Optional. If True, use the flux peak error calculated from the residuals
            as the error on the flux peak if it is greater than the flux peak
            error calculated by :py:func:`~lmfit.Model.fit`. Default is False.
            Useful if the error spectrum is not reliable. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.perror_useresid`.
        quiet
            Optional. Suppress messages. Default is False.


        Initialize continuum fit.

        Parameters
        ----------
        fcncontfit
            Function to fit continuum. Assumed to be a function in
            :py:mod:`q3dfit.contfit`. Exception is :py:mod:`ppxf.ppxf`,
            for which one can specify 'ppxf'. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.fcncontfit`.
        argscontfit
            Optional. Arguments for the continuum fitting function fcncontfit.
            Default is an empty dict. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.argscontfit`.
        siginit
            Optional. Uniform initial guess for stellar velocity dispersion in km/s,
            if fitting a stellar template. Default is 50. This can be overridden by
            setting :py:attr:`~q3dfit.q3din.q3din.siginit_stars` for individual
            spaxels after initialization.
        zinit
            Optional. Initial redshift for stellar template, if fitting one. If zinit
            is None, try to use :py:attr:`~q3dfit.q3din.q3din.zsys_gas`. Default is None.
            This can be overridden by setting :py:attr:`~q3dfit.q3din.q3din.zinit_stars` for
            individual spaxels after initialization.
        dividecont
            Optional. Divide data by continuum fit. Default is to subtract.
            Also sets the attribute :py:attr:`~q3dfit.q3din.q3din.dividecont`.
        av_star
            Optional. Initial guess for A_V for stellar template fitting in
            :py:func:`~ppxf.ppxf`. Default is None, which means no extinction
            is applied. Also sets the attribute :py:attr:`~q3dfit.q3din.q3din.av_star`.
        keepstarz
            Optional. If True, don't redshift stellar template before fitting. Default
            is False. Also sets the attribute :py:attr:`~q3dfit.q3din.q3din.keepstarz`.
        maskwidths
            Optional. Prior to the first continuum fit in :py:func:`~q3dfit.fitloop.fitloop`,
            mask these half-widths, in km/s, around the emission lines to be fit.
            To use this option, specify a value for each line and component.
            If set to None and both continuum and emission-line fits are attempted,
            routine defaults to uniform value set by maskwidths_def. Default is None.
            Also sets the attribute :py:attr:`~q3dfit.q3din.q3din.maskwidths`.
        maskwidths_def
            Optional. Prior to the first continuum fit in :py:func:`~q3dfit.fitloop.fitloop`,
            mask this uniform half-width, in km/s, around each emission line to be fit.
            Default is 500. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.maskwidths_def`.
        masksig_secondfit
            Optional. When computing half-widths for masking before the second fit
            in :py:func:`~q3dfit.fitloop.fitloop`, best-fit sigmas from the
            first fit are multiplied by this number. Default is 2.
        nolinemask
            Optional. If True, don't mask emission lines before continuum fit. Default
            is False. Also sets the attribute :py:attr:`~q3dfit.q3din.q3din.nolinemask`.
        nomaskran
            Optional. ArrayLike with 2 x nreg dimensions. Set of lower and upper
            wavelength limits of regions not to mask. Default is None.
            Also sets the attribute :py:attr:`~q3dfit.q3din.q3din.nomaskran`.
        startempfile
            Optional. Name of numpy save file containing stellar templates.
            Default is None. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.startempfile`. Must be set for stellar
            template fitting to work. To create the file, use the :py:func:`~numpy.save`
            function on a dictionary containing the keys 'wave' and 'flux'.
            'wave' is a 1d numpy array with rest wavelengths. 'flux' is a 2d array,
            with the first dimension being the number of wavelengths and the second
            dimension being the number of templates. If the key 'sigma' is present,
            it is a 1d numpy array with the resolution the template(s) at each wavelength
            in the input wavelength unit. The resolution is expressed as
            the sigma of a Gaussian. This is used to convolve the
            template to the resolution of the data cube using
            :py:meth:`~q3dfit.spectConvol.spectConvol.spect_convolver`.
            If the stellar template is not in vacuum wavelengths, set
            :py:attr:`~q3dfit.q3din.q3din.startempvac` to False. If it is in
            'Angstroms' rather than 'micron', set
            :py:attr:`~q3dfit.q3din.q3din.startempwaveunit` to 'Angstrom'.
        startempwaveunit
            Optional. Wavelength unit for stellar template. Options are 'micron'
            and 'Angstroms.' Default is 'micron.' Conversion is done to
            match the output wavelength unit of the data cube,
            which is set in :py:class:`~q3dfit.readcube.Cube`. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.startempwaveunit`.
        startempvac
            Optional. Is the stellar template in vacuum wavelengths? If True and the
            data are in air wavelengths, the template is converted to air wavelengths
            in :py:func:`~q3dfit.fitspec.fitspec`. Default is True. Also sets the attribute
            :py:attr:`~q3dfit.q3din.q3din.startempvac`.
        quiet
            Optional. Suppress messages. Default is False.
        tweakcntfit
            Optional. Tweak the continuum fit using local polynomial fitting.
            Default is None. (Not yet implemented.)


        Load data cube from file. Instantiates :py:class:`~q3dfit.readcube.Cube` object.

        Parameters
        ----------
        quiet
            Optional. Suppress Cube.about(). Default is False.

        Returns
        -------
        readcube.Cube
            :py:class:`~q3dfit.readcube.Cube` object.


    Perform fitting loops over spaxels. This function calls
    :py:func:`~q3dfit.fitspec.fitspec` to fit the data.

    Parameters
    ----------

    ispax
        Value of index over which to loop.
    colarr
        Array of column #s of spaxels to be fit (0-offset).
    rowarr
        Array of row #s of spaxels to be fit (0-offset).
    cube
        :py:class:`~q3dfit.readcube.Cube` object containing data to be fit.
    q3di
        :py:class:`~q3dfit.q3din.q3din` object containing fitting parameters.
    listlines
        Emission line labels and rest frame wavelengths, as part of an astropy Table
        output by :py:func:`~q3dfit.linelist.linelist`.
    specConv
        Instance of :py:class:`~q3dfit.spectConvol.spectConvol` specifying
        the instrumental spectral resolution convolution. If None, no convolution
        is performed.
    onefit
        If set, only one fit is performed. Default is False.
    quiet
        Optional. Suppress progress messages. Default is False.