    Plot the temporal evolution of a 1D eigenmode solution, i.e.

    :math:`f(u_1, u_2, u_3, t) =
    f_1(u_1) \\exp\\left(ik_2u_2 + ik_3u_3 - i\\omega t\\right)`,

    for a particular set of coordinates :math:`(u_2, u_3)` over a time interval.

    Parameters
    ----------
    ds : LegolasDataSet
        The data set containing the eigenfunction.
    omega : complex, list[complex], np.ndarray
        The (approximate) eigenvalue of the mode(s) to visualise.
    ef_name : str
        The name of the eigenfunction to visualise.
    u2 : float
        The y or :math:`\\theta` coordinate of the eigenmode solution.
    u3 : float
        The z coordinate of the eigenmode solution.
    time : list or np.ndarray
        The time interval to visualise.
    figsize : tuple[int, int]
        The size of the figure.
    add_background : bool
        Whether to add the equilibrium background to the plot.
    use_real_part : bool
        Whether to use the real part of the eigenmode solution.
    complex_factor : complex
        A complex factor to multiply the eigenmode solution with.
    show_ef_panel : bool
        Whether to show the eigenfunction panel.
    kwargs : dict
        Additional keyword arguments to pass to :meth:`~matplotlib.pyplot.imshow`.

    Returns
    -------
    TemporalEvolutionPlot1D
        The plot object.


    Plot a 2D spatial view of the eigenmode solution, i.e.

    :math:`f(u_1, u_2, u_3, t) =
    f_1(u_1) \\exp\\left(ik_2u_2 + ik_3u_3 - i\\omega t\\right)`,

    for a particular set of coordinates. If `slicing_axis = 'z'` then a 2D view is
    created for a given slicing point along the 'z'-axis (hence a 'xy'-view), for
    `slicing_axis = 'y'` a 'xz'-view will be created. The given spatial coordinates
    `u2` and `u3` must be consistent with the slicing axis. For cylindrical geometries
    slices in both Cartesian and polar coordinates can be created.

    Parameters
    ----------
    ds : LegolasDataSet
        The data set containing the eigenfunction.
    omega : complex, list[complex], np.ndarray
        The (approximate) eigenvalue of the mode(s) to visualise.
    ef_name : str
        The name of the eigenfunction to visualise.
    u2 : float, np.ndarray
        The y or :math:`\\theta` coordinate of the eigenmode solution.
    u3 : float, np.ndarray
        The z coordinate of the eigenmode solution.
    time : float
        The time at which to visualise the eigenmode solution.
    slicing_axis : str
        The axis to slice the 2D view along, either 'z', 'y' or 'theta'
    figsize : tuple[int, int]
        The size of the figure.
    add_background : bool
        Whether to add the equilibrium background to the plot.
    use_real_part : bool
        Whether to use the real part of the eigenmode solution.
    complex_factor : complex
        A complex factor to multiply the eigenmode solution with.
    show_ef_panel : bool
        Whether to show the eigenfunction panel.
    polar : bool
        Whether to use polar coordinates for the 2D view. Only used if the
        dataset geometry is cylindrical. Default is False.
    kwargs : dict
        Additional keyword arguments to pass to the plotting function.

    Returns
    -------
    p : CartesianSlicePlot2D or CylindricalSlicePlot2D
        The plot object.


    Plot a 3D spatial view of the eigenmode solution, i.e.

    :math:`f(u_1, u_2, u_3, t) =
    f_1(u_1) \\exp\\left(ik_2u_2 + ik_3u_3 - i\\omega t\\right)`,

    for a particular set of coordinates. Several 2D slices are superimposed on each
    other for every value of :math:`u_3`.

    Parameters
    ----------
    ds : LegolasDataSet
        The data set containing the eigenfunction.
    omega : complex, list[complex], np.ndarray
        The (approximate) eigenvalue of the mode(s) to visualise.
    ef_name : str
        The name of the eigenfunction to visualise.
    u2 : float, np.ndarray
        The y or :math:`\\theta` coordinate of the eigenmode solution.
    u3 : float, np.ndarray
        The z coordinate of the eigenmode solution.
    time : float
        The time at which to visualise the eigenmode solution.
    slicing_axis : str
        The axis to slice the 2D view along, either 'z', 'y' or 'theta'
    figsize : tuple[int, int]
        The size of the figure.
    add_background : bool
        Whether to add the equilibrium background to the plot.
    use_real_part : bool
        Whether to use the real part of the eigenmode solution.
    complex_factor : complex
        A complex factor to multiply the eigenmode solution with.
    kwargs : dict
        Additional keyword arguments to pass to the plotting function.

    Returns
    -------
    p : CartesianSlicePlot3D or CylindricalSlicePlot3D
        The plot object.


    Prepares for a VTK file export of the eigenmode solution in three dimensions.
    Returns a :class:`VTKDataCube3D` object which can be used to generate VTK files.

    Parameters
    ----------
    ds : LegolasDataSet
        The data set containing the eigenfunction.
    omega : complex, list[complex], np.ndarray
        The (approximate) eigenvalue of the mode(s) to visualise.
    u2 : np.ndarray
        The y or :math:`\\theta` coordinates of the eigenmode solution.
    u3 : np.ndarray
        The z coordinates of the eigenmode solution.
    use_real_part : bool
        Whether to use the real part of the eigenmode solution.

    Returns
    -------
    VTKCartesianData or VTKCylindricalData
        Object that can be used to generate VTK files.


        Validates the slicing axis.

        Parameters
        ----------
        slicing_axis : str
            The slicing axis.
        allowed_axes : list[str]
            The list of allowed axes.

        Returns
        -------
        str
            The validated slicing axis.


        Validates the combination of u2 and slicing axis.

        Parameters
        ----------
        u2 : float
            The :math:`u_2` coordinate.
        slicing_axis : str
            The slicing axis.
        axis : str
            The coordinate axis corresponding to :math:`u_2`.

        Returns
        -------
        float
            The validated :math:`u_2` coordinate.


        Validates the combination of u3 and slicing axis.

        Parameters
        ----------
        u3 : float
            The :math:`u_3` coordinate.
        slicining_axis : str
            The slicing axis.
        axis : str
            The coordinate axis corresponding to :math:`u_3`.

        Returns
        -------
        float
            The validated :math:`u_3` coordinate.


        Updates the axes with the new solution. If a contour plot is used, the
        contour lines are cleared and redrawn. If an image plot is used, the image is
        updated.

        Parameters
        ----------
        updated_solution : np.ndarray
            The new solution.


        Called on plot refreshing, the super call clears the figure and then redraws
        everything.


        Sets all relevant plot properties.

        Parameters
        ----------
        properties : dict
            Dictionary containing the usual matplotlib properties (marker, color,
            markersize, alpha, etc.)


Adds the spectrum to the plot, makes the points pickable.


Adds the eigenfunctions to the current figure.


Adds the derived eigenfunctions to the current figure.


Splits the original 1x2 plot into a 2x2 plot.


Adds the eigenfunctions for both datasets and merges the mpl callbacks.


        Adds the derived eigenfunctions for both datasets and merges the mpl
        callbacks.


        Validates the xdata passed, does typechecking and necessary casting.
        If a string is passed, this will request the proper values based on the
        parameters.

        Parameters
        ----------
        xdata : str, list, numpy.ndarray
            The xdata used as x values on the spectrum plot.

        Returns
        -------
        xdata_values : numpy.ndarray
            The xdata values of proper length and casted to a Numpy array.


        Gets the y data based on the value of :attr:`use_squared_omega`.

        Returns
        -------
        ydata : numpy.ndarray
            The y data values, either the real or imaginary parts based on
            :attr:`use_real_parts`. Every element is an array in itself corresponding
            to the various datasets, hence depending on the gridpoints in every dataset
            the elements themselves may be of different length.


Draw method, creates the spectrum.


        Adds the continua to the plot, either interactive or not.

        Parameters
        ----------
        interactive : bool
            If `True`, makes the legend interactive.


        Adds the continua to the spectrum.

        Parameters
        ----------
        interactive : bool
            If `True`, makes the legend pickable.

        Returns
        -------
        c_handler : ~pylbo.continua.ContinuaHandler
            The legendhandler used to plot the continua.


Adds the eigenfunctions to the plot, sets the eigenfunction handler.


Adds the derived eigenfunctions to the plot, sets the eigenfunction handler.


        In case the (derived) eigenfunctions are added to the plot, the locations
        of resonance with the continua will also be drawn.
        Does nothing if the (derived) eigenfunctions are not shown.


Returns the colors for the spectrum points.


        Creates the title of the derived eigenfunction plot.

        Parameters
        ----------
        ef_name : str
            The name of the derived eigenfunction as present in the datfile.

        Returns
        -------
        name : str
            The 'new' name for the derived eigenfunction, used as title.


        Creates the title of the eigenfunction plot.
        If the eigenfunction is retransformed an 'r' is prepended if appropriate,
        along with Re/Im depending on the real/imaginary part shown.

        Parameters
        ----------
        ef_name : str
            The name of the eigenfunction as present in the datfile.

        Returns
        -------
        name : str
            The 'new' name for the eigenfunction, used as title.


        Checks if the required data is present to draw for example
        eigenfunctions, is overloaded in subclasses.


        Checks if a given event has valid attributes, this prevents triggering the
        interface when clicking on legend items, for example.

        Parameters
        ----------
        event : ~matplotlib.backend_bases.PickEvent
            The pick event.

        Returns
        -------
        bool
            `True` if all conditions are met and callbacks can be connected, `False`
            otherwise.


Clears the current figure, clears the dictionary of selected eigenvalues.


Switches between the real and imaginary part of a given function.


Increments the index of the currently selected function by 1.


Decrements the index of the currently selected function by 1.


        Toggles a retransform of a function, for example an eigenfunction
        :math:`v_r \\leftrightarrow rv_r`"


Prints all selected eigenvalues to the console as an array.


        Saves all selected eigenvalues and their eigenfunctions as a list of
        dictionaries in a .npy file. Files can be loaded with the numpy load function.


        Saves the indices of all selected eigenvalues as an array in a .npy file.
        Files can be loaded with the numpy load function.


        Counts and prints the number of zeroes of the eigenfunctions for all selected
        eigenvalues on the plot, together with eigvals.


        Returns the label used in the legend. In case of a data series, the datfile
        name is prepended.

        Parameters
        ----------
        ds : ~pylbo.data_containers.LegolasDataSet
            The current dataset
        ev_idx : int
            The index of the current eigenvalue in the corresponding array
        w : float, complex
            The eigenvalue to use in the label

        Returns
        -------
        str
            The label to use in the legend.


Creates the title of a given plot, has to be overridden in a subclass.


        Updates the plot when an event is triggered, clears and then redraws
        the functions. Rescaling of the axes is done automatically.
        Has to be overridden in a subclass.


        Determines what happens when an eigenvalue is clicked.

        Parameters
        ----------
        event : ~matplotlib.backend_bases.PickEvent
            The pick event.


        Determines what happens when a key is pressed.

        Parameters
        ----------
        event : ~matplotlib.backend_bases.KeyEvent
            The key event.


        Determines what happens when left-clicking an eigenvalue.

        Parameters
        ----------
        event : ~matplotlib.backend_bases.PickEvent
            The pick event.


        Determines what happens when right-clicking an eigenvalue.

        Parameters
        ----------
        event : ~matplotlib.backend_bases.PickEvent
            The pick event.


        Retrieves the index (in the eigenvalue array), x data coordinate and y data
        coordinate of the eigenvalue nearest to the clicked point.

        Parameters
        ----------
        event : ~matplotlib.backend_bases.PickEvent
            The pick event.

        Returns
        -------
        idx : integer
            The index of the selected point in the eigenvalue array
        xdata : float
            The x data coordinate of the selected eigenvalue
        ydata : float
            The y data coordinate of the selected eigenvalue


        Checks if the selected index has eigenfunctions associated with it, in the
        case of for example eigenfunction subsets this is not guaranteed.

        Parameters
        ----------
        ds : ~pylbo.data_containers.LegolasDataSet
            The dataset associated with the given eigenvalue index
        idx : int
            The index of the selected eigenvalue

        Returns
        -------
        bool
            Returns `True` if `idx` corresponds to an eigenvalue with eigenfunctions,
            `False` otherwise.


        For dataseries, it is possible that not all datasets in the series
        have eigenfunctions associated with them. This routine will toggle a change
        in the opacity value for datapoints with no functions, so they are
        clearly distinguishable from those who do have them.


        Calculates the locations of resonance with the continua for a specific
        eigenmode.

        Parameters
        ----------
        ef_idx : int
            The number of the eigenvalue in the dataset.

        Returns
        -------
        r_inv : dict
            Dictionary of continua names and inverted resonance locations
            (float, or None if not in domain).
        labels : dict
            Dictionary containing the corresponding labels to be printed when drawing
            the locations of resonance.


        Shows the locations of resonance with the continua.
        There is a different linestyle for every continuum.


Initialises the pylbo logger.


Completely disables logging.


    Makes a matplotlib artist pickable and adds a pickradius.
    We have to handle this separately, because for line2D items the method
    :meth:`~matplotlib.axes.Axes.set_picker` is deprecated from version 3.3 onwards.

    Parameters
    ----------
    item : ~matplotlib.artist.Artist
        The artist which will be made pickable
    pickradius : int, float
        Sets the pickradius, which determines if something is "on" the picked point.


    Does a custom enumeration with a given stepsize.

    Parameters
    ----------
    iterable : ~typing.Iterable
        The iterable to iterate over.
    start : int
        The starting value for enumerate.
    step : int
        The stepsize between enumerate values.

    Yields
    ------
    start : int
        The current index in `iterable`, incremented with `step`.
    itr : ~typing.Iterable
        The corresponding entry of `iterable`.


    Transforms a given input argument `obj` to a list. If `obj`
    is a Numpy-array or tuple, a cast to `list()` is invoked.

    Parameters
    ----------
    obj : any
        The object to transform.

    Returns
    -------
    list
        The object converted to a list.


    Transforms a given input argument `obj` to a numpy array.

    Parameters
    ----------
    obj : any
        The object to transform.

    Returns
    -------
    numpy.ndarray
        The object transformed to a numpy array.


    Solves a given cubic polynomial of the form
    :math:`ax^3 + bx^2 + cx + d = 0` using the analytical cubic root formula
    instead of the general `numpy.roots` routine.
    From `StackOverflow <https://math.stackexchange.com/questions
    15865why-not-write-the-solutions-of-a-cubic-this-way/18873#18873/>`_.

    Parameters
    ----------
    a : int, float, complex
        Cubic coefficient.
    b : int, float, complex
        Quadratic coefficient.
    c : int, float, complex
        Linear coefficient.
    d : int, float, complex
        Constant term

    Returns
    -------
    roots : np.ndarray(ndim=3, dtype=complex)
        The three roots of the cubic polynomial as a Numpy array.


    Counts the number of zeroes of an array of complex eigenfunctions by looking at
    sign changes of the real and imaginary part of the eigenfunctions.
    Doesn't include the grid endpoints in the count, since the boundary conditions are
    automatically satisfied. This only becomes accurate for eigenfunctions with enough
    oscillations and is resolution dependent. Therefore, we take the minimum
    of the number of zeroes of the real and imaginary part.

    Parameters
    ----------
    eigfuncs : numpy.ndarray
        Array of eigenfunction arrays of complex numbers.

    Returns
    -------
    nzeroes : np.ndarray(dtype=int)
        Counter array containing the number of zeroes of the real or imaginary part
        of each input eigenfunction array.


    Finds the location of resonance for eigenmode solutions having a real part that
    might overlap with a continuum range.

    Parameters
    ----------
    cont : numpy.ndarray
        Array containing the range of a specific continuum. Automatically has the same
        length as r_gauss, since it has the same shape as the equilibrium fields used
        to calculate the continua. Can be complex, but only the resonance with the real
        part is calculated.
    r_gauss : numpy.ndarray
        Array containing the grid on which equilibrium fields are defined.
    sigma : complex
        An eigenvalue solution of the generalized eigenvalue problem.

    Returns
    -------
    r_inv : None, float
        The location where there is resonance between the eigenmode and the continuum.
        Returns None if there is no resonance with the specified continuum.


    Checks the file validity of a given logfile or datfile.

    Parameters
    ----------
    file : str, ~os.PathLike
        The path to the datfile, either as a :class:`str` or
        :class:`~os.PathLike` object.

    Raises
    -------
    FileNotFoundError
        If the datfile can not be found.
    InvalidLegolasFile
        If the datfile is not a valid Legolas output file.


    Loads a single Legolas datfile.

    Parameters
    ----------
    datfile : str, ~os.PathLike
        Path to the datfile.

    Raises
    ------
    ValueError
        If `datfile` is not a single file.

    Returns
    -------
    ds : ~pylbo.data_containers.LegolasDataSet
        A dataset instance for the given datfile.


    Loads multiple Legolas datfiles.

    Parameters
    ----------
    datfiles : list, numpy.ndarray
        Paths to the datfiles that should be loaded, in list/array form. Every element
        should be a string or a ~os.PathLike object.

    Raises
    ------
    ValueError
        If an empty list or array is supplied.

    Returns
    -------
    series : ~pylbo.data_containers.LegolasDataSeries
        A dataseries instance for the given datfiles.


    Reads a Legolas log file.

    Parameters
    ----------
    logfile : str, ~os.PathLike
       The path to the logfile.
    sort : bool
       If `True`, sorts the eigenvalues in the logfile. Sorting is done first
       on the real part, then on the imaginary part.

    Returns
    -------
    eigenvalues : numpy.ndarray
       Array containing the eigenvalues from the logfile.


    Opens an interactive window to select files to open.
    Requires a visual interface.

    Returns
    -------
    files : list
        A list containing the paths to the files selected.


    Reads a string from the input stream.

    Parameters
    ----------
    istream : BinaryIO
        The input stream to read from.
    length : int
        The length of the string to read.
    amount : int, optional
        The amount of strings to read, by default 1.
    offset : int, optional
        The offset to seek to before reading, by default `None`.
    byte_order : str, optional
        The byte order to use, by default "native".

    Returns
    -------
    str, list of str
        The string(s) read from the input stream.


    Reads an integer from the input stream.

    Parameters
    ----------
    istream : BinaryIO
        The input stream to read from.
    amount : int, optional
        The amount of integers to read, by default 1.
    offset : int, optional
        The offset to seek to before reading, by default `None`.
    byte_order : str, optional
        The byte order to use, by default "native".

    Returns
    -------
    int, tuple of int
        The integer(s) read from the input stream.


    Reads a boolean from the input stream.

    Parameters
    ----------
    istream : BinaryIO
        The input stream to read from.
    offset : int, optional
        The offset to seek to before reading, by default `None`.
    byte_order : str, optional
        The byte order to use, by default "native".

    Returns
    -------
    bool
        The boolean read from the input stream.


    Reads a float from the input stream.

    Parameters
    ----------
    istream : BinaryIO
        The input stream to read from.
    amount : int, optional
        The amount of floats to read, by default 1.
    offset : int, optional
        The offset to seek to before reading, by default `None`.
    byte_order : str, optional
        The byte order to use, by default "native".

    Returns
    -------
    float, tuple of float
        The float(s) read from the input stream.


    Reads a complex from the input stream.

    Parameters
    ----------
    istream : BinaryIO
        The input stream to read from.
    amount : int, optional
        The amount of complex numbers to read, by default 1.
    offset : int, optional
        The offset to seek to before reading, by default `None`.
    byte_order : str, optional
        The byte order to use, by default "native".

    Returns
    -------
    complex, tuple of complex
        The complex number(s) read from the input stream.


    Reads a number of mixed types from the input stream.

    Parameters
    ----------
    istream : BinaryIO
        The input stream to read from.
    fmt : str
        The format string to use.
    amount : int, optional
        The amount of mixed types to read, by default 1.
    offset : int, optional
        The offset to seek to before reading, by default `None`.
    byte_order : str, optional
        The byte order to use, by default "native".

    Returns
    -------
    tuple of mixed
        The mixed types read from the input stream.


Return the original dataset.

        Returns
        -------
        Dataset object (sndata class)
            Dataset to augment.


    Obtain the full path described in a text string.

    Corrects the format of the path, allowing the use of operating system
    abbreviations (for example, './', '../' and '~' for Unix).

    Parameters
    ----------
    text : str
        Text of the path, which can include operating system abbreviations.

    Returns
    -------
    path : str
        Text of the full path, so that Python can use it.


    Return a list of all the specified scans to be ignored.

    Parameters
    ----------
    input_bad_scans : list
        Scans to be ignored, including intervals of bad scans.

    Returns
    -------
    bad_scans : list
        All scans to be ignored.


    Remove extra spaces from a text string.

    Parameters
    ----------
    input_text : str
        Input text string.

    Returns
    -------
    text : str
        Resulting text.


    Save the input YAML dictionary into a file.

    Parameters
    ----------
    dictionary : dict
        Dictionary that wants to be saved.
    file_path : str
        Path of the output file.
    default_flow_style : bool, optional
        The flow style of the output YAML file. The default is False.
    replace : bool, optional
        If True, replace the output file in case it existed. If False, load the
        existing output file and merge it with the input dictionary.
        The default is False.

    Returns
    -------
    None.


    Format the input value.

    Francesco Montesano

    Get the value and returns the value formatted.
    To have all the number of the same size they are all returned as LaTeX
    strings


    Return the common elements for the given lists of elements.

    Parameters
    ----------
    lists : list (list)
        Input lists of elements to compare.

    Returns
    -------
    default_els : list
        List of the common elements.


        Group the input data according to the specified window size.

        Function by Erik Rigtorp.

        Parameters
        ----------
        x : array
            Input data.
        window : int
            Size of the windows to group the data.

        Returns
        -------
        y : array
            Output array.


        Group the input data according to the specified window size.

        Function by Erik Rigtorp.


    Apply a sigma clip and return a mask of the remaining data.

    Parameters
    ----------
    y : array
        Input data.
    sigmas : float, optional
        Number of standard deviations used as threshold. The default is 4.0.
    iters : int, optional
        Number of iterations performed. The default is 3.

    Returns
    -------
    cond : array (bool)
        Mask of the remaining data after applying the sigma clip.


    Fit the baseline of the curve ignoring the specified windows.

    Parameters
    ----------
    x : array
        Independent variable.
    y : array
        Dependent variable.
    windows : array
        Windows that specify the regions of the data.
    smooth_size : int
        Size of the filter applied for the fitting of the baseline.

    Returns
    -------
    y3 : array
        Baseline of the curve.


    Apply a function in a rolling way, in windows of the specified size.

    Parameters
    ----------
    y : array
        Input data.
    func : function
        Function to be applied.
    size : int
        Size of the windows to group the data. It must be odd.
    **kwargs : (various)
        Keyword arguments of the function to be applied.

    Returns
    -------
    y_f : array
        Resultant array.


    Select the regions of the input array specified by the given windows.

    Parameters
    ----------
    x : array
        Input data.
    windows : array
        Windows that specify the regions of the data.
    margin : float
        Margin for the windows.

    Returns
    -------
    cond : array (bool)
        Resultant condition array.


    Fit the baseline of the curve ignoring the specified windows.

    Parameters
    ----------
    x : array
        Independent variable.
    y : array
        Dependent variable.
    windows : array
        Windows that specify the regions of the data.
    smooth_size : int
        Size of the filter applied for the fitting of the baseline.

    Returns
    -------
    yf : array
        Baseline of the curve.


    Load the spectrum from the given input file.

    Parameters
    ----------
    file : str
        Path of the plain text file (.dat) to load, without the extenxion.
    load_fits : bool
        If True, load also a .fits file and return the HDU list.

    Returns
    -------
    x : array
        Frequency.
    y : array
        Intensity.
    hdul : HDU list (astropy)
        List of the HDUs (Header Data Unit).


    Find a region of the input data that has a similar noise than the one given.

    Parameters
    ----------
    x : array
        Independent variable.
    y : array
        Dependent variable.
    rms_noise : float
        The value of the RMS used as a reference.
    windows : array, optional
        The regions of the independent variable that should be ignored.
        The default is [].
    rms_threshold : float, optional
        Maximum relative difference that can exist between the RMS noise of the
        searched region and the reference RMS noise. The default is 0.1.
    offset_threshold : float, optional
        Maximum value, in units of the reference RMS noise, that the mean value
        of the dependent variable can have in the searched region.
        The default is 0.05.
    reference_width : int, optional
        Size of the desired region, in number of channels. The default is 200.
    min_width : int, optional
        Minimum size of the desired region, in number of channels.
        The default is 120.
    max_iters : int, optional
        Maximum number of iterations that will be done to find the desired
        region. The default is 1000.

    Returns
    -------
    rms_region : list
        Frequency regions of the desired region.


Format the selected points into windows.


Obtain the complementary of the input windows for the array x.


Plot the current selected windows.


Reduce the data.


    Plot spectrum contained in the input dictionary.

    Parameters
    ----------
    spectrum : dict
        Dictionary containing the following elements of the spectrum:
            frequency : array (float)
            intensity : array (float)
            baseline : array (float)


Interact with the plot by clicking on it.


Interact with the plot when pressing a key.


Old version of calculate spin used in Bolmont's thesis 2013


    Old version of calculate spin used in all cases in Bolmont et al 2015 except
    for cases 6, 6', 6'', 6''' and 7


    For earth-like planets, calculate the planet radius factor given the planet
    mass and the percentage of rock.

    - planet_mass_type='factor': Planet mass is a factor of R_EARTH (recommended)
    - planet_mass_type='AU': Planet mass is in AU


    Calculate the keplerian orbital elements

    - target_mass: mass (typically the target planet mass+central body mass)
    - target_position: position (Axes)
    - target_velocity: position (Axes)

    In case of instead of a central massive body there are two (i.e., circumbinary
    planet), then it is necessary to provide their masses, positions and velocities
    (as list of Axes objects) and target_mass must correspond only to the planet
    mass. Order is important, for instance:

    - target_mass: planet mass
    - masses: [star1_mass, star2_mass]
    - positions: [star1_position, star2_position]
    - velocities: [star1_velocity, star2_velocity]

    It returns:

    - a: semi-major axis (in AU)
    - q: perihelion distance
    - eccentricity: eccentricity
    - i: inclination
    - p: longitude of perihelion (NOT the argument of perihelion)
    - n: longitude of ascending node
    - l: mean anomaly (or mean longitude if eccentricity < 1.e-8)
    - f: true anomaly


    Calculate the heliocentric position and velocity

    - target_mass: mass (typically the target planet mass+central body mass)
    - q: perihelion distance
    - e: eccentricity
    - i0: inclination (degrees)
    - p: longitude of perihelion
    - n0: longitude of the ascending node (degrees)
    - l: mean anomaly

    In case of instead of a central massive body there are two (i.e., circumbinary
    planet), then it is necessary to provide their masses, positions and velocities
    (as list of Axes objects) and target_mass must correspond only to the planet
    mass. Order is important, for instance:

    - target_mass: planet mass
    - masses: [star1_mass, star2_mass]
    - positions: [star1_position, star2_position]
    - velocities: [star1_velocity, star2_velocity]


Compute the spin vector.

    This function calculates the spin vector given its angular frequency,
    orbital inclination, obliquity, and the longitude of the ascending node.

    Args:
        angular_frequency (float): The angular frequency representing the magnitude of the spin.
        inclination (float): The orbital inclination of the orbit with respect to the reference plane (usually the xy-plane).
        obliquity (float): The obliquity, which is the angle between the body's rotational axis and its orbital axis.
        longitude_ascending_node (float, optional): The longitude of the ascending node of the orbit, which is the angle from the reference direction (e.g., the vernal equinox) to the point where the orbit crosses the reference plane. Defaults to 0.

    Returns:
        Axes: A vector representing the spin, with components along the x, y, and z axes.


    Wind parametrisation (Bouvier 1997):

    wind_k_factor = 4.0e-18 # K_wind = 1.6d47 cgs, which is in Msun.AU2.day
    wind_rotation_saturation = 14. * TWO_PI/25.0 # = 1.7592918860102842, wsat in units of the spin of the Sun today


Creates a directory. Same behaviour as 'mkdir -p'.


    Given a resonance as a Fraction object, and g, n M for inner and
    outer planet, the function return if there is the resonance between
    the two planets

    Parameters :
    res : a Fraction object (for instance Fraction(3,2))
    g_inner, n_inner, M_inner : g, n, M for the inner planet (in degrees)
    g_outer, n_outer, M_outer : g, n, M for the outer planet (in degrees)

    Optional parameters :
    nb_points : [50] The number of points, at the end the each time span, that we will use to test resonance
    angler_center_value : [0.] (in degrees) we will overlap all the angle, through congruence, to have angle centered over this value.
                          For instance, with 0, angle will be between -180 and +180 degrees.
    std_threshold = [20.] in degrees, the value below which we will consider that a resonant angle prove the existence of a MMR.

    Return :
    True or False

    NOTE: From a package developed by Autiwa <autiwa@gmail.com>


Generic remote data download.


Get ref file from given key in given FITS header.


    Return a list of reference filenames, as defined in the primary
    header of the given input image, necessary for calibration; i.e.,
    only those associated with ``*CORR`` set to ``PERFORM`` will be
    considered.


Return a list of RAW input files in a given ASN.


        Compare output with "truth" using appropriate
        diff routine; namely,
            ``fitsdiff`` for FITS file comparisons
            ``unified_diff`` for ASCII products.
        Parameters
        ----------
        outputs : list of tuple
            A list of tuples, each containing filename (without path)
            of CALXXX output and truth, in that order.
        raise_error : bool
            Raise ``AssertionError`` if difference is found.
        Returns
        -------
        report : str
            Report from ``fitsdiff``.
            This is part of error message if ``raise_error=True``.


This test is for level 1? FUV data


Writes a mock RAW datasets with two sets of [SCI, ERR, DQ] exts.


Writes a mock CRREJTAB file with only one row.


Write out JSON file to upload results from test to storage area.
    This function relies on the JFROG JSON schema for uploading data into
    artifactory using the Jenkins plugin.  Docs can be found at::
        https://www.jfrog.com/confluence/display/RTF/Using+File+Specs
    Parameters
    ----------
    pattern : str or list of strings
        Specifies the local file system path to test results which should be
        uploaded to Artifactory. You can specify multiple artifacts by using
        wildcards or a regular expression as designated by the regexp property.
    target : str
        Specifies the target path in Artifactory in the following format:
            [repository_name]/[repository_path]
    testname : str
        Name of test that generate the results.  This will be used to create the
        name of the JSON file to enable these results to be uploaded to Artifactory.
    recursive : bool, optional
        Specify whether or not to identify files listed in sub-directories
        for uploading.  Default: False


Compare FITS header values using keywords
    Parameters
    ----------
    left, right: str
        The FITS files to compare
    keys: list
        The header keywords to compare `left` and `right`
        (See `defaults_compare` for initial values)
    rtol: float
        The relative difference to allow when comparing two float values either
        in header values, image arrays, or table columns.
        (See `defaults_compare` for initial values)
    no_assert: boolean
        Return result object instead of asserting
    kwargs: dict
        Additional arguments to be passed to `FITSDiff`
    Returns
    -------
    None
        Assert left and right are identical


Generate list of FITS header elements to compare
    TODO: Use correct terminology
    Parameters
    ----------
    fitsobj: HDUList
        TODO
    base: str
        Primary keyword
    keywords: list
        Additional keywords to use
    limit: int
        Number of extensions
        Note: 1-indexed
    start: int
        Start with extension number
    Returns
    -------
    output: list
        Keywords to compare


Check to strings word-by-word based for word length
    The strings are checked word for word, but only for the first
    `length` characters
    Parameters
    ----------
    str1, str2: str
        The strings to compare
    length: int
        The number of characters in each word to check.
    Returns
    -------
    match: boolean
        True if the strings match


Simple http/https downloader


Determine if `url` can be resolved without error


Add suffix to file name
    Parameters
    ----------
    fname: str
        The file name to add the suffix to
    suffix: str
        The suffix to add_suffix
    range: range
        If specified, the set of indexes will be added to the
        outputs.
    Returns
    -------
    fname, fname_with_suffix
        2-tuple of the original file name and name with suffix.
        If `range` is defined, `fname_with_suffix` will be a list.


Return a copy of rowdata, sorted on sortcol.


Rotate a2displ, if MJD and DEGPERYR are in the trace table.

    Parameters
    ----------
    trace_info: rec_array
        an array of the relevant rows of the table;
        the A2DISPL column will be modified in-place if the MJD and
        DEGPERYR columns are present
    expstart: float
        exposure start time (MJD)


    Calculate the STIS empirical correction to magnitude and astrometric shift,
    given photometry results.

    Parameters
    ----------
    ycol: arr
        Y-column # of object
    net: arr
        Net photometric counts (background subtracted) measured from science image
        and scaled to cosmic-ray split exposure time (from which sky is measured)
    sky: arr
        Single-pixel sky-background estimate measured from individual cosmic-ray
        split, bias- and dark-subtracted, flat-fielded images (flt.fits) with no
        sky subtraction
    stisimage: str or None, optional
        The name of the SX2 file from which to pull the header keywords.
    mjd: float or None, optional
        Modified julian date corresponding to the start time of the 1st
        exposure, corresponds to the TEXPSTRT keyword. If stisimage file is
        defined TEXPSTRT keyword will overwrite any provided mjd value.
    nread: int or None, optional
        Number of image sets combined during CR rejection, corresponds to the
        NCOMBINE keyword. If stisimage file is defined NCOMBINE keyword will
        overwrite any provided nread value.
    ybin: int or None, optional
        Axis2 data bin size in unbinned detector pixels, corresponds to the
        BINAXIS2 keyword. If stisimage file is defined BINAXIS2 keyword will
        overwrite any provided ybin value.
    gain: float or None, optional
        The image gain, corresponds to the CCDGAIN keyword.  If stisimage file
        is defined the CCDGAIN keyword will overwrite any provided gain value.
        If the gain is 4.0, it will be upated to 4.08.
    amp: str, optional [Default: 'D']
        The amplifier used for the observation (default 'D').  Ignored if
        stisimage is provided.
    sx2: bool, optional [Default: False]
        Force the procedure to remove the top/bottom 38 rows. This is
        automatically done if the file in stisname contains '_sx2'. Default
        values is False

    Returns
    -------
    fluxc: arr
        The empirically-corrected flux (counts)
    dmagc: arr
        The empirical photometric correction (delta mag)
    dyc: arr
        The empirical astrometric correction (delta pixels)


Compares the rate of cosmic rays in the extraction box and everywhere else
    in a CCD spectroscopic image. Based on crrej_exam from `STIS ISR 2019-02
    <https://www.stsci.edu/files/live/sites/www/files/home/hst/instrumentation/stis/documentation/instrument-science-reports/_documents/201902.pdf>`_.

    Higher ratios of cosmic ray rates in the extraction box to the rest of the image
    may indicate the need to rerun stistools.ocrreject() with different parameters.

    Parameters
    ----------
    obs_ids: iter of str or str
        One of more STIS observation ID rootnames in ipppssoot format (e.g. odvkl1040).

    data_dir: str
        Directory containing both the flat fielded (_flt.fits) and extracted
        spectrum (_sx1.fits or _x1d.fits) files of the observation if using obs_ids argument.
        Defaults to current working directory.

    plot: bool
        Option to generate diagnostic plots, default=False

    plot_dir: str or None
        Directory to save diagnostic plots in if plot=True.
        Defaults to data_dir parameter

    interactive: bool
        Option to generate zoomable html plots using plotly, default=False

    verbose: bool
        Option to print some results

    Returns
    -------
    results: list of dict

        - ``rootname``: obs_id
        - ``extr_fracs``: cosmic ray rejection rates in the extraction boxes for each CR-SPLIT
        - ``outside_fracs``: cosmic ray rejection rates outside the extraction boxes for each CR-SPLIT
        - ``ratios``: ``extr_fracs``/``outside_fracs``
        - ``avg_extr_frac``: The average of ``extr_fracs``
        - ``avg_outside_frac``: The average of ``outside_fracs``
        - ``avg_ratio``: ``avg_extr_frac``/``avg_outside_frac``

    If called from the command line, prints the avg extraction, outside, and ratio values for quick verification.


Generates n distinct colors from a given colormap.

    Based on mycolorpy's gen_color() from https://github.com/binodbhttr/mycolorpy


Takes desired boundary values and colors from a matplotlib colorplot and makes a Plotly colorscale.

    Based on discrete_colorscale() from https://community.plotly.com/t/colors-for-discrete-ranges-in-heatmaps/7780


Creates a list of strings that are the positions requred for centering an evenly spaced colorbar in Plotly


Creates a visualization of where CR pixels are in a stacked image

    Parameters
    ----------
    stack_image: array
        2d array to plot

    box_lower: array
        1d array of ints of the bottom of the extraction box (0 indexed)

    box_upper: array
        1d array of ints of the top of the extraction box (0 indexed)

    split_num: int
        Number of splits in the stack

    texpt: float
        Value of total exposure time

    obs_id: str
        ipppssoot of observation

    propid: int
        proposal id of observation

    plot_dir: str
        Directory to save plot in

    interactive: bool
        If True, uses Plotly to create an interactive zoomable html plot


Creates a visualization of where CR pixels are in each subexposure

    Parameters
    ----------
    splits: list
        list of CR flagged pixels in each subexposure

    box_lower: array
        1d array of ints of the bottom of the extraction box (0 indexed)

    box_upper: array
        1d array of ints of the top of the extraction box (0 indexed)

    split_num: int
        Number of splits in the stack

    individual_exposure_times: list
        List of exposure times for each subexposure

    texpt: float
        Value of total exposure time

    obs_id: str
        ipppssoot of observation

    propid: int
        proposal id of observation

    plot_dir: str
        Directory to save plot in

    interactive: bool
        If True, uses Plotly to create an interactive zoomable html plot


Command line usage of ocrreject_exam


Return the wavelength corresponding to pixel x.

    The dispersion solution is evaluated iteratively, and the slope
    (dispersion) for Newton's method is determined numerically, using a
    difference in wavelength of one Angstrom.  Note that the evalDisp
    in this file assumes that the grating is first order.

    Parameters
    ----------
    x: float or ndarray
        a single pixel number or an array of pixel numbers
    coeff: array_like object
        a list of eight elements containing the
        dispersion coefficients as read from a STIS _dsp.fits table
    cenwave: int or float
        central wavelength, in Angstroms
    niter: int
        number of iterations

    Returns
    -------
    wavelength: float or ndarray
        a single wavelength or an array (numarray) of wavelengths,
        in Angstroms


Return the pixel corresponding to wavelength wl.

    Notes
    -----
    The expression in the calstis code is::

      x = coeff[0] +
          coeff[1] * m * wl +
          coeff[2] * m**2 * wl**2 +
          coeff[3] * m +
          coeff[4] * wl +
          coeff[5] * m**2 * wl +
          coeff[6] * m * wl**2 +
          coeff[7] * m**3 * wl**3

    This version of the function to evaluate the dispersion relation
    assumes that the grating is first order, i.e. m = 1.  The dispersion
    coefficients give one-indexed pixel coordinates (reference pixels),
    but this function converts to zero-indexed pixels.

    Parameters
    ----------
    coeff: array_like object
        a list of eight elements containing the
        dispersion coefficients as read from a STIS _dsp.fits table

    wl: float or ndarray
        a single wavelength or an array (numarray) of wavelengths,
        in Angstroms

    Returns
    -------
    pix_number: float or ndarray
        the pixel number (or array of pixel numbers) corresponding
        to the input wavelength(s); note that these are zero indexed


    Shift each image extension of an input file by N rows and write the
    new image extension to the output file.


Align spectra from different images of an imset.

    Parameters
    ----------
    input: list
        A list of input filenames.  These must be STIS flat-
        fielded (_flt) image FITS files.  This argument will accept a
        single filename or a list of filenames.
    shifts: list of int or None, optional
        A list of integers indicating the number of rows to shift
        each image of each file in the cross-dispersion (Y-) direction.
    platescale: float or None, optional
        The size of a pixel in arcseconds.  Used to convert
        the value of the POSTARG2 keyword to pixels.
    tolerance: float or None, optional
        The allowed difference between calculated shifts and
        integer pixel shifts (fraction of pixel).

    Returns
    -------
    output: list, optional
        A list of output filenames. The number of output
        filenames must match the number of input filenames.  If no output
        is given, then the _flt substring of the input file is replace by
        the _sfl substring to create an output file.  This option will
        accept a single filename or a list of filenames.

    Notes
    -----
    Author:
      - Paul Barrett (STScI)


Print a list of command-line options and arguments.


Calibrate STIS data.

    Parameters
    ----------
    input: str
        Name of the input file.

    wavecal: str
        Name of the input wavecal file, or "" (the default).  This is
        only needed if the name is not the "normal" name
        (rootname_wav.fits).

    outroot: str
        Root name for the output files, or "" (the default).  This can
        be a directory name, in which case the string must end in '/'.

    savetmp: bool
        True if calstis should not delete temporary files.

    verbose: bool
        If True, calstis will print more info.

    timestamps: bool
        If True, calstis will print the date and time at various points
        during processing.

    trailer: str
        If specified, the standard output and standard error will be
        written to this file instead of to the terminal.  Note, however,
        that if print_version or print_revision is specified, the value
        will be printed to the terminal, and any name given for the
        trailer will be ignored.

    print_version: bool
        If True, calstis will print the version number (a string) and
        then return 0.

    print_revision: bool
        If True, calstis will print the full version string and then
        return 0.

    Returns
    -------
    status: int
        0 is OK.
        1 is returned if cs0.e (the calstis host executable) returned a
        non-zero status.  If verbose is True, the value returned by cs0.e
        will be printed.
        2 is returned if the specified input file or files were not found.


TEAL interface for the calstis function.


Expand environment variable in a file name.

    If the input file name begins with either a Unix-style or IRAF-style
    environment variable (e.g. $lref/name_dqi.fits or lref$name_dqi.fits
    respectively), this routine expands the variable and returns a complete
    path name for the file.

    Parameters
    ----------
    filename: str
        A file name, possibly including an environment variable.

    Returns
    -------
    fullname: str
        The file name with environment variable expanded.


Interpolate.

    Linear interpolation is used.  If the specified indpendent variable
    value xp is outside the range of the array x, the first (or last)
    value in values will be returned.

    Parameters
    ----------
    x: a sequence object, e.g. an array, int or float
        Array of independent variable values.
    values:  a sequence object, e.g. an array (not character)
        Array of dependent variable values.
    xp: int or float
        Independent variable value at which to interpolate.

    Returns
    -------
    interp_vals: the same type as one element of values
        Linearly interpolated value.


Rectify 2-D STIS spectral data.

    Parameters
    ----------
    input: str
        Name of the input raw file.

    output: str
        Name of the output file, or "" (the default).  If no name was
        specified, the output name will be constructed from the input name.

    helcorr: str
        If "perform", correct for heliocentric Doppler shift.

    fluxcorr: str
        If "perform", convert to absolute flux.

    statflag: bool
        If True, compute statistics for image arrays and update keywords.

    center: bool
        If True, center the target spectrum in the cross-dispersion
        direction.  For G140L and G140M spectra, the target has at
        different times been offset to a location either above or below
        the middle of the detector, to avoid the repeller wire.  This
        argument allows more convenient comparison of data taken at
        widely different times.

    blazeshift: float or None
        Blaze shift (in pixels).  None means blazeshift is not specified.

    err_alg: str
        Algorithm for computing error estimates.  The default is "wgt_var",
        which means that the weight (for bilinear interpolation) is applied
        to the variances of the input pixels.  The alternative is
        "wgt_err", to specify that the weight should be applied to the
        errors of the input pixels.

    verbose: bool
        If True, calstis will print more info.

    timestamps: bool
        If True, calstis will print the date and time at various points
        during processing.

    trailer: str
        If specified, the standard output and standard error will be
        written to this file instead of to the terminal.  Note, however,
        that if print_version or print_revision is specified, the value
        will be printed to the terminal, and any name given for the
        trailer will be ignored.

    print_version: bool
        If True, calstis will print the version number (a string) and
        then return 0.

    print_revision: bool
        If True, calstis will print the full version string and then
        return 0.

    Returns
    -------
    status: int
        0 is OK.
        1 is returned if cs7.e (the calstis host executable) returned a
        non-zero status.  If verbose is True, the value returned by cs7.e
        will be printed.
        2 is returned if the specified input file or files were not found,
        or the numbers of input and output files (if the latter was
        specified) are not the same.


TEAL interface for the x2d function.


Perform basic 2-D calibration of STIS raw data.

    Some calibration steps are relevant only for CCD or only for MAMA, and
    since an output file of calstis or basic2d may be used as the input,
    some steps may have already been done.  Most calibration steps will not
    be done if they are not relevant or if they have already been done,
    regardless of the value of the calibration switch (e.g. flatcorr).

    Parameters
    ----------
    input: str
        Name of the input raw file.

    output: str
        Name of the output file, or "" (the default).  If no name was
        specified, the output name will be constructed from the input name.

    outblev: str
        Name of the output text file for blev info, or "" (the default).

    dqicorr: str
        If "perform", update the DQ array.

    atodcorr: str
        The analog-to-digital correction is ignored because it was never
        implemented.

    blevcorr: str
        If "perform", subtract a bias level based on the overscan values.
        (CCD only.)

    doppcorr: str
        If "perform", convolve reference files (bpixtab, darkfile,
        flatfile) as needed with the Doppler shift offset throughout the
        exposure, if Doppler correction was done on-board.  (MAMA only,
        because for the CCD Doppler correction is not done on-board.)

    lorscorr: str
        If "perform", bin high-res data to lo-res.  (MAMA only.)

    glincorr: str
        If "perform", correct for global non-linearity.  (MAMA only.)

    lflgcorr: str
        If "perform", flag local non-linearity.  (MAMA only.)

    biascorr: str
        If "perform", subtract the bias image.  (CCD only.)

    darkcorr: str
        If "perform", subtract the dark image, scaled by the exposure time
        and possibly also a temperature-dependent factor.

    flatcorr: str
        If "perform", divide by the flat field image.

    shadcorr: str
        The shutter shading correction is ignored because it was never
        implemented.

    photcorr: str
        If "perform", determine the photometric parameters and populate
        keywords PHOTFLAM, PHOTZPT, PHOTPLAM and PHOTBW.  (Imaging only.)

    statflag: bool
        If True, compute statistics for image arrays and update keywords.

    darkscale: str
        This may be used to override the time and/or temperature dependent
        scale factor that would normally be applied to the dark image
        before subtracting from the raw data.  It's a string rather than
        a float in order to accept a different scale factor for each
        image set in the input data.  calstis reads the value or values
        (separated by blanks) from the string, and if the value is greater
        than zero, it will be used instead of the value determined from
        the temperature and time.  (CCD or NUV-MAMA only.)

    verbose: bool
        If True, calstis will print more info.

    timestamps: bool
        If True, calstis will print the date and time at various points
        during processing.

    trailer: str
        If specified, the standard output and standard error will be
        written to this file instead of to the terminal.  Note, however,
        that if print_version or print_revision is specified, the value
        will be printed to the terminal, and any name given for the
        trailer will be ignored.

    print_version: bool
        If True, calstis will print the version number (a string) and
        then return 0.

    print_revision: bool
        If True, calstis will print the full version string and then
        return 0.

    Returns
    -------
    status: int
        0 is OK.
        1 is returned if cs1.e (the calstis host executable) returned a
        non-zero status.  If verbose is True, the value returned by cs1.e
        will be printed.
        2 is returned if the specified input file or files were not found,
        or if there is a mismatch between the number of input, output,
        and/or outblev files specified.


TEAL interface for the basic2d function.


    Analyze STIS target acquisition images.

    Parameters
    ----------
    raw_filename: str
        Name of the input raw file. For some raw files you will need a copy of
        the spt file in the same directory.

    update: bool
        If True, keywords associated with tastis checks will be updated.
        Default values is False.


    Read in raw and spt FITS file header keywords used in :func:`tastis`, and
    store the results in a dictionary returned by the function.

    Parameters
    ----------
    raw_filename: str
        Name of the FITS input raw file.

    spt_filename: str
        Name of the FITS spt file associated with the raw file.

    spt_exists: bool
        If True, the `spt_filename` exists in the same directory as the raw
        file.

    Returns
    -------
    keywords: dict
        dictionary containing all keywords and other data needed by
        :func:`tastis`.


    Calculate slew information used by :func:`tastis` using input data
    dictionary. THIS FUNCTION EDITS THE DICTIONARY IN PLACE.

    Parameters
    ----------
    keywords: dict
        dictionary containing all keywords and other data needed for slew
        calculation. DICTIONARY IS EDITED IN PLACE.


    Print analysis output to stdout for :func:`tastis` report.

    Parameters
    ----------
    keywords: dict
        dictionary containing all keywords and other data needed by
        :func:`tastis`.

    spt_exists: bool
        If True, the `spt_filename` exists in the same directory as the raw
        file.

    Returns
    -------
    badacq: integer (bit flag)
        Bit flag integer containing :func:`tastis` error flags.


    Print warnings output to stdout for :func:`tastis` report.

    Parameters
    ----------
    keywords: dict
        dictionary containing all keywords and other data needed by
        :func:`tastis`.

    spt_exists: bool
        If True, the `spt_filename` exists in the same directory as the raw
        file.

    Returns
    -------
    badacq: integer (bit flag)
        Bit flag integer containing :func:`tastis` error flags.


    Translate pixel values to arcsecond units

    Parameters
    ----------
    x: int, float
        Input pixel value.

    Returns
    -------
    arcsec: float
        Pixel translated to arcsecond unit.


    Translate arcsecond values to v2coordinate system.

    Parameters
    ----------
    x: int, float
        Input arcsecond value.

    y: int, float
        Input arcsecond value.

    Returns
    -------
    v2coord: float
        v2coord value.


    Translate arcsecond values to v3coordinate system.

    Parameters
    ----------
    x: int, float
        Input arcsecond value.

    y: int, float
        Input arcsecond value.

    Returns
    -------
    v3coord: float
        v3coord value.


    Return input float value rounded up to nearest tenth decimal place.

    Parameters
    ----------
    x: float
        Input value to be rounded up.

    Returns
    -------
    rounded: float
        input value rounded up to nearest tenth decimal place


Get the orbital parameters from the spt primary header.

        Parameters
        ----------
        spt: str
            Name of the support file (rootname_spt.fits)


Construct an Observation object for the current mode.

    Parameters
    ----------
    input: str
        The name of an input file.

    instrument: str
        Value of keyword INSTRUME, should be "COS" or "STIS"

    Returns
    -------
    obs: an Observation object
        Information about the observation, mostly from header keywords.


Get nextend and instrument.


Get the name of the support file.

        Returns
        -------
        spt: str
            Name of the support (_spt.fits) file.


Compute Doppler parameters.

        The following attributes will be assigned:
        orbitper:  orbital period (seconds)
        doppzero:  time (MJD) when the Doppler shift is zero and increasing
        doppmag_v:  magnitude of the Doppler shift in km/s
        doppmag:  magnitude of the Doppler shift in pixels


Convert from RA & Dec to rectangular coordinates.

        Parameters
        ----------
        ra_targ: float
            Right ascension (radians) of the target.

        dec_targ: float
            Declination (radians) of the target.

        Returns
        -------
        target: list of three floats
            Unit vector (rectangular coords.) pointing toward the target.


Compute the radial velocity.

        Parameters
        ----------
        time: float
            A particular time (MJD).

        Returns
        -------
        radial velocity: float
            The component of the velocity away from the target.


Convert radial velocity to Doppler shift in pixels.

        Parameters
        ----------
        radvel: float
            Radial velocity in km/s.

        Returns
        -------
        doppmag: str
            Maximum value of Doppler shift (pixels) over entire orbit.


Convert Doppler shift in pixels to radial velocity.

        Parameters
        ----------
        doppmag: float
            Maximum value of Doppler shift (pixels) over entire orbit.

        Returns
        -------
        radvel: float
            Radial velocity in km/s.


Compute and print the Doppler shift at intervals of dt.

        Parameters
        ----------
        dt: float
            Time interval (seconds) for printing Doppler shift throughout
            the orbit, or if dt is zero print the min and max Doppler shift
            during the orbit.


Get the location of the maximum (or minimum) of a quadratic.

        Parameters
        ----------
        y: array_like
            Values of a function at three uniformly spaced points.

        x_middle: float
            Independent variable at the middle point.

        spacing: float
            Increment in the independent variable between elements of `y`.

        Returns
        -------
        x: float
            Independent variable of the maximum (or minimum) of the
            quadratic that passes through the three uniformly spaced
            points.


Update keywords in the first extension header.

        Parameters
        ----------
        input: str
            The name of an input file (modified in-place).

        sci_ext: int
            The number of the science extension.


Compute the heliocentric velocity of the Earth.

    This function computes the radial velocity of a target based on the
    Earth's orbital velocity around the Sun.  The space motion of the
    target is not taken into account.  That is, the radial velocity is
    just the negative of the component of the Earth's orbital velocity
    in the direction toward the target.

    Parameters
    ----------
    ra_targ: float
        right ascension of the target (degrees)
    dec_targ: float
        declination of the target (degrees)
    mjd: float
        Modified Julian Date at the time of observation

    Returns
    -------
    radial_vel: float
        the radial velocity in km/s


Compute and return the velocity of the Earth at the specified time.

    This function computes the Earth's orbital velocity around the Sun
    in celestial rectangular coordinates.  The expressions are from the
    Astronomical Almanac, p C24, which gives low precision formulas for
    the Sun's coordinates.  We'll apply these formulas directly to get
    the velocity of the Sun relative to the Earth, then we'll convert to
    km per sec and change the sign to get the velocity of the Earth.

    Notes
    -----
    We get the velocity of the Sun relative to the Earth as follows:

    The velocity in the ecliptic plane with the X-axis aligned with the
    radius vector is:

      - Vx = radius_dot,
      - Vy = radius * elong_dot,
      - Vz = 0

    where:

      - radius is the radial distance from Earth to Sun
      - elong is the ecliptic longitude of the Sun
      - eps is the obliquity of the ecliptic
      - _dot means the time derivative

    Rotate in the XY-plane by elong to get the velocity in ecliptic
    coordinates::

      radius_dot * cos (elong) - radius * elong_dot * sin (elong)
      radius_dot * sin (elong) + radius * elong_dot * cos (elong)
      0

    Rotate in the YZ-plane by eps to get the velocity in equatorial
    coordinates::

       radius_dot * cos (elong) - radius * elong_dot * sin (elong)
       (radius_dot * sin (elong) + radius * elong_dot * cos (elong)) * cos (eps)
       (radius_dot * sin (elong) + radius * elong_dot * cos (elong)) * sin (eps)

    Parameters
    ----------
    mjd: float
        time, Modified Julian Date

    Returns
    -------
    vel: ndarray
        the velocity vector of the Earth around the Sun, in
        celestial coordinates (shape=(3,),ndtype=float64)


Precess target coordinates from J2000 to the date mjd.

    Notes
    -----
    target can be a single vector, e.g. [x0, y0, z0], or it can be
    a 2-D array; in the latter case, the shape should be (n,3)::

        target = [[x0, x1, x2, x3, x4],
                  [y0, y1, y2, y3, y4],
                  [z0, z1, z2, z3, z4]]

    The algorithm used in this function was based on [1]_ and [2]_.

    References
    ----------
    .. [1] Lieske, et al. 1976, Astron & Astrophys vol 58, p 1.

    .. [2] J.H. Lieske, 1979, Astron & Astrophys vol 73, 282-284.

    Parameters
    ----------
    mjd: float
        time, Modified Julian Date
    target: array_like object
        unit vector pointing toward the target, J2000 coordinates

    Returns
    -------
    vector: ndarray
        the target vector (or matrix) precessed to mjd as an
        array object of type float64 and the same shape as target,
        i.e. either (3,) or (n,3)


Find and reject cosmic rays in STIS data.

    Parameters
    ----------
    input: str
        Name of the input file or files.

    output: str
        Name of the output file.  See all for further information.

    all: bool
        If True (the default), combine all input files into one output
        file.  In this case, output should just be one file name.  If
        False, the number of input and output file names must be the same.

    crrejtab: str
        This argument may be used to override the CRREJTAB value in the
        primary headers of the input files.

    scalense: str
        If specified, this overrides SCALENSE in the CRREJTAB.

    initgues: str
        If specified, this overrides INITGUES in the CRREJTAB.  The
        allowed values are "min" and "med" and "".

    skysub: str
        If specified, this overrides SKYSUB in the CRREJTAB.  The
        allowed values are "none", "mode" and "".

    crsigmas: str
        If specified, this overrides CRSIGMAS in the CRREJTAB.  The
        value should be a comma-separated string of one or more
        integer or float values.  For each such value, calstis will
        perform one cosmic-ray-rejection cycle, with the sigma taken
        from the numerical value that was specified.

    crradius: float or None
        If not None, this overrides CRRADIUS in the CRREJTAB.  This is
        the rejection propagation radius in pixels (e.g. 1.5).  After
        finding an outlier (a cosmic ray hit), adjacent pixels can also
        be flagged and excluded.  Neighboring pixels will be rejected if
        their values are discrepant by more than crthresh * sigmas * noise,
        where noise is based on the noise model (i.e. Poisson noise and
        readout noise).

    crthresh: float or None
        If not None, this overrides CRTHRESH in the CRREJTAB.  This is the
        rejection propagation threshold (e.g. 0.8).  If crthresh = 0 then
        all adjacent pixels (see crradius) will be rejected.

    badinpdq: int or None
        If specified, this overrides BADINPDQ in the CRREJTAB.  This is a
        data quality flag (or bitwise OR of flags) to allow rejection of
        pixels in the input images when forming the "guess" image (the
        image with which to compare the input images when looking for
        outliers).

    crmask: str
        If specified, this overrides CRMASK in the CRREJTAB.  crmask =
        "yes" means that the cosmic rays that are detected should be
        flagged in the DQ (data quality) extensions of the input files.

    verbose: bool
        If True, calstis will print more info.

    timestamps: bool
        If True, calstis will print the date and time at various points
        during processing.

    trailer: str
        If specified, the standard output and standard error will be
        written to this file instead of to the terminal.  Note, however,
        that if print_version or print_revision is specified, the value
        will be printed to the terminal, and any name given for the
        trailer will be ignored.

    print_version: bool
        If True, calstis will print the version number (a string) and
        then return 0.

    print_revision: bool
        If True, calstis will print the full version string and then
        return 0.

    Returns
    -------
    status: int
        0 is OK.
        1 is returned if cs2.e (the calstis host executable) returned a
        non-zero status.  If verbose is True, the value returned by cs2.e
        will be printed.


TEAL interface for the ocrreject function.


Refine a stis spectroscopic trace.


Given a 1D array of size m, interpolates it to a size n (m < n).


Returns a spectrum trace table


reads the specified row from the 1dttab.fits


        The 'writeTrace' method performs the following steps:

          - Adds sciline-refline to all traces with the relevent OPT_ELEM,
            CENWAVE and SPORDER.
          - Writes the new trace table to the current directory.
          - Updates the SPTRCTAB keyword in the header to point to the new table.
          - Writes out fits files with the

            - science trace - '_sci'
            - the fit to the science trace - '_scifit'
            - the interpolated trace - '_interp'
            - the linear fit to the interpolated trace - '_interpfit'


Generates a trace from a science file.


Fit a gaussian to each column of an image.


Convert an events table of TIMETAG into an integrated ACCUM image.

        Parameters
        ----------
        tagfile: str
            input file that contains TIMETAG event stream. This is ordinarily a
            FITS file containing two tables. The TIMETAG data are in the table
            with EXTNAME = "EVENTS", and the "good time intervals" are in the
            table with EXTNAME = "GTI". If the GTI table is missing or empty,
            all times will be considered "good".

        output: str
            Name of the output FITS file.

        starttime: float
            Start time for integrating events, in units of seconds since the
            beginning of the exposure. The default value of None means that
            the start time will be set to the first START time in the GTI table.

        increment: float
            Time interval in seconds. The default value of None means integrate
            to the last STOP time in the GTI table, divided by rcount.

        rcount: int
            Repeat count, the number of output image sets to create. If rcount is
            greater than 1 and increment is not specified, will subdivide the total exposure time by rcount.

        highres: bool
            Create a high resolution output image? Default is False.

        allevents: bool
            If allevents is set to True, all events in the input EVENTS table will
            be accumulated into the output image. The TIME column in the EVENTS
            table will only be used to determine the exposure time, and the GTI
            table will be ignored.

        verbose: bool
            Print additional info?

        Returns
        -------


Calculate exposure time, expstart, and expstop and mask imset

        Parameters
        ----------
        starttime: float
            Start time of the imset in seconds

        stoptime: float
            Stop time of the imset in seconds

        events_data: record array
            Record array of timetag events.

        gti_data: record array
            Record array of good time intervals (GTIs).

        tzero_mjd: bool
            Modified Julian Date (MJD) corresponding to the beginning of the exposure

        Returns
        -------
        exp_time: float
            Total exposure time in seconds for the given imset. This number accounts for any exposure time lost
            to non-GTI time (if the user is not using allevents).

        expstart: float

            Start time of the imset exposure

        expstop: float

            Stop time of the imset exposure

        good_events: float
            The events list within the imset exposure time and within the GTIs.


Map timetag events to a 2d accum image array.

        Parameters
        ----------
        events_data: record array
            Record array of timetag events.

        size_x: int
            Number of pixels on axis 1 of the detector.

        size_y: int
            Number of pixels on axis 2 of the detector.

        highres: bool
            Boolean value indicating whether the output accum image is in high or low resolution.

        Returns
        -------
        accum: array
            2d image of all events in the imset on the detector.


Perform wavecal processing for STIS data.

    Parameters
    ----------
    input: str
        Names of the flt or crj file or files for the science exposure.
        The SHIFTA1 and SHIFTA2 keywords will be updated in these files,
        based on the results of processing the wavecal file(s).

    wavecal: str
        Names of the associated wavecal file or files (either raw or
        calibrated).  If this is a raw file, it will first be calibrated
        using cs1.e (basic2d), then with cs7.e (x2d) for first-order
        grating data.  These calibrated files are regarded as temporary,
        and (unless savetmp) they will be deleted when processing has
        been completed.

    debugfile: str
        If specified, debugging information will be written to a file with
        this name.  For echelle data this will be a FITS file, but for
        first-order data it will be a text file (and possibly a FITS file
        as well).

    savetmp: bool
        If wavecal is a raw wavecal file, some calibration will be
        performed, depending on mode.  If savetmp is False (the default),
        the calibrated wavecal files will be deleted after wavecal
        processing is complete.

    option: str
        If the wavecal file contains more than one image set, the shifts
        will be interpolated between wavecal exposures that bracket the
        science exposure.  This argument gives the interpolation option,
        either "linear" (the default) or "nearest".  If the science
        exposure was before the first or after the last exposure in the
        wavecal file, the shifts will be copied from the first or last
        exposure respectively.

    angle: float or None
        This argument is only relevant for echelle data for which the
        wavecal was taken with a long slit (e.g. 6X0.2).  The angles have
        not been measured accurately; they vary from one grating to
        another, and they even vary depending on location on the detector.
        This argument specifies the slit angle, in degrees measured
        clockwise from the Y axis.  Here are some approximate values:

            - E230M:  0.9 to 1.2
            - E230H:  4.9 to 6.9
            - E140H: -3.8 to -5.8

    verbose: bool
        If True, calstis will print more info.

    timestamps: bool
        If True, calstis will print the date and time at various points
        during processing.

    trailer: str
        If specified, the standard output and standard error will be
        written to this file instead of to the terminal.  Note, however,
        that if print_version or print_revision is specified, the value
        will be printed to the terminal, and any name given for the
        trailer will be ignored.

    print_version: bool
        If True, calstis will print the version number (a string) and
        then return 0, without checking any other argument.

    print_revision: bool
        If True, calstis will print the full version string and then
        return 0.

    Returns
    -------
    status: int
        0 is OK.
        1 is returned if cs4.e (the calstis host executable) returned a
        non-zero status.  If verbose is True, the value returned by cs4.e
        will be printed.
        2 is returned if the specified input file or files were not found,
        of if the numbers of input and wavecal files (or of debugfiles) are
        not the same.


Subtract a fraction of the science image from the wavecal image.


TEAL interface for the wavecal function.


Adds Poisson Confidence Interval columns to extracted spectra.
       For use with MAMA data only. Works with echelle or first-order
       spectra.

        Parameters
        ----------
        x1dfile: str
            Input MAMA x1d file from which we will calculate the poisson
            confidence interval.

        output: str
            Name of the output FITS file. Will overwrite existing file.

        verbose: bool
            Prints a completion message before function returns.

        Returns
        -------
        Nothing is returned directly, but the file is written to output.


Resample the input, correcting for geometric distortion.

    Parameters
    ----------
    input: str
        name of input file containing an image set
    output: str
        name of the output file
    wavelengths: str, optional [Default: None]
        name of the output file for wavelengths
    helcorr: str
        specify "perform" or "omit" to override header keyword
    algorithm: {'wavelet', 'kd'}
        algorithm to use in resampling the input
    trace: str or array or None
        trace array, or name of FITS table containing trace(s)
    order: int [Default: 7]
        polynomial order (an odd number, e.g. 5 or 7)
    subdiv: int [Default: 8]
        number of subpixels (a power of 2, e.g. 8 or 16)
    psf_width: float [Default: 0.]
        width of PSF for convolution (e.g. 1.3);
        0 means no convolution
    rows: tuple, optional [Default: None]
        a tuple giving the slice of rows to process; output values
        in all other rows will be set to zero.
        The default of None means all rows, same as (0, 1024)
    subsampled: str, optional [Default: None]
        name of the output file with the subsampled image
    convolved: str, optional [Default: None]
        name of the output file with the convolved image


Resample one image set, and append to output file(s).

    Parameters
    ----------
    ft: HDUList
        FITS HDUList object for the input file.

    imset: int
        one-indexed image set number
    output: str
        name of the output file
    wavelengths: str or None
        name of the output file for wavelengths
    helcorr: str, {'perform', 'omit'}
        specify "perform" or "omit" to override header keyword
    algorithm: str, {'wavelet', 'kd'}
        algorithm to use to process input
    tracefile: str or array
        trace array, or name of FITS table containing trace(s)
    order: int
        polynomial order
    subdiv: int
        number of subpixels
    psf_width: float
        width of PSF for convolution
    rows: tuple
        a tuple giving the slice of rows to process
    subsampled: str or None
        name of the output file with the subsampled image
    convolved: str or None
        name of the output file with the convolved image


Resample img and errimg using wavelets.

    Parameters
    ----------
    hdu: FITS header/data unit object
        header/data unit for a SCI extension
    img: ndarray
        SCI image array (could be a subset of full image)
    errimg: ndarray
        ERR image array (could be a subset of full image)
    original_nrows: int
        number of image lines (NAXIS2) in input image
    nrows: int
        number of image lines in subset
    ncols: int
        number of image columns (NAXIS1)
    rows: tuple
        tuple giving the slice of rows to process
    a2center: ndarray
        1-D array of Y locations
    a2displ: ndarray
        array of traces, one for each a2center; the length of each
        trace must be the same as the number of columns in the input image
    offset: float
        offset of the first row in 'image' from the beginning of
        the data block in the original file, needed for trace
    shifta2: float
        offset of the row from nominal (from shifta2 keyword)
    imset: int
        number of the current image set (keyword EXTVER)
    order: int
        polynomial order
    subdiv: int
        number of subpixels per input pixel
    psf_width: float
        width of PSF for convolution (e.g. 1.3);
    subsampled: str or None
        name of the output file with the subsampled image
    convolved: str or None
        name of the output file with the convolved image

    Returns
    -------
    img_arr: tuple of ndarrays
        the image and error arrays (to replace the input img and errimg)


Apply Kris Davidson's resampling method.

    Parameters
    ----------
    img: ndarray
        SCI image array (could be a subset of full image)
    errimg: ndarray
        ERR image array (could be a subset of full image)
    original_nrows: int
        number of image lines (NAXIS2) in input image
    nrows: int
        number of image lines in subset
    ncols: int
        number of image columns (NAXIS1)
    rows: tuple
        tuple giving the slice of rows to process
    a2center: ndarray
        1-D array of Y locations
    a2displ: ndarray
        array of traces, one for each a2center; the length of each
        trace must be the same as the number of columns in the input image
    offset: float
        offset of the first row in 'image' from the beginning of
        the data block in the original file, needed for trace
    shifta2: float
        offset of the row from nominal (from shifta2 keyword)

    Returns
    -------
    img_arr: tuple
        the image and error arrays (to replace the input img and errimg)


Kris Davidson's resampling algorithm, following the trace.

    Parameters
    ----------
    image: ndarray
        input 2-D image array
    a2center: ndarray
        array of Y locations
    a2displ: ndarray
        array of traces, one for each a2center; the length of
        each trace must be the same as the number of columns in 'image'
    offset: float
        offset of the first row in 'image' from the beginning
        of the data block in the original file, needed for trace
    shifta2: float
        offset of the row from nominal (from shifta2 keyword)

    Returns
    -------
    x2d: ndarray
        2-D array containing the resampled image


Evaluate the cross-dispersion PSF at x.

    Parameters
    ----------
    x: float
        offset in pixels from the center of the profile
    a: float
        a measure of the width of the PSF

    Returns
    -------
    val: float
        the PSF evaluated at x


Add together 'subdiv' rows of 'image', following the trace.

    Parameters
    ----------
    image: ndarray
        input 2-D image array, oversampled by 'subdiv' in axis 0
    a2center: ndarray
        1-D array of Y locations
    a2displ: ndarray
        array of traces, one for each a2center; the length of each
        trace must be the same as the number of columns in the input image
    subdiv: int
        number of rows to add together
    offset: float
        offset of the first row in 'image' from the beginning of
        the data block in the original file, needed for trace
    shifta2: float
        offset of the row from nominal (from shifta2 keyword)
    extname: str
        which type of extension (SCI, ERR, DQ)?

    Returns
    -------
    x2d: ndarray
        resampled 2-D image array

    Notes
    -----
    The function value is a 2-D array containing the resampled image.
    This is binned by subdiv in Y (axis 0), after shifting by trace
    (multiplied by subdiv).

    For extname = "ERR" the result differs in these ways:

      (1) fractions of pixels at the endpoints of the extraction region
          are not included
      (2) the values are combined as the average of the sum of the squares

    For extname = "DQ" the result differs in these ways:

      (1) the output is type int16
      (2) the output values are nominally the same as the input, while
          for SCI the output are subdiv times larger than the input
      (3) fractions of pixels at the endpoints of the extraction region
          are not included
      (4) the values are combined via bitwise OR rather than an average or sum


Add together 'subdiv' rows of 'image', centered on 'locn'.

    Parameters
    ----------
    image: ndarray
        input array, oversampled by 'subdiv' in axis 0
    locn: ndarray
        a 1-D array giving the location at which to extract; an
        integer value corresponds to the center of the pixel.  The length
        must be the same as the number of columns in the input image.
    subdiv: int
        number of rows to add together

    Returns
    -------
    spec: ndarray
        a 1-D array containing the extracted row


Average 'subdiv' rows of 'image', centered on 'locn'.

    Parameters
    ----------
    image: ndarray
        input array, oversampled by 'subdiv' in axis 0
    locn: ndarray
        a 1-D array giving the location at which to extract; an
        integer value corresponds to the center of the pixel
    subdiv: int
        number of rows to add together

    Returns
    -------
    spec: ndarray
        a 1-D array containing the extracted row

    Notes
    -----
    This takes the square root of the average of the squares, intended to be
    used for interpolating the ERR array.  Fractions of pixels at the upper
    and lower edges are excluded.


Bitwise OR 'subdiv' rows of 'image', centered on 'locn'.

    Parameters
    ----------
    image: ndarray
        input array, oversampled by 'subdiv' in axis 0
    locn: ndarray
        a 1-D array giving the location at which to extract; an
        integer value corresponds to the center of the pixel
    subdiv: int
        number of rows to add together

    Returns
    -------
    spec: ndarray
        a 1-D array containing the extracted row


Interpolate within the array of traces, and return a trace.

    Parameters
    ----------
    a2center: ndarray
        array of Y locations
    a2displ: ndarray
        array of traces, one trace for each element of a2center
    y: float
        Y location on the detector
    length: int
        length of a trace; needed only if traces is empty


Return the 1dt table name or array.

    Parameters
    ----------
    trace: str or array or None
        if trace is None the header keyword SPTRCTAB will be
        gotten from phdr; else if this is a str it should be the name
        of a trace file (possibly using an environment variable); otherwise,
        it should be a trace, in which case it will be returned unchanged
    phdr: FITS Header object
        primary header, used only if trace is None

    Returns
    -------
    tracefile: str or array
        name of a trace file (with environment variable expanded),
        or an actual trace array


bin the traces by the factor binaxis1

    Parameters
    ----------
    a2displ: ndarray
        an array of one or more arrays of Y displacements (traces)
    binaxis1: int
        binning factor in the dispersion axis
    ltv: float
        offset in the dispersion axis (one indexing)

    Returns
    -------
    a2displ: ndarray
        an array of traces (a2displ), but with the trace arrays binned
        and shorter by the factor binaxis1


used for interpolation

    Parameters
    ----------
    x: ndarray
        the integer values from 0 through n-1 inclusive (but float64)
    y: ndarray
        a 2-D array, axis 0 of length n
    z: float
        n / 2.
    n: int
        1 + order of polynomial fit


Calculate the S_REGION keyword for a single STIS file. If the
    dry_run parameter is False, set the S_REGION in the SCI extensions with
    the calculated value.  If keyword isn't present, add it


Write the S_REGION keyword to the header, creating the keyword if it
    doesn't exist


Find the limiting values of X and Y (ideal coords) given
    the limits from the SIAF projected aperture and those calculated from the
    WCS applied to the limits of the data array


Helper function to extract the RA and DEC as lists of floating
    point numbers from the S_REGION string


Convenience function to write a DS9 regions file from the S_REGION
    value in the header of a file.  If include_mast is set to True, will
    also get the existing S_REGION value from the mast catalog and include
    it in the region file.  The region file will include the keyword S_REGION
    in blue, the RA_APER and DEC_APER in red, and the mast catalog value of the
    S_REGION in green, if include_mast is True


Extract a 1-D spectrum from an flt or crj file.

    Parameters
    ----------
    input: str
        Name of the input raw file.

    output: str
        Name of the output file, or "" (the default).  If no name was
        specified, the output name will be constructed from the input name.

    backcorr: str
        If "perform", subtract the background.

    ctecorr: str
        If "perform", apply CTE correction (CCD only).

    dispcorr: str
        If "perform", compute wavelengths from the dispersion relation.

    helcorr: str
        If "perform", correct for heliocentric Doppler shift.

    fluxcorr: str
        If "perform", convert to absolute flux.

    sporder: int or None
        The number of the spectral order to extract.

    a2center: float or None

    maxsrch: float or None

    globalx: bool
        If True, use the global cross correlation offset (i.e. average for
        all orders) for all spectral orders.

    extrsize:  float or None
        Size of extraction box.  None means extrsize is not specified.

    bk1size:  float or None
        Size of first background region.  None means bk1size is not specified.

    bk2size:  float or None
        Size of second background region.  None means bk2size is not specified.

    bk1offst:  float or None
        Offset of first background region.  None means bk1offst is not
                specified.

    bk2offst:  float or None
        Offset of first background region.  None means bk2offst is not
        specified.

    bktilt:  float or None
        Background tilt.  None means bktilt is not specified.

    backord:  int or None
        Background order (0 or 1).  None means backord is not specified.

    bksmode: str
        Background smoothing mode ("off", "median" (the default), or
        "average").

    bksorder: int
        Background smoothing polynomial order (default is 3).

    blazeshift: float or None
        Blaze shift (in pixels).  None means blazeshift is not specified.

    algorithm: str
        Extraction algorithm ("unweighted" (the default) or "sc2d")

    xoffset: float
        Offset in X for slitless extraction.

    verbose: bool
        If True, calstis will print more info.

    timestamps: bool
        If True, calstis will print the date and time at various points
        during processing.

    trailer: str
        If specified, the standard output and standard error will be
        written to this file instead of to the terminal.  Note, however,
        that if print_version or print_revision is specified, the value
        will be printed to the terminal, and any name given for the
        trailer will be ignored.

    print_version: bool
        If True, calstis will print the version number (a string) and
        then return 0.

    print_revision: bool
        If True, calstis will print the full version string and then
        return 0.

    Returns
    -------
    status: int
        0 is OK.
        1 is returned if cs6.e (the calstis host executable) returned a
        non-zero status.  If verbose is True, the value returned by cs6.e
        will be printed.
        2 is returned if the specified input file or files were not found,
        or the numbers of input and output files (if the latter was
        specified) are not the same.


TEAL interface for the x1d function.


Calibrate STIS data (calstis) with modified cosmic ray rejection parameters.

    A temporary CRREJTAB is created, with values derived from user-supplied inputs and
    defaults derived from the file's ext=0 CRREJTAB keyword.  This default file may
    be overridden by specifying a different `crrejtab`.

    This routine should be used instead of `stistools.ocrreject.ocrreject()` when the
    order of operation is of concern.

    **Note:**
    This routine does not replace `ocrreject`'s functionality for combining multiple
    CCD datasets together into one CRJ file (i.e. the "all" parameter).

    Parameters
    ----------
    input: str
        Name of the input file.

    wavecal: str, default=''
        Name of the input wavecal file, or '' (the default).  This is
        only needed if the name is not the "normal" name
        (rootname_wav.fits).

    outroot: str, default=''
        Root name for the output files, or '' (the default).  This can
        be a directory name, in which case the string must end in '/'.

    savetmp: bool, default=False
        True if calstis should not delete temporary files.

    verbose: bool, default=False
        If True, calstis will print more info.

    timestamps: bool, default=False
        If True, calstis will print the date and time at various points
        during processing.

    trailer: str, default=''
        If specified, the standard output and standard error will be
        written to this file instead of to the terminal.  Note, however,
        that if print_version or print_revision is specified, the value
        will be printed to the terminal, and any name given for the
        trailer will be ignored.

    print_version: bool, default=False
        If True, calstis will print the version number (a string) and
        then return 0.

    print_revision: bool, default=False
        If True, calstis will print the full version string and then
        return 0.

    crrejtab: str, default=''
        This argument may be used to override the CRREJTAB value in the
        primary header of the input files.  This file determines the
        default CR-rejection parameters below.

    scalense: str, default=''
        Multiplicative scale factor applied to noise.
        If specified, this overrides SCALENSE in the CRREJTAB.

    initgues: str, default=''
        Initial guess method.
        If specified, this overrides INITGUES in the CRREJTAB.
        The allowed values are 'minimum' and 'median' and ''.

    skysub: str, default=''
        Sky value subtracted.
        If specified, this overrides SKYSUB in the CRREJTAB.
        The allowed values are 'none', 'mode' and ''.

    crsigmas: str, default=''
        Statistical rejection criteria.
        If specified, this overrides CRSIGMAS in the CRREJTAB.  The
        value should be a comma-separated string of one or more
        integer or float values.  For each such value, calstis will
        perform one cosmic-ray-rejection cycle, with the sigma taken
        from the numerical value that was specified.

    crradius: float or None, default=None
        If not None, this overrides CRRADIUS in the CRREJTAB.  This is
        the rejection propagation radius in pixels (e.g. 1.5).  After
        finding an outlier (a cosmic ray hit), adjacent pixels can also
        be flagged and excluded.  Neighboring pixels will be rejected if
        their values are discrepant by more than crthresh * sigmas * noise,
        where noise is based on the noise model (i.e. Poisson noise and
        readout noise).

    crthresh: float or None, default=None
        If not None, this overrides CRTHRESH in the CRREJTAB.  This is the
        rejection propagation threshold (e.g. 0.8).  If crthresh = 0 then
        all adjacent pixels (see crradius) will be rejected.

    badinpdq: int or None, default=None
        If specified, this overrides BADINPDQ in the CRREJTAB.  This is a
        data quality flag (or bitwise OR of flags) to allow rejection of
        pixels in the input images when forming the "guess" image (the
        image with which to compare the input images when looking for
        outliers).

    crmask: bool or None, default=None
        If specified, this overrides CRMASK in the CRREJTAB.  crmask = True
        means that the cosmic rays that are detected should be flagged in
        the DQ (data quality) extensions of the input files.

    Returns
    -------
    status: int
        0 is OK.
        1 is returned if cs0.e (the calstis host executable) returned a
        non-zero status.  If verbose is True, the value returned by cs0.e
        will be printed.
        2 is returned if the specified input file or files were not found.