    Load data from the MMS Hot Plasma Composition Analyzer (HPCA)

    Parameters
    ----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']
            Default: ['2015-10-16', '2015-10-17']

        probe : str or list of str
            list of probes, valid values for MMS probes are ['1','2','3','4'].
            Default: '1'

        data_rate : str or list of str
            instrument data rates for HPCA include 'brst', 'srvy'.
            Default: 'srvy'

        level : str
            indicates level of data processing
            Default: 'l2'

        datatype : str or list of str
            Valid datatypes for HPCA are 'moments' and 'ion'
            Default: 'moments'

        get_support_data: bool
            Data with an attribute "VAR_TYPE" with a value of "support_data"
            will be loaded into tplot.
            Default: True

        varformat: str
            The file variable formats to load into tplot.  Wildcard character
            "*" is accepted.
            Default: None (all variables are loaded)

        varnames: list of str
            List of variable names to load. If list is empty or not specified,
            all data variables are loaded)
            Default: [] (all variables are loaded)

        time_clip: bool
            Data will be clipped to the exact trange specified by the trange keyword.
            Default: False

        suffix: str
            The tplot variable names will be given this suffix.
            Default: None

        center_measurement: bool
            If True, the CDF epoch variables are time-shifted to the middle
            of the accumulation interval by their DELTA_PLUS_VAR and
            DELTA_MINUS_VAR variable attributes
            Default: False

        notplot: bool
            If True, then data are returned in a hash table instead of
            being stored in tplot variables (useful for debugging, and
            access to multidimensional data products)
            Default: False

        available: bool
            If True, simply return the available data files (without downloading)
            for the requested parameters
            Default: False

        no_update: bool
            Set this flag to preserve the original data. if not set and newer
            data is found the existing data will be overwritten
            Default: False

        cdf_version: str
            Specify a specific CDF version # to load (e.g., cdf_version='4.3.0')
            Default: None

        min_version: str
            Specify a minimum CDF version # to load
            Default: None

        latest_version: bool
            Only grab the latest CDF version in the requested time interval
            Default: False

        major_version: bool
            Only open the latest major CDF version (e.g., X in vX.Y.Z) in the requested time interval
            Default: False

        always_prompt: bool
            Set this keyword to always prompt for the user's username and password;
            useful if you accidentally save an incorrect password, or if your SDC password has changed
            Default: False

        spdf: bool
            If True, download the data from the SPDF instead of the SDC
            Default: False

    Returns
    --------
        list of str
            List of tplot variables created.

    Example
    -------

    >>> import pyspedas
    >>> from pyspedas import tplot
    >>> mom_vars = pyspedas.projects.mms.mms_load_hpca(trange=['2015-10-16', '2015-10-17'], datatype='moments')
    >>> tplot(['mms1_hpca_hplus_number_density', 'mms1_hpca_hplus_ion_bulk_velocity'])
    >>> # load the ion data (support data, fluxes, phase space densities, all ion data samples are n x m arrays
    >>> ion_vars = pyspedas.projects.mms.mms_load_hpca(trange=['2016-10-16', '2016-10-17'], datatype='ion')


    This function sets the plot metadata for HPCA data products, and is meant
    to be called from the HPCA load routine

    Parameters
    ------------
        fov : list of int
            field of view, in angles, from 0-360

        probe : str
            probe #, e.g., '4' for MMS4

        suffix: str
            suffix of the loaded data

    Returns
    ------------
        None


    Returns 3D particle data structures containing MMS HPCA
    data for use with SPEDAS particle routines.

    Input
    ----------
        tname: str
            tplot variable name containing the HPCA distribution data

    Parameters
    ----------
        probe: str
            Spacecraft probe #

        data_rate: str
            Instrument data rates for HPCA include 'brst' and 'srvy'

        species: str
            Species of the data specified by the 'tname' input

        index: int
            Index of time sample to return

        times: bool
            Flag to return the distribution times instead of the particle data structure(s)

    Returns
    ------------
        3D particle data structure(s) containing MMS HPCA distribution functions


Returns structure containing hpca look directions, energies, and other info.


    Calculations of Grad, Curl, Curv,..., for MMS using
    the Linear Gradient/Curl Estimator technique
    see Chanteur, ISSI, 1998, Ch. 11

    Parameters
    ----------
    fields : list of str
        Names of the magnetic field data variables, ordered by spacecraft
        (e.g., ['mms1_b_gse', 'mms2_b_gse', 'mms3_b_gse', 'mms4_b_gse']).
    positions : list of str
        Names of the spacecraft position data variables, ordered by spacecraft
        (e.g., ['mms1_pos_gse', 'mms2_pos_gse', 'mms3_pos_gse', 'mms4_pos_gse']).
    suffix : str, optional
        Suffix to add to the names of the output variables.

    Returns
    -------
    None
        The function stores the computed parameters as tplot variables


    This function updates the metadata for FGM data products

    Parameters
    ----------
        probe : str or list of str
            probe or list of probes, valid values for MMS probes are ['1','2','3','4'].

        data_rate : str or list of str
            instrument data rates for FGM include 'brst' 'fast' 'slow' 'srvy'. The
            default is 'srvy'.

        level : str
            indicates level of data processing. the default if no level is specified is 'l2'

        instrument : str
            instrument; probably 'fgm'

        suffix: str
            The tplot variable names will be given this suffix.  By default,
            no suffix is added.


    Helper routine for splitting 4-vector FGM data (Bx, By, Bz, b_total)
    into 2 tplot variables, one for the vector (Bx, By, Bz), and one for the total


    This function applies the curlometer technique to MMS FGM data

    Parameters
    ----------
        fields : list of str
            List of tplot variables containing the B-field for each spacecraft
            (in GSE coordinates)

        positions : list of str
            List of tplot variables containing the S/C position vectors for
            each spacecraft (also GSE coordinates)

        suffix: str
            The tplot variable names will be given this suffix.  By default,
            no suffix is added.

    Notes
    ----------
        The input B-field data and position data are required to be in
        GSE coordinates

        Based on the original mms_curl, written in IDL, by Jonathan Eastwood

        For more info on this method, see:
          Chanteur, G., Spatial Interpolation for Four Spacecraft: Theory,
          Chapter 14 of Analysis methods for multi-spacecraft data, G.
          Paschmann and P. W. Daly (Eds.) ISSI Scientific Report SR-001.

    Returns
    ----------
        List of tplot variables created


    Load MMS fluxgate magnetometer data

    Parameters
    ----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']
            Default: ['2015-10-16', '2015-10-17']

        probe : str or list of str
            list of probes, valid values for MMS probes are ['1','2','3','4'].
            Default: '1'

        data_rate : str or list of str
            instrument data rates for FGM include 'brst' 'fast' 'slow' 'srvy'. The
            default is 'srvy'.
            Default: 'srvy'

        level : str
            indicates level of data processing. the default if no level is specified is 'l2'
            Default: 'l2'

        datatype : str or list of str
            Do not use: defined only for consistency with other load routines.  All FGM data will be loaded.
            Default: ''

        get_support_data: bool
            Data with an attribute "VAR_TYPE" with a value of "support_data"
            will be loaded into tplot.
            Default: True

        time_clip: bool
            Data will be clipped to the exact trange specified by the trange keyword.
            Default: False

        varformat: str
            The file variable formats to load into tplot.  Wildcard character
            "*" is accepted.
            Default: None (all variables are loaded)

        exclude_format: str
            Variables matching this pattern will not be processed while loading the CDFs.
            Wildcard character "*" is allowed.
            Default: '*rdeltahalf*'

        varnames: list of str
            List of variable names to load. If list is empty or not specified,
            all data variables are loaded.
            Default: []

        suffix: str
            The tplot variable names will be given this suffix.
            Default: None

        notplot: bool
            If True, then data are returned in a hash table instead of
            being stored in tplot variables (useful for debugging, and
            access to multidimensional data products)
            Default: False

        available: bool
            If True, simply return the available data files (without downloading)
            for the requested parameters
            Default: False

        no_update: bool
            Set this flag to preserve the original data. if not set and newer
            data is found the existing data will be overwritten
            Default: False

        cdf_version: str
            Specify a specific CDF version # to load (e.g., cdf_version='4.3.0')
            Default: None

        min_version: str
            Specify a minimum CDF version # to load
            Default: None

        latest_version: bool
            Only grab the latest CDF version in the requested time interval
            Default: False

        major_version: bool
            Only open the latest major CDF version (e.g., X in vX.Y.Z) in the requested time interval
            Default: False

        keep_flagged: bool
            If True, don't remove flagged data (flagged data are set to NaNs by
            default, this keyword turns this off)
            Default: False

        always_prompt: bool
            Set this keyword to always prompt for the user's username and password;
            useful if you accidentally save an incorrect password, or if your SDC password has changed
            Default: False

        spdf: bool
            If True, download the data from the SPDF instead of the SDC
            Default: False

        get_fgm_ephemeris: bool
            Keep the ephemeris variables in the FGM files
            Default: False

    Returns
    -------
        list of str
            List of tplot variables created.

    Example
    -------

    >>> import pyspedas
    >>> from pyspedas import tplot
    >>> fgm_vars = pyspedas.projects.mms.mms_load_fgm(trange=['2015-10-16', '2015-10-17'])
    >>> tplot('mms1_fgm_b_gsm_srvy_l2')


    This function removes data flagged by the FGM 'flag' variable (flags > 0),
    in order to only show science quality data by default.

    Parameters
    -----------
        probe: str or list of str
            probe or list of probes, valid values for MMS probes are ['1','2','3','4'].

        data_rate: str or list of str
            instrument data rates for FGM include 'brst' 'fast' 'slow' 'srvy'. The
            default is 'srvy'.

        level: str
            indicates level of data processing. the default if no level is specified is 'l2'

        instrument: str
            instrument; probably 'fgm'

        suffix: str
            The tplot variable names will be given this suffix.  By default,
            no suffix is added.


    Load data from the MMS Search Coil Magnetometer (SCM)

    Parameters
    ----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']
            Default: ['2015-10-16', '2015-10-17']

        probe : str or list of str
            list of probes, valid values for MMS probes are ['1','2','3','4'].
            Default: '1'

        data_rate : str or list of str
            instrument data rates for SCM include ['brst' 'fast' 'slow' 'srvy'].
            Default: 'srvy'

        level : str
            indicates level of data processing. the default if no level is specified is 'l2'
            Default: 'l2'

        datatype : str or list of str
            Valid datatypes for SCM are: ['scsrvy', 'cal', 'scb', 'scf', 'schb', 'scm', 'scs']
            Default is 'scsrvy' for srvy data, and 'scb' for brst data.

        get_support_data: bool
            Data with an attribute "VAR_TYPE" with a value of "support_data"
            will be loaded into tplot.  By default, only loads in data with a
            "VAR_TYPE" attribute of "data".
            Default: False

        time_clip: bool
            Data will be clipped to the exact trange specified by the trange keyword.
            Default: True

        varformat: str
            The file variable formats to load into tplot.  Wildcard character
            "*" is accepted.  By default, all variables are loaded in.
            Default: None (all variables are loaded)

        varnames: list of str
            List of variable names to load. If list is empty or not specified,
            all data variables are loaded
            Default: [] (all variables are loaded)

        suffix: str
            The tplot variable names will be given this suffix.
            Default: None

        notplot: bool
            If True, then data are returned in a hash table instead of
            being stored in tplot variables (useful for debugging, and
            access to multidimensional data products)
            Default: False

        available: bool
            If True, simply return the available data files (without downloading)
            for the requested parameters
            Default: False

        no_update: bool
            Set this flag to preserve the original data. if not set and newer
            data is found the existing data will be overwritten
            Default: False

        cdf_version: str
            Specify a specific CDF version # to load (e.g., cdf_version='4.3.0')
            Default: None

        min_version: str
            Specify a minimum CDF version # to load
            Default: None

        latest_version: bool
            Only grab the latest CDF version in the requested time interval
            Default: False

        major_version: bool
            Only open the latest major CDF version (e.g., X in vX.Y.Z) in the requested time interval
            Default: False

        always_prompt: bool
            Set this keyword to always prompt for the user's username and password;
            useful if you accidentally save an incorrect password, or if your SDC password has changed
            Default: False

        spdf: bool
            If True, download the data from the SPDF instead of the SDC

    Returns
    ---------
        list of str
            List of tplot variables created.

    Example
    -------

        >>> import pyspedas
        >>> from pyspedas import tplot
        >>> scm_vars = pyspedas.projects.mms.mms_load_scm(trange=['2015-10-16', '2015-10-17'])
        >>> tplot('mms1_scm_acb_gse_scsrvy_srvy_l2')


    This function updates the metadata for the SCM data products

    Parameters
    ----------
        tnames : list of str
            list of tplot variables loaded by the load routine

        probe : str
            spacecraft probe #, valid values for MMS probes are ['1', '2', '3', '4'].

        datatype : str
            SCM datatype loaded

        coord : str or list of str
            SCM coordinate system; depends on data level

        suffix: str
            The tplot variable names will be given this suffix.  By default,
            no suffix is added.


    Load data from the MMS Active Spacecraft Potential Control (ASPOC)

    Parameters
    ----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']
            Default: ['2015-10-16', '2015-10-17']

        probe : str or list of str
            list of probes, valid values for MMS probes are ['1','2','3','4'].
            Default: 1

        data_rate : str or list of str
            instrument data rates for ASPOC include 'srvy', 'sitl'.
            Default: 'srvy'.

        level : str
            indicates level of data processing.
            Default: 'l2'

        datatype : str or list of str
            Do not use: defined only for consistency with other load routines.  All ASPOC data will be loaded.

        get_support_data: bool
            Data with an attribute "VAR_TYPE" with a value of "support_data"
            will be loaded into tplot.
            Default: False

        time_clip: bool
            Data will be clipped to the exact trange specified by the trange keyword.
            Default: False

        varformat: str
            The file variable formats to load into tplot.  Wildcard character
            "*" is accepted.
            Default: None (all variables are loaded in)

        varnames: list of str
            List of variable names to load.  If list is empty or unspecified, all data variables are loaded.
            Default: empty list (all data variables are loaded)

        suffix: str
            The tplot variable names will be given this suffix.
            Default: None

        notplot: bool
            If True, then data are returned in a hash table instead of
            being stored in tplot variables (useful for debugging, and
            access to multidimensional data products)
            Default: False

        available: bool
            If True, simply return the available data files (without downloading)
            for the requested parameters
            Default: False

        no_update: bool
            Set this flag to preserve the original data. if not set and newer
            data is found the existing data will be overwritten
            Default: False

        cdf_version: str
            Specify a specific CDF version # to load (e.g., cdf_version='4.3.0')
            Default: None

        min_version: str
            Specify a minimum CDF version # to load
            Default: None

        latest_version: bool
            Only grab the latest CDF version in the requested time interval
            Default: False

        major_version: bool
            Only open the latest major CDF version (e.g., X in vX.Y.Z) in the requested time interval
            Default: False

        always_prompt: bool
            Set this keyword to always prompt for the user's username and password;
            useful if you accidentally save an incorrect password, or if your SDC password has changed
            Default: False

        spdf: bool
            If True, download the data from the SPDF instead of the SDC
            Default: False

    Returns
    --------
        list of str
            List of tplot variables created.

    Examples
    ---------

    >>> import pyspedas
    >>> from pyspedas import tplot
    >>> asp_data = pyspedas.projects.mms.mms_load_aspoc(trange=['2015-10-16', '2015-10-17'], probe='1')
    >>> tplot('mms1_aspoc_ionc_l2')


    Generates a tplot variable containing the FEEPS pitch angles for each telescope from magnetic field data.

    Parameters
    -----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']

        probe: str
            probe #, e.g., '4' for MMS4

        level: str
            data level, e.g., 'l2'

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        datatype: str
            'electron' or 'ion'

        suffix: str
            suffix of the loaded data

    Returns
    ----------
        Tuple: (tplot variable created, hash table used by PAD routine)


    This function splits the last integral channel from the FEEPS spectra,
    creating 2 new tplot variables:

       [original variable]_clean - spectra with the integral channel removed
       [original variable]_500keV_int - the integral channel that was removed

    Parameters
    -----------
        units_type: str
            instrument datatype, e.g., 'intensity'

        species: str
            'electron' or 'ion'

        probe: str
            probe #, e.g., '4' for MMS4

        suffix: str
            suffix of the loaded data

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        level: str
            data level

        sensor_eyes: dict
            Hash table containing the active sensor eyes

    Returns
    -----------
        List of tplot variables created.


       Apply flat field correction factors to FEEPS ion/electron data;
       correct factors are from the gain factor found in:

           FlatFieldResults_V3.xlsx

       from Drew Turner, 1/19/2017

    Parameters
    ---------------
        probes: list of str
            list of probes #, e.g., '4' for MMS4

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        suffix: str
            suffix of the loaded data

    Notes
    ---------------
        From Drew Turner, 1/18/17:
           Here are the correction factors that we need to apply to the current
           ION counts/rates/fluxes in the CDF files.
           NOTE, THIS IS A DIFFERENT TYPE OF CORRECTION THAN THAT FOR THE ELECTRONS!
           These shifts should be applied to the counts/rates/fluxes data EYE-BY-EYE on each spacecraft.
           These are multiplication factors (i.e., Jnew = Jold * Gcorr).
           For those equations, Jold is the original count/rate/flux array and
           Jnew is the corrected version of the arrays using the factors listed below.

            MMS1:
            Top6: Gcorr = 0.7
            Top7: Gcorr = 2.5
            Top8: Gcorr = 1.5
            Bot6: Gcorr = 0.9
            Bot7: Gcorr = 1.2
            Bot8: Gcorr = 1.0

            MMS2:
            Top6: Gcorr = 1.3
            Top7: BAD EYE
            Top8: Gcorr = 0.8
            Bot6: Gcorr = 1.4
            Bot7: BAD EYE
            Bot8: Gcorr = 1.5

            MMS3:
            Top6: Gcorr = 0.7
            Top7: Gcorr = 0.8
            Top8: Gcorr = 1.0
            Bot6: Gcorr = 0.9
            Bot7: Gcorr = 0.9
            Bot8: Gcorr = 1.3

            MMS4:
            Top6: Gcorr = 0.8
            Top7: BAD EYE
            Top8: Gcorr = 1.0
            Bot6: Gcorr = 0.8
            Bot7: Gcorr = 0.6
            Bot8: Gcorr = 0.9


    Removes the sunlight contamination from FEEPS data

    Parameters
    -----------
        sensor_eyes: dict
            Hash table containing the active sensor eyes

        trange: list of str
            time range

        probe: str
            probe #, e.g., '4' for MMS4

        datatype: str
            'electron' or 'ion'

        data_units: str
            'intensity'

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        level: str
            data level

        suffix: str
            suffix of the loaded data

    Returns
    -----------
        List of tplot variables created.


    This function will calculate pitch angle distributions using data from the MMS Fly's Eye Energetic Particle Sensor (FEEPS)

    Parameters
    ----------
        probe: str
            probe #, e.g., '4' for MMS4

        data_units: str
            'intensity'

        datatype: str
            'electron' or 'ion'

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        level: str
            data level

        suffix: str
            suffix of the loaded data

        energy: list of float
            energy range to include in the calculation

        bin_size: float
            size of the pitch angle bins

        angles_from_bfield: bool
            calculate the pitch angles from the B-field data instead of reading from the CDFs

    Returns
    --------
        List of tplot variables created.


    Calculate gyrophase distributions using data from the MMS Fly's Eye Energetic Particle Sensor (FEEPS)

    Parameters
    ----------
        probe: str
            probe #, e.g., '4' for MMS4

        data_units: str
            'intensity'

        datatype: str
            'electron' or 'ion'

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        level: str
            data level

        suffix: str
            suffix of the loaded data

        energy: list of float
            energy range to include in the calculation

        bin_size: float
            size of the pitch angle bins

    Returns
    --------
        Tplot variable containing the gyrophase distribution

    Notes
    ------
        Based on IDL code by Drew Turner (10 Oct 2017): mms_feeps_gpd.pro


    This function returns the FEEPS sectors to mask due to sunlight contamination

    Parameters
    -----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']

    Returns
    -----------
        Hash table containing the sectors to mask for each spacecraft and sensor ID


    Load data from the MMS Fly's Eye Energetic Particle Sensor (FEEPS)

    Parameters
    ----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']
            Default: ['2015-10-16','2015-10-17']

        probe : str or list of str
            list of probes, valid values for MMS probes are ['1','2','3','4'].
            Default: '1'

        data_rate : str or list of str
            instrument data rates for FEEPS include ['brst', 'srvy'].
            Default: 'srvy'

        level : str
            indicates level of data processing. the default if no level is specified is 'l2'
            Default: 'l2'

        datatype : str or list of str
            Valid datatypes for FEEPS are::

                       L2, L1b: ['electron', 'ion']
                       L1a: ['electron-bottom', 'electron-top', 'ion-bottom', 'ion-top']

            Default: 'electron'

        data_units : str or list of str
            Unit types to be loaded, options are 'count_rate', 'intensity'
            Default: ['count_rate', 'intensity']

        no_flatfield_corrections: bool
            If True, no flatfield corrections are performed.
            Default: False

        get_support_data: bool
            Data with an attribute "VAR_TYPE" with a value of "support_data"
            will be loaded into tplot.
            Default: True

        time_clip: bool
            Data will be clipped to the exact trange specified by the trange keyword.
            Default: False

        varformat: str
            The file variable formats to load into tplot.  Wildcard character
            "*" is accepted.
            Default: None (all variables are loaded)

        varnames: list of str
            List of variable names to load. If list is empty or not specified,
            all data variables are loaded.
            Default: []

        suffix: str
            The tplot variable names will be given this suffix.  By default,
            no suffix is added.
            Default: None

        notplot: bool
            If True, then data are returned in a hash table instead of
            being stored in tplot variables (useful for debugging, and
            access to multidimensional data products)
            Default: False

        available: bool
            If True, simply return the available data files (without downloading)
            for the requested parameters
            Default: False

        no_update: bool
            Set this flag to preserve the original data. if not set and newer
            data is found the existing data will be overwritten
            Default: False

        cdf_version: str
            Specify a specific CDF version # to load (e.g., cdf_version='4.3.0')
            Default: None

        min_version: str
            Specify a minimum CDF version # to load
            Default: None

        latest_version: bool
            Only grab the latest CDF version in the requested time interval

        major_version: bool
            Only open the latest major CDF version (e.g., X in vX.Y.Z) in the requested time interval

        always_prompt: bool
            Set this keyword to always prompt for the user's username and password;
            useful if you accidentally save an incorrect password, or if your SDC password has changed

        spdf: bool
            If True, download the data from the SPDF instead of the SDC

        filter_recvary_warnings: bool
            If True, capture warnings from cdf_to_tplot and filter out the ones complaining about non-record-varying support data with timestamps

    Returns
    --------
        list of str
            List of tplot variables created.

    Example
    -------

    >>> import pyspedas
    >>> from pyspedas import tplot
    >>> feeps_data = pyspedas.projects.mms.mms_load_feeps(trange=['2015-10-16', '2015-10-17'], probe='1', datatype='electron')
    >>> tplot(['mms1_epd_feeps_srvy_l2_electron_intensity_omni_spin', 'mms1_epd_feeps_srvy_l2_electron_intensity_omni'])


    This function removes bad eyes, bad lowest energy channels based on data from Drew Turner

    Parameters
    ------------
        probe: str
            probe #, e.g., '4' for MMS4

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        datatype: str
            'electron' or 'ion'

        level: str
            data level

        suffix: str
            suffix of the loaded data

        trange: list of str or list of float
            Time range
    Returns
    ------------
        None


    This function will spin-average the omnidirectional FEEPS energy spectra

    Parameters
    -----------
        probe: str
            probe #, e.g., '4' for MMS4

        data_units: str
            'intensity' or 'count_rate'

        datatype: str
            'electron' or 'ion'

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        level: str
            data level, e.g., 'l2'

        suffix: str
            suffix of the loaded data

    Returns
    -----------
        Name of tplot variable created.


    This function will calculate the omnidirectional FEEPS spectrograms, and is automatically called from mms_load_feeps

    Parameters
    ------------
        eyes: dict
            Hash table containing the active sensor eyes

        probe: str
            probe #, e.g., '4' for MMS4

        datatype: str
            'electron' or 'ion'

        data_units: str
            'intensity'

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        level: str
            data level

        suffix: str
            suffix of the loaded data

    Returns
    ------------
        List of tplot variables created.


    This function returns the FEEPS active eyes, based on date/probe/species/rate

    Parameters:
        trange: list of str
            time range

        probe: str
            probe #, e.g., '4' for MMS4

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        species: str
            'electron' or 'ion'

        level: str
            data level

    Returns:
        Hash table containing 2 keys:
            output['top'] -> maps to the active top eyes
            output['bottom'] -> maps to the active bottom eyes

    Notes:
         1) Burst mode should include all sensors (TOP and BOTTOM):
             electrons: [1, 2, 3, 4, 5, 9, 10, 11, 12]
             ions: [6, 7, 8]

         2) SITL should return (TOP only):
             electrons: set_intersection([5, 11, 12], active_eyes)
             ions: None

         3) From Drew Turner, 9/7/2017, srvy mode:

           - before 16 August 2017:
              electrons: [3, 4, 5, 11, 12]
              iond: [6, 7, 8]

           - after 16 August 2017:
               MMS1
                 Top Eyes: 3, 5, 6, 7, 8, 9, 10, 12
                 Bot Eyes: 2, 4, 5, 6, 7, 8, 9, 10

               MMS2
                 Top Eyes: 1, 2, 3, 5, 6, 8, 10, 11
                 Bot Eyes: 1, 4, 5, 6, 7, 8, 9, 11

               MMS3
                 Top Eyes: 3, 5, 6, 7, 8, 9, 10, 12
                 Bot Eyes: 1, 2, 3, 6, 7, 8, 9, 10

               MMS4
                 Top Eyes: 3, 4, 5, 6, 8, 9, 10, 11
                 Bot Eyes: 3, 5, 6, 7, 8, 9, 10, 12


    This function will spin-average the FEEPS pitch angle distributions

    Parameters
    -----------
        probe: str
            probe #, e.g., '4' for MMS4

        data_units: str
            'intensity' or 'count_rate'

        datatype: str
            'electron' or 'ion'

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        level: str
            data level, e.g., 'l2'

        suffix: str
            suffix of the loaded data

        energy: list of float
            energy range to include in the calculation

        bin_size: float
            size of the pitch angle bins

    Returns
    ----------
        Name of tplot variable created.


    This function modifies the energy table in FEEPS spectra (intensity, count_rate, counts) variables
       using the function: mms_feeps_energy_table (which is s/c, sensor head and sensor ID dependent)

    Parameters
    -------------
        probes: list of str
            list of probes #, e.g., '4' for MMS4

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst'

        level: str
            data level (default: 'l2')

        suffix: str
            suffix of the loaded data

    Notes
    -------
        BAD EYES are replaced by NaNs


    This function returns the energy table based on
    each spacecraft and eye; based on the table from:

       FlatFieldResults_V3.xlsx

    from Drew Turner, 1/19/2017

    Parameters
    -------------
        probe: str
            probe #, e.g., '4' for MMS4

        eye: str
            sensor eye #

        sensor_id: int
            sensor ID

    Returns
    --------
        Energy table

    Notes
    --------
        BAD EYES are replaced by NaNs

        - different original energy tables are used depending on if the sensor head is 6-8 (ions) or not (electrons)

        Electron Eyes: 1, 2, 3, 4, 5, 9, 10, 11, 12
        Ion Eyes: 6, 7, 8


    Calculates FEEPS gyrophase angles for electron burst data

    Notes: This is intended for use with burst mode data, but the output gyrophase product,
           mms*_feeps_gyrophase, can be interpolated onto FEEPS burst or survey cadence
           to produce spectra

    Based on the IDL code writen by Drew Turner (10 Oct 2017): mms_feeps_getgyrophase.pro


r"""
    Generate an overview plot for MMS data.

    Parameters:
    -----------
    trange (list of 2 strings, optional):
        Time range, start and end date. If not specified, it will be calculated based on the date and duration parameters.
    date: str, optional
        Date in the format 'YYYY-MM-DD' or 'YYY-MM-DD/hh:mm:ss. Used to calculate the time range if trange is not specified.
    duration: str, optional
        Duration in days. Used to calculate the time range if trange is not specified.
    probe: str, optional
        MMS probe number (1-4).
    skip_ae_idx: bool, optional
        Whether to skip plotting the AE index panel.
    save_png: str, optional
        .Filename to save plot as PNG
    save_eps: str, optional
        .Filename to save plot as EPS
    save_svg: str, optional
        .Filename to save plot as SVG
    save_pdf: str, optional
        .Filename to save plot as PDF
    save_jpeg: str, optional
        .Filename to save plot as JPEG
    display: bool, optional
        If True, then this function will display the plotted tplot variables. Necessary to make this optional
        so we can avoid it in a headless server environment.
    xsize: int, optional
        Size of the x-axis of the plot window in inches. Default is 10.
    ysize: int, optional
        Size of the y-axis of the plot window in inches. Default is 14.

    Returns:
    --------
    None

    Examples:
    ---------
    from pyspedas import mms_overview_plot
    mms_overview_plot(date='2023-03-23', probe='1', save_png="c:\\work\\mms\\summary_plots\mms_overview", display=False)

    Notes:
    ------
    It may need a long time to complete.

    Todo:
    -----
    1. Implement time_clip. Currently, it is not working correctly for spectra.
    2. Fix legends. The option "legend_location"="spedas", does not work correctly, it hides part of the legend, both on screen and in the saved PNG file.
    3. Implement thm_gen_multipngplot (6 hours, 2 hours).
    4. Fix problems when data is missing.


Helper routine for loading tetrahedron quality factor data (ASCII files from the SDC); not meant to be called directly


Helper routine for loading state data (ASCII files from the SDC); not meant to be called directly; see pyspedas.projects.mms.state instead


    Search for local state MMS files in case a list cannot be retrieved from the
    remote server.  Returns a sorted list of file paths.

    Parameters:
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']

        probe: str
            probe #, e.g., '4' for MMS4

        level: str
            state data level; either 'def' (for definitive) or 'pred' (for predicted)

        filetype: str
            state file type, e.g. 'eph' (for ephemeris) or 'att' (for attitude)

    Returns:
        List of local files found matching the input parameters.


    This function loads the state (ephemeris and attitude) data from the ASCII files
    into tplot variables

    Parameters
    ----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']
            Default: ['2015-10-16', '2015-10-17']

        probe : str or list of str
            list of probes, valid values for MMS probes are ['1','2','3','4'].
            Default: '1'

        level : str
            indicates level of data (options: 'def' (definitive), 'pred' (predicted)
            Default: 'def'

        datatypes : str or list of str
            Datatypes for state data to be loaded (options: 'pos', 'vel', 'spinras', 'spindec')
            Default: ['pos', 'vel']

        suffix: str
            The tplot variable names will be given this suffix.
            Default: None

        no_update: bool
            Set this flag to preserve the original data. if not set and newer
            data is found the existing data will be overwritten
            Default: False

        pred_or_def: bool
            Load definitive or predicted (if definitive isn't available); defaults to True
            Default: True

    Returns
    --------
        list of str
            List of tplot variables created.

    Example
    -------

    >>> import pyspedas
    >>> from pyspedas import tplot
    >>> pos_data = pyspedas.projects.mms.mms_load_state(trange=['2015-10-16', '2015-10-17'], probe='1', datatypes='pos', level='def')
    >>> tplot('mms1_defeph_pos')


    Search for local ancillary files in case a list cannot be retrieved from the
    remote server.  Returns a sorted list of file paths.

    Parameters:
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']

        filetype: str
            state file type, e.g. 'tetrahedron_qf' (for tetrahedron quality factor)

    Returns:
        List of local files found matching the input parameters.


Helper routine for loading tetrahedron QF data (ASCII files from the SDC); not meant to be called directly


    Load the MMS tetrahedron quality factor data from the ASCII files
    into tplot variables

    Parameters
    ----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']
            Default: ['2015-10-16', '2015-10-17']

        suffix: str
            The tplot variable names will be given this suffix.  By default,
            no suffix is added.
            Default: None

        no_update: bool
            Set this flag to preserve the original data. if not set and newer
            data is found the existing data will be overwritten
            Default: False

    Returns
    --------
        list of str
            List of tplot variables created.

    Example
    -------

    >>> import pyspedas
    >>> from pyspedas import tplot
    >>> qf_vars = pyspedas.projects.mms.mms_load_tetrahedron_qf(trange=['2015-10-16', '2015-10-17'])
    >>> tplot('mms_tetrahedron_qf')


    Calculate the pitch-angle distribution (angle vs energy plot) and energy spectrum
    in the omni, para, perp, and anti-para directions using MMS FPI data.
    Also returns the one-count-level.

    Parameters
    ------------
        dists : list of dicts
            List of dictionaries containing the FPI particle distribution data.
        time : str or float, optional
            Time at which the pad will be computed.
        window : float, optional
            Length in seconds from TIME over which data will be averaged.
        center_time : bool, optional
            Flag denoting that TIME should be the midpoint for the window instead of the beginning.
        trange : list, optional
            Two-element time range over which data will be averaged.
        samples : int or float, optional
            Number of nearest samples to TIME to average.
        mag_data : str, optional
            Name of tplot variable containing magnetic field data or 3-vector.
            This will be used for pitch-angle calculation and must be in the
            same coordinates as the particle data.
        vel_data : str, optional
            Name of tplot variable containing the bulk velocity data or 3-vector.
            This will be used for pitch-angle calculation and must be in the
            same coordinates as the particle data.
        nbin : int, optional
            Number of bins in the pitch-angle direction.
        da : float, optional
            Pitch angle range for the "para" spectrum, default = 45.0.
        da2 : float, optional
            Pitch angle range for the "anti-para" spectrum, default = 45.0.
        pr___0 : list or tuple, optional
            Pitch angle range for the "para" spectrum, default = [0, 45].
        pr__90 : list or tuple, optional
            Pitch angle range for the "perp" spectrum, default = [45, 135].
        pr_180 : list or tuple, optional
            Pitch angle range for the "anti-para" spectrum, default = [135, 180].
        subtract_bulk : bool, optional
            Set True to subtract bulk velocity from velocity data.
        units : str, optional
            Units for both the pitch-angle-distribution (pad) and energy spectrum.
            Options are 'eflux' [eV/(cm!U2!N s sr eV)] or 'df_km' [s!U3!N / km!U6!N'].
            The default is 'eflux'.
        oclreal : bool, optional
            Set True to return the real one-count level
        norm : bool, optional
            Set True for normalizing the data at each energy bin.

    Returns
    --------
        results : dict
            A dictionary containing the following results:
            - trange : list
                Two-element time range over which data was averaged.
            - egy : array-like
                Energy values in eV.
            - pa : array-like
                Pitch angle values in degrees.
            - data : array-like, shape (Nenergy, Npitch)
                Pitch-angle distribution (angle vs energy plot).
            - datanorm : array-like, shape (Nenergy, Npitch)
                Normalized pitch-angle distribution (angle vs energy plot).
            - numSlices : int
                Number of slices in the data.
            - nbin : int
                Number of pitch angle bins.
            - units : str
                Units of the returned data.
            - subtract_bulk : bool
                True if bulk velocity was subtracted from velocity data.
            - egyrange : list
                Energy range of the data.
            - spec___0 : array-like
                Energy spectrum in the "para" direction.
            - spec__90 : array-like
                Energy spectrum in the "perp" direction.
            - spec_180 : array-like
                Energy spectrum in the "anti-para" direction.
            - spec_omn : array-like
                Energy spectrum in the omni direction.
            - cnts___0 : array-like
                One-count-level data in the "para" direction.
            - cnts__90 : array-like
                One-count-level data in the "perp" direction.
            - cnts_180 : array-like
                One-count-level data in the "anti-para" direction.
            - cnts_omn : array-like
                One-count-level data in the omni direction.
            - oclv___0 : array-like
                One-count-level data in the "para" direction.
            - oclv__90 : array-like
                One-count-level data in the "perp" direction.
            - oclv_180 : array-like
                One-count-level data in the "anti-para" direction.
            - oclv_omn : array-like
                One-count-level data in the omni direction.
            - eror___0 : array-like
                Error data in the "para" direction.
            - eror__90 : array-like
                Error data in the "perp" direction.
            - eror_180 : array-like
                Error data in the "anti-para" direction.
            - eror_omn : array-like
                Error data in the omni direction.
            - vbulk_para : float
                Bulk velocity in the "para" direction.
            - vbulk_perp_abs : float
                Absolute value of bulk velocity in the "perp" direction.
            - vbulk_vxb : float
                Velocity of the cross product of magnetic field and bulk velocity.
            - vbulk_exb : float
                Velocity of the cross product of electric field and magnetic field.
            - bnrm : float
                Average magnetic field magnitude.
            - Vbulk : float
                Bulk velocity magnitude.
            - bfield : float
                Magnetic field magnitude.
            - species : str
                Name of the particle species.
            - pa_azpol : array-like, shape (Npitch, 2)
                Pitch angle values in degrees in azimuthal and polar coordinates.


    Creates various plots directly from the FPI distribution functions, including:
         - angle-angle (azimuth vs zenith)
         - angle-energy (azimuth and zenith vs energy)

    Input
    ------
        time: str
            Time to generate the angle-angle plots for

    Parameters
    -----------
        species: str
            'i' for ions, 'e' for electrons

        probe: str
            MMS spacecraft probe # (1-4)

        data_rate: str
            Data rate ('brst' or 'fast')

        level: str
            Data level

        center_measurement: bool
            Flag to center the FPI measurements

        energy_range: list
            Range of energies to include in the figures (default: 10-30000 eV)

        xsize: float
            X-size of the output figure

        ysize: float
            Y-size of the output figure

        cmap: str
            Color map to use (default: 'spedas')

        zrange: list
            Range of the color bar

        display: bool
            Flag to display the figures (with plt.show()); default: True


    Load data from the MMS Fast Plasma Investigation (FPI)

    Parameters
    ----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']
            Default: ['2015-10-16', '2015-10-17']

        probe : str or list of str
            list of probes, valid values for MMS probes are ['1','2','3','4'].
            Default: '1'

        data_rate : str or list of str
            instrument data rates for FPI include 'brst', 'fast'.
            Default: 'fast'

        level : str
            indicates level of data processing. Valid options: 'l2', 'ql'
            Default: 'l2'

        datatype : str or list of str
            Valid datatypes for FPI are:
             'des-moms', 'dis-moms', 'des-momsaux', 'dis-momsaux', 'des-partmoms', 'dis-partmoms', 'des-dist', 'dis-dist', 'des', 'dis'
             Defaults:
             ['des-moms', 'dis-moms', 'des-dist' , 'dis-dist', 'des-momsaux', 'dis-momsaux'] (for level != 'ql' or unspecified)
             ['des', 'dis'] (for level == 'ql')

        get_support_data: bool
            Data with an attribute "VAR_TYPE" with a value of "support_data"
            will be loaded into tplot.
            Default: False

        time_clip: bool
            Data will be clipped to the exact trange specified by the trange keyword.
            Default: False

        varformat: str
            The file variable formats to load into tplot.  Wildcard character
            "*" is accepted.
            Default: None (All variables are loaded)

        varnames: list of str
            List of variable names to load. If list is empty or not specified,
            all data variables are loaded
            Default: [] (all variables are loaded)

        suffix: str
            The tplot variable names will be given this suffix.
            Default: None

        center_measurement: bool
            If True, the CDF epoch variables are time-shifted to the middle
            of the accumulation interval by their DELTA_PLUS_VAR and
            DELTA_MINUS_VAR variable attributes
            Default: False

        notplot: bool
            If True, then data are returned in a hash table instead of
            being stored in tplot variables (useful for debugging, and
            access to multidimensional data products)
            Default: False

        available: bool
            If True, simply return the available data files (without downloading)
            for the requested parameters
            Default: False

        no_update: bool
            Set this flag to preserve the original data. if not set and newer
            data is found the existing data will be overwritten
            Default: False

        cdf_version: str
            Specify a specific CDF version # to load (e.g., cdf_version='4.3.0')
            Default: None

        min_version: str
            Specify a minimum CDF version # to load
            Default: None

        latest_version: bool
            Only grab the latest CDF version in the requested time interval
            Default: False

        major_version: bool
            Only open the latest major CDF version (e.g., X in vX.Y.Z) in the requested time interval
            Default: False

        always_prompt: bool
            Set this keyword to always prompt for the user's username and password;
            useful if you accidentally save an incorrect password, or if your SDC password has changed
            Default: False

        spdf: bool
            If True, download the data from the SPDF instead of the SDC
            Default: False

    Returns
    -------
        list of str
            List of tplot variables created.

    Example
    -------

    >>> import pyspedas
    >>> from pyspedas import tplot
    >>> fpi_vars = pyspedas.projects.mms.mms_load_fpi(trange=['2015-10-16', '2015-10-17'], datatype='dis-moms')
    >>> tplot(['mms1_dis_bulkv_gse_fast', 'mms1_dis_numberdensity_fast'])


    Splits FPI tensor variables (pressure, temperature) into their components

    Input
    -----------
        tensor_variable: str
            Tplot variable containing the tensor data

    Returns
    ---------
        List of variables created.


    This function updates the metadata for FPI data products

    Parameters
    ----------
        probe : str or list of str
            probe or list of probes, valid values for MMS probes are ['1','2','3','4'].

        data_rate : str or list of str
            instrument data rates for FPI include 'brst' and 'fast'. The
            default is 'fast'.

        level : str
            indicates level of data processing. the default if no level is specified is 'l2'
            Not used (as of 29May2021)

        suffix: str
            The tplot variable names will be given this suffix.  By default,
            no suffix is added.


    Calculates the omni-directional pitch angle distribution (summed and averaged)
    from the individual tplot variables

    Parameters
    ----------
        probe: str
            probe, valid values for MMS probes are ['1','2','3','4'].

        level: str
            indicates level of data processing. the default if no level is specified is 'sitl'

        datatype: str
            Valid datatypes for FPI are:
              Quicklook: ['des', 'dis']
              SITL: '' (none; loads both electron and ion data from single CDF)
              L1b/L2: ['des-dist', 'dis-dist', 'dis-moms', 'des-moms']

        data_rate: str
            instrument data rates for FPI include 'brst' and 'fast'. The
            default is 'fast'.

        suffix: str
            The tplot variable names will be given this suffix.  By default,
            no suffix is added.

        autoscale: bool
            If set, use the default zrange; otherwise, use the min and max of the data for the zrange

    Returns
    ----------
        List of tplot variables created.


    Returns 3D particle data structures containing MMS FPI
    data for use with SPEDAS particle routines.

    Input
    ----------
        tname: str
            tplot variable name containing the FPI distribution data

    Parameters
    ----------
        probe: str
            Spacecraft probe #

        data_rate: str
            Instrument data rates for FPI include 'brst' and 'fast'

        species: str
            Species of the data specified by the 'tname' input
            (valid options: 'i' for ions and 'e' for electrons)

        index: int
            Index of time sample to return

    Returns
    ----------
        3D particle data structure(s) containing MMS FPI distribution functions


    Creates FPI's compressionloss flag bars

    Parameters
    -----------
        tname: str
            Tplot variable name of DIS or DES compressionloss data

        lossy: bool
            The value for lossy compression (use this keyword only for special case)

    Flag
    -----------
        0: Lossless compression
        1: Lossy compression
      In old files (v2.1.0 or older until the end of Phase 1A)
        1: Lossless compression
        3: Lossy compression

    Notes
    -----------
        In cases when data had been lossy compressed, some artifacts may appear in the data due to the compression.
        Since all of fast survey data are lossy compressed, it is not necessary to make this bar for fast survey data.

    Returns
    ------------
        List of the tplot variables created.


    This procedure creates FPI error flag bars for plotting

        For DES/DIS moments:
            tname+'_flagbars_full': Detailed flag bars (all bars)
            tname+'_flagbars_main': Standard flag bars (4 bars)
            tname+'_flagbars_mini': Smallest flag bar (1 bars)

        For DES/DIS distribution functions
            tname+'_flagbars_dist': Standard flag bars (2 bars)

    Input
    -----------
        tname: str
            tplot variable containing the DIS or DES errorflag data

    Parameters
    -----------
        level: str
            Level of the data to create the errorflags bar for;
            (default is l2; this only needs to be set for QL data)

    Examples
    -----------
       > mms_fpi_make_errorflagbars('mms1_des_errorflags_fast')
       > mms_fpi_make_errorflagbars('mms1_dis_errorflags_fast')
       > mms_fpi_make_errorflagbars('mms1_des_errorflags_brst')
       > mms_fpi_make_errorflagbars('mms1_dis_errorflags_brst')

       For DES/DIS distribution function (Brst and Fast):
         bit 0 = manually flagged interval --> contact the FPI team for direction when utilizing this data; further correction is required
         bit 1 = overcounting/saturation effects likely present in skymap

       For DES/DIS moments (Brst):
         bit 0 = manually flagged interval  --> contact the FPI team for direction when utilizing this data; further correction is required
         bit 1 = overcounting/saturation effects likely present in skymap
         bit 2 = reported spacecraft potential above 20V
         bit 3 = invalid/unavailable spacecraft potential
         bit 4 = significant (>10%) cold plasma (<10eV) component
         bit 5 = significant (>25%) hot plasma (>30keV) component
         bit 6 = high sonic Mach number (v/vth > 2.5)
         bit 7 = low calculated density (n_DES < 0.05 cm^-3)
         bit 8 = onboard magnetic field used instead of brst l2pre magnetic field
         bit 9 = srvy l2pre magnetic field used instead of brst l2pre magnetic field
         bit 10 = no internally generated photoelectron correction applied
         bit 11 = compression pipeline error
         Bit 12 = spintone calculation error (DBCS only)
         Bit 13 = significant (>=20%) penetrating radiation (DIS only)
         Bit 14 = high MMS3 spintone due to DIS008 anomaly (DIS only)

       For DES/DIS moments (Fast):
         bit 0 = manually flagged interval --> contact the FPI team for direction when utilizing this data; further correction is required
         bit 1 = overcounting/saturation effects likely present in skymap
         bit 2 = reported spacecraft potential above 20V
         bit 3 = invalid/unavailable spacecraft potential
         bit 4 = significant (>10%) cold plasma (<10eV) component
         bit 5 = significant (>25%) hot plasma (>30keV) component
         bit 6 = high sonic Mach number (v/vth > 2.5)
         bit 7 = low calculated density (n_DES < 0.05 cm^-3)
         bit 8 = onboard magnetic field used instead of srvy l2pre magnetic field
         bit 9 = not used
         bit 10 = no internally generated photoelectron correction applied
         bit 11 = compression pipeline error
         Bit 12 = spintone calculation error (DBCS only)
         Bit 13 = significant (>=20%) penetrating radiation (DIS only)
         Bit 14 = high MMS3 spintone due to DIS008 anomaly (DIS only)

    Notes
    -----------
        EXPERIMENTAL!
        Based on the IDL version by Naritoshi Kitamura

    Returns
    -----------
        List containing the names of the created tplot variables


    Load data from the MMS Digital Signal Processing (DSP) board.

    Parameters
    ----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']
            Default: ['2015-10-16', '2015-10']

        probe : str or list of str
            list of probes, valid values for MMS probes are ['1','2','3','4'].
            Default: '1'

        data_rate : str or list of str
            instrument data rates for DSP include ['fast', 'slow', 'srvy'].
            Default: 'srvy'

        level : str
            indicates level of data processing.
            Default: 'l2'

        datatype : str or list of str
            Valid datatypes for DSP are: ['epsd', 'bpsd', 'swd']
            Default: 'bpsd'

        get_support_data: bool
            Data with an attribute "VAR_TYPE" with a value of "support_data"
            will be loaded into tplot.
            Default: False

        time_clip: bool
            Data will be clipped to the exact trange specified by the trange keyword.
            Default: False

        varformat: str
            The file variable formats to load into tplot.  Wildcard character
            "*" is accepted.
            Default: None (all variables are loaded)

        varnames: list of str
            List of variable names to load.  If list is empty or unspecified,
            all data variables are loaded)
            Default: []

        suffix: str
            The tplot variable names will be given this suffix.
            Default: None

        notplot: bool
            If True, then data are returned in a hash table instead of
            being stored in tplot variables (useful for debugging, and
            access to multidimensional data products)
            Default: False

        available: bool
            If True, simply return the available data files (without downloading)
            for the requested parameters
            Default: False

        no_update: bool
            Set this flag to preserve the original data. if not set and newer
            data is found the existing data will be overwritten
            Default: False

        cdf_version: str
            Specify a specific CDF version # to load (e.g., cdf_version='4.3.0')
            Default: None

        min_version: str
            Specify a minimum CDF version # to load
            Default: None

        latest_version: bool
            Only grab the latest CDF version in the requested time interval
            Default: False

        major_version: bool
            Only open the latest major CDF version (e.g., X in vX.Y.Z) in the requested time interval
            Default: False

        always_prompt: bool
            Set this keyword to always prompt for the user's username and password;
            useful if you accidentally save an incorrect password, or if your SDC password has changed
            Default: False

        spdf: bool
            If True, download the data from the SPDF instead of the SDC
            Default: False

    Returns
    --------
        list of str
            List of tplot variables created.

    Examples
    --------

    >>> import pyspedas
    >>> from pyspedas import tplot
    >>> dsp_data = pyspedas.projects.mms.mms_load_dsp(trange=['2015-10-16', '2015-10-17'], probe='1', data_rate='fast', datatype='bpsd')
    >>> tplot('mms1_dsp_bpsd_omni_fast_l2')


    This function updates the metadata for DSP data products

    Parameters
    ----------
        probe : str or list of str
            probe or list of probes, valid values for MMS probes are ['1','2','3','4'].

        data_rate : str or list of str
            instrument data rate for DSP

        level : str
            indicates level of data processing. the default if no level is specified is 'l2'

        suffix: str
            The tplot variable names will be given this suffix.  By default,
            no suffix is added.


    Performs a quaternion rotation on a tplot variable.

    Note: this routine will interpolate the input data to the quaternion
    timestamps if the data aren't the same length as the quaternions

    Parameters
    ----------
        in_name: str
            Tplot variable to be transformed

        q_name: str
            Tplot variable containing the quaternions

        out_name: str
            Tplot variable to be created

        inverse: bool:
            Flag to use the quaternionConjugate on the quaternion data prior to rotating


    Support routine for mms_qcotrans; recursively goes from one coordinate system to
    another by going through ECI

    Operates on a single variable/transformation at a time

    Parameters
    -----------
        in_name: str
            Tplot variable to be transformed

        out_name: str
            Tplot variable to be created with the transformed data

        in_coord: str
            Coordinate system of the input data

        out_coord: str
            Coordinate system to rotate to

        probe: str
            Spacecraft probe #


    Tranforms MMS vector fields from GSM coordinates to LMN (boundary-normal) coordinates
    using the Shue et al., 1998 magnetopause model

    Input
    ------
        name_in: str
            Name of the input tplot variable

        name_out: str
            Name of the output tplot variable

    Parameters
    -----------
        gsm: bool
            Flag to indicate the input data are in GSM coordinates

        gse: bool
            Flag to indicate the input data are in GSE coordinates; note: the input data
            will be transformed to GSM prior to transforming to LMN

        probe: str
            Spacecraft probe #; if not specified, the routine attempts to extract from the
            input variable name

        data_rate: str
            Data rate of the ephemeris support data to be loaded; default is 'srvy'

    Returns
    --------
        Name of the variable containing the data in LMN coordinates.


    Loads solar wind data for use in the GSM to LMN transformation.

    Parameters
    ----------
        trange: list of float
            Time range of data to be loaded

        level: str
            Data level (default: hro2)

        min5: bool
            Flag indicating whether to load 1 minute or 5 minute data (default: 1 minute)

    Returns
    -------
        Numpy array of solar wind data with shape (N, 3), where N is the number of time points
        and the columns are the time, Bz GSM, and pressure.


    Perform coordinate transformations using MMS MEC quaternions.

    This routine uses SpacePy to do the quaternion transformation operations.

    Parameters
    -----------
        in_name: str or list of str
            Names of Tplot variables of vectors to be transformed

        out_name: str or list of str
            Names of output variables

        in_coord: str
            Input coordinate system, valid options:
            'bcs', 'dbcs', 'dmpa', 'smpa', 'dsl', 'ssl', 'gse', 'gse2000', 'gsm', 'sm', 'geo', 'eci', 'j2000'

        out_coord: str
            Output coordinate system valid options:
            'bcs', 'dbcs', 'dmpa', 'smpa', 'dsl', 'ssl', 'gse', 'gse2000', 'gsm', 'sm', 'geo', 'eci', 'j2000'

        probe: str
            MMS spacecraft # (must be 1, 2, 3, or 4)

    Returns
    --------
        List of variables created

    Examples
    --------
    >>> from pyspedas.projects.mms import mec, mms_qcotrans # Import MMS namespace and mms_qcotrans routine
    >>> from pyspedas import tplot # Import tplot routine to plot results
    >>> mec(trange=['2015-10-16', '2015-10-17'], probe='1')   # Load quaternions, positions, and velocity variables from MEC data, using default datatypes
    >>> mms_qcotrans('mms1_mec_v_sm', 'mms1_mec_v_sm_2gse', out_coord='gse') # Transform SM velocity to GSE
    >>> tplot(['mms1_mec_v_sm','mms1_mec_v_sm_2gse']) # Plot input and output variables


    Calculate spin-averaged pitch angle distributions using data from the MMS Energetic Ion Spectrometer (EIS)

    Parameters
    ----------
        scopes: list of str
            telescope #s to include in the calculation

        probe: str
            probe #, e.g., '4' for MMS4

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst' (default: 'srvy')

        level: str
            data level ['l1a','l1b','l2pre','l2' (default)]

        datatype: str
            'extof' or 'phxtof' (default: 'extof')

        data_units: str
            'flux' or 'cps' (default: 'flux')

        species: str
            species for calculation (default: 'proton')

        energy: list of float
            energy range to include in the calculation (default: [55, 800])

        size_pabin: int
            size of the pitch angle bins, in degrees (default: 15)

        suffix: str
            suffix of the loaded data

    Returns
    --------
        Name of tplot variables created.


    Combines omni-directional energy spectrogram variable from EIS on multiple
        MMS spacecraft.

    Parameters
    ----------
        datatype: str
            'extof', 'electroenergy', or 'phxtof' (default: 'extof')

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst' (default: 'srvy')

        level: str
            data level ['l1a','l1b','l2pre','l2' (default)]

        data_units: str
            desired units for data, e.g., 'flux' or 'cps' (default: 'flux')

        suffix: str
            suffix of the loaded data; useful for preserving original tplot var

        species: str
            species for calculation, e.g., proton, oxygen, alpha or electron
            (default: 'proton')

    Returns
    --------
        Name of tplot variables created.


    This function updates the metadata for the EIS data products

    Parameters
    ----------
        tplotnames : list of str
            list of tplot variables loaded by the load routine

        data_rate : str
            Data rate

        datatype : str
            EIS datatype loaded (extof or phxtof)

        suffix: str
            The tplot variable names will be given this suffix.  By default,
            no suffix is added.


    Calculate pitch angle distributions using data from the MMS Energetic Ion Spectrometer (EIS)

    Parameters
    ----------
        scopes: list of str
            telescope #s to include in the calculation

        probe: str
            probe #, e.g., '4' for MMS4

        level: str
            data level for calculation (default: 'l2')

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst' (default: 'srvy')

        datatype: str
            'extof' or 'phxtof' (default: 'extof')

        species: str
            species for calculation (default: 'proton')

        data_units: str
            'flux' or 'cps' (default: 'flux')

        energy: list of float
            energy range to include in the calculation (default: [55, 800])

        size_pabin: int
            size of the pitch angle bins, in degrees (default: 15)

        suffix: str
            suffix of the loaded data

    Returns
    ----------
        Name of tplot variables created.


    This function will spin-average the EIS spectrograms, and is automatically called from mms_load_eis

    Parameters
    ----------
        probe: str
            probe #, e.g., '4' for MMS4

        species: str
            species for calculation (default: 'proton')

        data_units: str
            'flux' or 'cps' (default: 'flux')

        datatype: str
            'extof' or 'phxtof' (default: 'extof')

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst' (default: 'srvy')

        level: str
            data level ['l1a','l1b','l2pre','l2' (default)]

        suffix: str
            suffix of the loaded data

    Returns
    --------
        List of tplot variables created.


    Load data from the MMS Energetic Ion Spectrometer (EIS)

    Parameters
    ----------
        trange : list of str
            time range of interest [start time, end time] with the format
            'YYYY-MM-DD','YYYY-MM-DD'] or to specify more or less than a day
            ['YYYY-MM-DD/hh:mm:ss','YYYY-MM-DD/hh:mm:ss']
            Default: ['2015-10-16', '2015-10-17']

        probe : str or list of str
            list of probes, valid values for MMS probes are ['1','2','3','4'].
            Default: '1'

        data_rate : str or list of str
            instrument data rates for EIS include ['brst', 'srvy'].
            Default: 'srvy'

        level : str
            indicates level of data processing.
            Default: 'l2'

        datatype : str or list of str
            Valid datatypes for EIS are: ['extof', 'phxtof', and 'electronenergy']
            Default: 'extof'

        get_support_data: bool
            Data with an attribute "VAR_TYPE" with a value of "support_data"
            will be loaded into tplot.
            Default: 'True'

        time_clip: bool
            Data will be clipped to the exact trange specified by the trange keyword.
            Default: 'False'

        varformat: str
            The file variable formats to load into tplot.  Wildcard character
            "*" is accepted.
            Default: None (all variables are loaded)

        varnames: list of str
            List of variable names to load. If list is empty or not specified,
            all data variables are loaded.
            Default: []

        suffix: str
            The tplot variable names will be given this suffix.
            Default: None

        notplot: bool
            If True, then data are returned in a hash table instead of
            being stored in tplot variables (useful for debugging, and
            access to multidimensional data products)
            Default: False

        available: bool
            If True, simply return the available data files (without downloading)
            for the requested parameters
            Default: False

        no_update: bool
            Set this flag to preserve the original data. if not set and newer
            data is found the existing data will be overwritten
            Default: False

        cdf_version: str
            Specify a specific CDF version # to load (e.g., cdf_version='4.3.0')
            Default: None

        min_version: str
            Specify a minimum CDF version # to load
            Default: None

        latest_version: bool
            Only grab the latest CDF version in the requested time interval
            Default: False

        major_version: bool
            Only open the latest major CDF version (e.g., X in vX.Y.Z) in the requested time interval
            Default: False

        always_prompt: bool
            Set this keyword to always prompt for the user's username and password;
            useful if you accidentally save an incorrect password, or if your SDC password has changed
            Default: False

        spdf: bool
            If True, download the data from the SPDF instead of the SDC
            Default: False

    Returns
    -------
        list of str
            List of tplot variables created.

    Example
    -------

    >>> import pyspedas
    >>> from pyspedas import tplot
    >>> eis_vars = pyspedas.projects.mms.mms_load_eis(trange=['2015-10-16', '2015-10-17'], probe='1', datatype=['phxtof', 'extof'])
    >>> # plot the non-spin averaged flux
    >>> tplot(['mms1_epd_eis_srvy_l2_extof_proton_flux_omni', 'mms1_epd_eis_srvy_l2_phxtof_proton_flux_omni'])
    >>> # plot the spin averaged flux
    >>> tplot(['mms1_epd_eis_srvy_l2_extof_proton_flux_omni_spin', 'mms1_epd_eis_srvy_l2_phxtof_proton_flux_omni_spin'])


    This function will calculate the omnidirectional EIS spectrograms, and is automatically called from mms_load_eis

    Parameters
    ----------
        probe: str
            probe #, e.g., '4' for MMS4

        species: str
            species for calculation (default: 'proton')

        datatype: str
            'extof' or 'phxtof' (default: 'extof')

        suffix: str
            suffix of the loaded data

        data_units: str
            'flux' or 'cps' (default: 'flux')

        data_rate: str
            instrument data rate, e.g., 'srvy' or 'brst' (default: 'srvy')

        level: str
            data level ['l1a','l1b','l2pre','l2' (default)]

    Returns
    ---------
        Name of tplot variable created.


    Generate spectra and moments from 3D MMS particle data; note: this routine isn't
    meant to be called directly - see the wrapper mms_part_getspec instead.

    Input
    ----------
        in_tvarname: str
            Name of the tplot variable containing MMS 3D particle distribution data

    Parameters
    ----------
        units: str
            Specify units of output variables; must be 'eflux' to calculate moments

            valid options:
            'flux'   -  # / (cm^2 * s * sr * eV)
            'eflux'  -  eV / (cm^2 * s * sr * eV)  <default>
            'df_cm'  -  s^3 / cm^6
            'df_km'  -  s^3 / km^6

        species: str
            Specify the species of the input tplot variable

        data_rate: str
            Data rate of the input data

        instrument: str
            Instrument (FPI or HPCA)

        probe: int or str
            Spacecraft probe #

        output: str or list of str
            Output variables; options::

                'energy': energy spectrograms
                'theta': theta spectrograms
                'phi': phi spectrograms
                'pa': pitch-angle spectrograms
                'gyro': gyro-phase spectrograms
                'moments': plasma moments
                'fac_energy': energy spectrogram in field-aligned coordinates
                'fac_moments': moments in field-aligned coordinates

        energy: list of float
            Energy range [min, max], in eV

        phi: list of float
            Phi range [min, max], in degrees

        theta: list of float
            Theta range [min, max], in degrees

        pitch: list of float
            Pitch-angle range [min, max], in degrees

        gyro: list of float
            Gyro-angle range [min, max], in degrees

        mag_name: str
            Tplot variable containing magnetic field data for
            moments and FAC transformations

        pos_name: str
            Tplot variable containing spacecraft position for
            FAC transformations

        sc_pot_name: str
            Tplot variable containing spacecraft potential data
            for moments corrections

        fac_type: str
            Field aligned coordinate system variant; default: 'mphigeo'
            options: 'phigeo', 'mphigeo', 'xgse'

        correct_photoelectrons: bool
            Flag to correct FPI data for photoelectrons
            (defaults to True for FPI electron data - disable with the parameter below)

        disable_photoelectron_corrections: bool
            Flag to disable FPI photoelectron corrections

        internal_photoelectron_corrections: bool
            Apply internal photoelectron corrections

        zero_negative_values: bool
            Turn negative values to 0 after doing the photoelectron corrections (DES)

        no_regrid: bool
            Flag to disable reegridding

            ###new###
        subtract_bulk: bool
            Subtracts the bulk velocity from the distribution data

        regrid: array of int
            Array giving dimensions of regridded data
            Default: [32,16]

        vel_name: str
            Name of tplot variable containing bulk velocity data

        prefix: str
            Prefix for output tplot variables. Default: ''

        suffix: str
            Suffix for output tplot variables. Default: ''

        sdc_units: bool
            If True, convert moments ptens and qflux values and units to nPa and mW/m^2 respectively, for
            compatibility with MMS SDC products.
            Default: False

    Returns
    ----------
        Creates tplot variables containing spectrograms and moments


    Perform unit conversions for MMS particle data structures

    Input
    ----------
        data_in: dict
            Single particle data structure

    Parameters
    ----------
        units: str
            String specifying output units
            supported units:
                flux   -   # / (cm^2 * s * sr * eV)
                eflux  -  eV / (cm^2 * s * sr * eV)
                df_cm  -  s^3 / cm^6
                df_km     -  s^3 / km^6

    Returns
    ----------
        3D particle data structure with the data in the units specified by
        the 'units' parameter


    Generate spectra and moments from 3D MMS particle data

    Parameters
    ----------
        trange: list of str
            Time range

        units: str
            Specify units of output variables; must be 'eflux' to calculate moments.   Valid options::

                'flux'   -  # / (cm^2 * s * sr * eV)
                'eflux'  -  eV / (cm^2 * s * sr * eV)  <default>
                'df_cm'  -  s^3 / cm^6
                'df_km'  -  s^3 / km^6

            Default: 'eflux'

        species: str
            Specify the species of the input tplot variable (Default: 'e')

        data_rate: str
            Data rate of the input data (Default: 'fast')

        instrument: str
            Instrument (FPI or HPCA)

        probe: int or str
            Spacecraft probe # (Default: 1)

        output: str or list of str
            Output variables; options::

                'energy': energy spectrograms
                'theta': theta spectrograms
                'phi': phi spectrograms
                'pa': pitch-angle spectrograms
                'gyro': gyro-phase spectrograms
                'moments': plasma moments

            Default: ['energy', 'theta', 'phi', 'pa', 'gyro']

        energy: list of float
            Energy range [min, max], in eV

        phi: list of float
            Phi range [min, max], in degrees

        theta: list of float
            Theta range [min, max], in degrees

        pitch: list of float
            Pitch-angle range [min, max], in degrees

        gyro: list of float
            Gyro-angle range [min, max], in degrees

        mag_name: str
            Tplot variable containing magnetic field data for
            moments and FAC transformations

        mag_data_rate: str
            Data rate to use when loading the spacecraft potential data ('fast', 'srvy' or 'brst')
            If not given, defaults to value of 'data_rate'.

        pos_name: str
            Tplot variable containing spacecraft position for
            FAC transformations. If not given, defaults to 'mmsN_mec_r_gse'

        sc_pot_name: str
            If set, overrides default sc_pot variable name constructed from sc_pot_data_rate below.
            Default: None

        sc_pot_data_rate: str
            Data rate to use when loading the spacecraft potential data ('fast', 'srvy' or 'brst')
            If not given, defaults to value of 'data_rate'.

        fac_type: str
            Field aligned coordinate system variant; options::

                'phigeo'
                'mphigeo'
                'xgse'

            Default: 'mphigeo'

        ### ADDED 4.16.2025, TESTING BULK VELOCITY SUBTRACTION
        subtract_bulk: bool
            subtract the bulk velocity prior to doing the calculations

        vel_name: str
            Tplot variable containing velocity data in km/s for use with /subtract_bulk

        vel_data_rate: str
            Data rate to use when loading the bulk velocity data ('fast' or 'brst')

        #################

        correct_photoelectrons: bool
            Flag to correct FPI data for photoelectrons
            (defaults to True for FPI electron data - disable with the parameter below)

        disable_photoelectron_corrections: bool
            Flag to disable FPI photoelectron corrections

        internal_photoelectron_corrections: bool
            Apply internal photoelectron corrections

        zero_negative_values: bool
            Turn negative values to 0 after doing the photoelectron corrections (DES)

        regrid: array of int
            Dimensions for regridded data array (see no_regrid flag below)
            Default: [32,16]

        no_regrid: bool
            Flag to disable regridding of data array

        prefix: str
            Prefix for output tplot variables. Default: ''

        suffix: str
            Suffix for output tplot variables. Default: ''

        sdc_units: bool
            If True, convert moments ptens and qflux values and units to nPa and mW/m^2 respectively, for
            compatibility with MMS SDC products
            Default: False

    Returns
    -------
    None
       Creates tplot variables containing spectrograms and moments


    Builds phi (longitudinal) spectrogram from a sanitized particle data structure.

    Parameters
    ----------
    data_in : dict
        The sanitized particle data structure containing 'phi', 'data', and 'bins' arrays.
    resolution : int, optional
        The number of bins to divide the 360 degrees of phi into. Default is 32.

    Returns
    -------
    y : array
        The bin centers for the phi spectrogram.
    ave : array
        The phi spectrogram with shape (n_phi,).

    Notes
    -----
    This function concatenates the sample's data to the `spec` variable. Both
    the spectrogram `spec` and the y-axis `yaxis` will be initialized if not set.
    The y-axis will remain a single dimension until a change is detected in the data,
    at which point it will be expanded to two dimensions.


    This routine creates 2D slices of 3D distribution function data from the FPI and HPCA instruments.
    This is essentially a wrapper around slice2d and slice2d_plot, that loads the data,
    any required support data, calculates the slice with slice2d and plots it with slice2d_plot.

    Parameters
    -----------
        probe: int or str
            MMS spacecraft probe # (1, 2, 3 or 4)

        instrument: str
            MMS plasma instrument (fpi or hpca)

        species: str
            Particle species; depends on the instrument::

                FPI: 'e' for electrons, 'i' for ions
                HPCA: 'hplus' for H+, 'oplus' for O+, 'heplus' for He+, 'heplusplus', for He++

        data_rate: str
            FPI/HPCA data rate [fast (fpi), srvy (hpca), or brst (both fpi and hpca)]

        mag_data_rate: str
            FGM data rate for transformations

        level: str
            Data level (default: l2); lower levels require an SDC username and password

        spdf: bool
            Flag to download the data from SPDF instead of the MMS SDC

        trange: list of str or list of float
            Two-element time range over which data will be averaged (optional; can also use the 'time' keyword)

        time: str or float
            Time at which the slice will be computed (optional; can also use 'trange' above)

        samples: int
            Number of nearest samples to TIME to average.

        window: float
            Length in seconds from TIME over which data will be averaged

        center_time: bool
            Flag denoting that TIME should be midpoint for window instead of beginning

        interpolation: str
            Interpolation method; valid options::

                'geometric': Each point on the plot is given the value of the bin it intersects.
                            This allows bin boundaries to be drawn at high resolutions.
                '2d': Data points within the specified theta or z-axis range are projected onto
                            the slice plane and linearly interpolated onto a regular 2D grid.

        rotation: str
            Aligns the data relative to the magnetic field and/or bulk velocity.
            This is applied after the CUSTOM_ROTATION. (BV and BE are invariant
            between coordinate systems); valid options::

                'BV':  The x axis is parallel to B field; the bulk velocity defines the x-y plane
                'BE':  The x axis is parallel to B field; the B x V(bulk) vector defines the x-y plane
                'xy':  (default) The x axis is along the data's x axis and y is along the data's y axis
                'xz':  The x axis is along the data's x axis and y is along the data's z axis
                'yz':  The x axis is along the data's y axis and y is along the data's z axis
                'xvel':  The x axis is along the data's x axis; the x-y plane is defined by the bulk velocity
                'perp':  The x axis is the bulk velocity projected onto the plane normal to the B field; y is B x V(bulk)
                'perp_xy':  The data's x & y axes are projected onto the plane normal to the B field
                'perp_xz':  The data's x & z axes are projected onto the plane normal to the B field
                'perp_yz':  The data's y & z axes are projected onto the plane normal to the B field

        custom_rotation: str or np.ndarray
            Applies a custom rotation matrix to the data.  Input may be a
            3x3 rotation matrix or a tplot variable containing matrices.
            If the time window covers multiple matrices they will be averaged.
            This is applied before other transformations

        slice_x: str or np.ndarray
            Specifies the slice plane's x-axis within the coordinates
            specified by custom_rotation and rotation. If not specified, the given
            coordinate's x-axis will be used. If slice_x is not perpendicular to the
            normal, its projection onto the slice plane will be used.

        slice_norm: str or np.ndarray
            Specifies the slice plane's normal within the coordinates
            specified by custom_rotation and rotation; if not specified, the given
            coordinate's z-axis will be used (slice along by x-y plane in those coordinates).

        energy: bool
            Flag to plot data against energy (in eV) instead of velocity.

        log: bool
            Flag to apply logarithmic scaling to the radial measure (i.e. energy/velocity).
            (on by default if ENERGY is True)

        erange: list of float
            Two element array specifying the energy range to be used in eV

        thetarange: list of float
            (2D interpolation only) Angle range, in degrees [-90,90], used to calculate slice.
            Default = [-20,20]; will override ZDIRRANGE.

        zdirrange: list of float
            (2D interpolation only) Z-Axis range, in km/s, used to calculate slice.
            Ignored if called with THETARANGE.

        subtract_bulk: bool
            Subtract the bulk velocity vector

        resolution: int
            Integer specifying the resolution along each dimension of the
            slice (defaults:  2D interpolation: 150, geometric: 500)

        smooth: int
            An odd integer >=3 specifying the width of a smoothing window in #
            of points.  Smoothing is applied to the final plot using a gaussian
            convolution. Even entries will be incremented, 0 and 1 are ignored.

        xrange: list of float
            Keyword to limit the range of the slice's x-axis in the plot

        yrange: list of float
            Keyword to limit the range of the slice's y-axis in the plot

        zrange: list of float
            Keyword to limit the range of the slice's color bar

        save_png: str
            Save the plot as a PNG file

        save_eps: str
            Save the plot as an EPS file

        save_pdf: str
            Save the plot as a PDF file

        save_svg: str
            Save the plot as an SVG file

        display: bool
            Flag to allow disabling displaying of the figure

        return_slice: bool
            Flag to return the slice instead of displaying it

    Returns
    --------
    None or dict
        By default, no return value (but creates a figure). If return_slice=True, returns the slice data structure.

    Examples
    --------

    >>> from pyspedas.projects.mms import mms_part_slice2d
    >>> time = '2023-03-24/07:07:33'
    >>> # FPI ions with geometric interpolation
    >>> mms_part_slice2d(time=time, instrument='fpi', data_rate='brst', species='i', rotation='bv', erange=[0, 20000])
    >>> # Same as above, but return the slice data structure
    >>> the_slice = mms_part_slice2d(return_slice=True, time=time, instrument='fpi', species='i', rotation='bv', erange=[0, 20000])
    >>> # FPI ions with 2D interpolation
    >>> mms_part_slice2d(interpolation='2d', time=time, instrument='fpi', data_rate='brst', species='i', rotation='bv', erange=[0, 20000])


This is a translation of Mitsuo Oka's IDL routine: moka_mms_clean_data


    Builds an energy spectrogram from a simplified particle data structure.

    Parameters
    ----------
    data_in : dict
        The input data structure.

    Returns
    -------
    outtable : ndarray, shape (ny,)
        The energy bins.
    ave : ndarray, shape (ny,)
        The spectrogram.

    Notes
    -----
    - Each energy bin in the output spectrogram (`ave`) is the weighted average
      of the corresponding bins in the input data (`data_in`).
    - The input data is sanitized by zeroing inactive bins to ensure areas with
      no data are represented as NaN.
    - The function uses the first energy table for rebinning the data.


    Loads and returns the FPI/DES photoelectron model based on stepper ID

    Input
    ----------
        dist_var: str
            tplot variable containing DES distribution data

    Notes
    ----------
        For more information on the model, see:
        https://agupubs.onlinelibrary.wiley.com/doi/full/10.1002/2017JA024518

    Returns
    ----------
        Dictionary containing the photoelectron model


    Sanitize MMS FPI/HPCA data structures for use with
    mms_part_products; reforms energy by theta by phi to energy by angle
    and calculates delta-energy for each bin


    Split hpca elevation bins so that dphi == dtheta.
    This should allow the regrid step for FAC spectra to be skipped in mms_part_products.


    Builds a theta (latitudinal) spectrogram from a simplified particle data structure.

    Parameters
    ----------
    data_in : dict
        A dictionary containing the particle data, including 'data', 'theta', and 'bins' keys.
    resolution : int, optional
        The number of bins to use for the spectrogram. Defaults to 16.
    colatitude : bool, optional
        Set to True if the input data is in colatitude rather than latitude.

    Returns
    -------
    y : numpy.ndarray
        The y axis of the spectrogram.
    ave : numpy.ndarray
        The spectrogram.


    Transform and/or interpolate support data to match the particle data

    Parameters
    ----------
        mag_name: str
            Tplot variable containing magnetic field data

        vel_name: str
            Tplot variable containing bulk velocity data

        sc_pot_name: str
            Tplot variable containing spacecraft potential data

    Returns
    ----------
        Tuple containing interpolated (magnetic field, velocity, spacecraft potential)


Generates the 'xgse' transformation matrix


Generates the 'phigeo' transformation matrix


Generates the 'mphigeo' transformation matrix


Generate the field aligned coordinate transformation matrix