Create a plot of labels versus predictions

    Create a plot of labels versus predictions. The figure (or axes) is
    not displayed, but returned so the caller can display or save it as
    required.

    A 2-D histogram of the labels and predictions is generated, and
    optionally interpolated to give a smoothed result. The plot is
    coloured according to the number of (interpolated) samples at each

    Parameters
    ----------
    fig_name : str
        A name for the figure. Used to generate a title and filename
        for the figure.
    y : array
        The sample labels.
    yhat : array
        The sample predictions.
    top_text : str or dict, optional
        If str: The text to display in the top-left corner of the plot.
        If dict: The evaluation statistics. The text displayed is
        derived from these metrics.
        If None: No text is displayed. The default is None.
    bottom_text : str, optional
        If str: The text to display in the bottom-right plot corner.
        If None: No text is displayed. The default is None.
    lower : int, optional
        The lower bound to use for binning. The default is 0.
    upper : int, optional
        The upper bound to use for binning. The default is 300.
    interpolate : bool, optional
        True: Interpolate the result before plotting to smooth the plot
        points.
        False: Plot the raw results. The default is False.
    bins : int, optional
        The number of bins (in each dimension) to use when binning the
        data. Ignored if interpolate is False. The default is 30.
    diagonal : bool, optional.
    regress : bool or str, optional.
        Plot the regression line, if truthy. If type str, then assumed
        to be the plot colour. If True, the default colour is used.
    show_grid : bool, optional
    ax : MatPlotLib axes, optional
        An axes for the figure. Used if the plot is to be added as a
        sub-plot to a figure. If this is set, a figure object is not
        created and an axes object is returned. The default is None.
    cmap : Colormap, optional
    vmin : int, optional
        The minimum bin size. Only used for the colour scale, so does
        not cause an error if the number of values in a bin is less
        than this limit. The default is 0.
    vmax : int, optional
        The maximum bin size. Only used for the colour scale, so does
        not cause an error if the number of values in a bin exceeds
        this limit. The default is 25.

    Returns
    -------
    MatPlotLib axes or figure
        Returns the axes if one specified, else the figure.


Calculate model evaluation statistics

    These metrics are available for regression results:
      - Bias: The difference between the mean prediction and the mean
        label
      - RMSE: The root mean squared error of the predictions
      - RMSPE: the root mean squared proportionate error of the predictions
      - ubRMSE (Unbiased RMSE): The RMSE obtained if each prediction is
        adjusted by the Bias
      - R: The correlation coefficient
      - R2 (R-squared): The percent of variance explained

    These metrics are available for classification results:
        'Acc', 'F1Score', 'Kappa', 'AvgPrecision', 'LogLoss', 'AuROC'
      - Acc: Accuracy of the predictions
      - F1Score: The F1-score of the predictions
      - Kappa: the Cohen Kappa score of the predictions
      - AvgPrecision: The average precision obtained from the
        precision/recall curve
      - LogLoss: The log (cross-entropy) loss
      - AuROC: The area under the receiver operating curve

    For all results:
      - Count: The number of y (and yhat) values provided

    Parameters
    ----------
    y : array
        The sample labels.
    yhat : array
        The sample predictions.
    classify : bool
        If True: calculate binary classification metrics. y is a list
        of class labels (0/1 or False/True) and yhat is the predicted
        probability of the 1/True label
    metrics : list, optional
        The list of metrics required. The metric names should be a
        case-insensitive subset of the list above. If ``None``, the
        list ``['Count', 'RMSE', 'R2', 'Bias']`` is used for regression
        results and ``['Count', 'Acc', 'F1Score', 'Kappa']`` is used
        for classification results. If 'All', then all regression or
        classification metrics are calculated. The default is None.
    ybar : int or float
        The sample mean. If None, ybar = y.mean(). The default is None.
        Specifying ybar allows calculation of R2 for a sub-sample using
        the sample mean instead of the sub-sample mean. This allows
        comparisons between the R2 for different sub-samples to be
        compared, which can't be done is the sub-sample mean is used.
    threshold : float
        If ``classify``, then the probability threshold to use when
        assigning class labels. The default is 0.5.
    precision : int
        Round calculated statistics to this number of decimal places.

    Returns
    -------
    dict
        The calculated statistics. Keys are the metrics names in the
        same case as specified in the ``metrics`` parameter.


 Calculates statistics for each group of results

    Groups the samples and predictions by values of the grouping colum
    and calculates statistics separately for each group of results

    Parameters
    ----------
    samples : DataFrame
        A data frame of samples.
    predicts : list - of either DataFrames or lists of DataFrames
        Each dataframe contains a set of test results - the rows are
        the samples and the columns are each test run.
    grouping_column : str
        The samples column to use for grouping.
    target_column : str
        The target column in the samples.
    test_list : list
        A list of test names. Should be the same length as the total
        number of data frames in ``predicts``.
    keys : list, optional
        An optional list of values to select from the grouping column.
        If ``None``, all values in the grouping column are used. The
        default is None.
    measures : str or list of str, optional
        The statictics to return - currently should be a subset of the
        regression defaults. If ``None``, all default regression
        metrics are returned. The default is 'RMSE'.

    Returns
    -------
    results : DataFrame or dict of DataFrames
        If a single measure - a dataframe of the results.
        If a list of measures - a dictionary. Keys are the measures and
        values are a dataframe of the results for the measure.
        The columns of the data frames are the grouping column values
        and the rows are the test names


Calculates the model bias and variance.

    Parameters
    ----------
    model : string
        Specifies which derived model to use - e.g. 'base' for the base
        model, 'merge10' for the derived model formed by merging the
        last 10 checkpoints.
    tests : list
        A list of test names.
    num_runs : int
        The number of runs in each test.
    source : list
        A list of dataframes containing the predictions for each test.
        A flat list of the runs for all tests, in test then run order
        (i.e. all runs for test 1, then all runs for test 2, etc.).
    all_tests : bool, optional
        If ``True``, the bias and variance is calculated across all
        runs for all tests, as well as the individual tests. The
        default is False.

    Returns
    -------
    pd.DataFrame
        A dataframe containing the bias/variance results.


Gets data for samples from sites with historical data.

    Parameters
    ----------
    all_samples : DataFrame
        Data frame containing the sample data. Should have a row for
        all records in all_predictions, but may have extra rows.
    all_predictions : DataFrame
        Data frame containing the prediction data.
    site_column : Str, optional
        The name of the ``all_samples`` column containing the sampling
        site. The default is 'Site'
    year_column : Str, optional
        The name of the ``all_samples`` column containing the sampling
        year. The default is 'Sampling year'

    Returns
    -------
    yearly_samples : DataFrame
        DESCRIPTION.
    yearly_predicts : DataFrame
        DESCRIPTION.


Sorts a list of file names.

    Sorts a list of file names on the integer part of the name. To sort
    the file names, the file extension and the first part of the file
    name, up to and including the basename_prefix are removed. The
    function assumes the remaining part is an integer. The file names
    are then sorted based on these integer values. For example, calling
    `sort_file_list(['test2.dat', 'test10.dat', 'test1.dat'], 'test')`
    will return `['test1.dat', 'test2.dat', 'test10.dat']`

    Parameters
    ----------
    file_list : List of file names
        The list of file names to be sorted.
    basename_prefix : str
        The basename prefix to remove from the file names.

    Returns
    -------
    List
        The sorted list of file names.


Train the model.

    Calls the model train method, then creates the derived models.

    Parameters
    ----------
    model : Lfmc_Model
        The model - must be ready for training/fitting - i.e. built and
        compiled, with any callbacks defined.
    train : dict
        The training dataset.
    val : dict
        The validation dataset.

    The train and val dictionaries are all the same format. They have
    two items, ``X`` and ``y`` for the predictors and labels
    respectively. ``X`` is also a dictionary with an item for each source.

    Returns
    -------
    None.


Evaluates a model.

    Evaluates a model using the ``data`` dataset. If the ``which``
    parameter is specified, only that child model is run, otherwise
    all child models are run. The model predictions and prediction
    statistics are stored as model attributes ``<test_name>_predicts``
    and ``<test_name>_stats``. If this is not a fold model, the stats
    and (if save_preds) predictions are saved to the model directory.

    Parameters
    ----------
    model : Lfmc_Model
        The model to be evaluated. It should be trained/fitted.
    data : dict
        The evaluation data. It should have two items, ``X`` and ``y``
        for the predictors and labels respectively. ``X`` is also a
        dictionary with an item for each source.
    which : str, optional
        The child model to run. If ``None``, all child models are run.
        The default is None.
    test_name : str, optional
        The name of the test. Prefixed to the prediction and statistics
        file names. The default is None, meaning the default file names
        are used.
    train_stats : bool, optional
        Indicates if the model training time and counts should be
        stored with the prediction statistics. The default is False.
    save_preds : bool, optional
        Indicates if the predictions should be saved. If ``False`` only
        the prediction statistics are saved. The default is True.

    Returns
    -------
    None.


Trains and evaluates the model.

    Train the model, evaluate it using the test data, then evaluate
    using the training data, so the model can be checked for
    overfitting.

    Parameters
    ----------
    model : Lfmc_Model
        The model - must be ready for training/fitting - i.e. built and
        compiled, with any callbacks defined.
    train : dict
        The training dataset.
    val : dict
        The validation dataset.
    test : dict
        The test dataset.

    The train, val and test dictionaries are all the same format. They
    have two items, ``X`` and ``y`` for the predictors and labels
    respectively. ``X`` is also a dictionary with an item for each source.

    Returns
    -------
    None.


        If "verbose", prints a summary of parameters for the user's convenience.

        :return:
            (string) formatted display of all parameters used in KinMS() initialisation


        Creates a psf with which one can convolve their cube based on the beam provided.

        :param xpixels:
                (float or int) Number of pixels in the x-axis
        :param ypixels:
                (float or int) Number of pixels in the y-axis
        :param beamSize:
                (float or int, or list or array of float or int) Scalar or three element list for size of convolving beam (in arcseconds). If a scalar then beam is
                assumed to be circular. If a list/array of length two. these are the sizes of the major and minor axes,
                and the position angle is assumed to be 0. If a list/array of length 3, the first 2 elements are the
                major and minor beam sizes, and the last the position angle (i.e. [bmaj, bmin, bpa]).
        :param cellSize:
                (float or int) Pixel size required (arcsec/pixel)
        :param cent:
            (array or list of float or int) Optional, default value is [xpixels / 2, ypixels / 2].
                Central location of the beam in units of pixels.
        :return psf or trimmed_psf:
                (float array) psf required for convlution in self.model_cube(). trimmed_psf returned if self.huge_beam=False,
                otherwise default return is the untrimmed psf.


        Samples cloudlets from radial profiles provided given that inClouds is not provided in the __init__.

        :param sbRad:
                (numpy array) Radius vector for surface brightness profile (units of arcseconds).
        :param sbProf:
                (numpy array) Surface brightness profile (arbitrarily scaled) as a function of 'sbrad'.
        :param nSamps:
                (int) Number of cloudlets to use to create the model. Large numbers will reduce numerical noise (especially
                in large cubes), at the cost of increasing runtime.
        :param diskThick:
                (numpy array) The disc scaleheight in arcseconds. If a single value then this is used at all radii. If an array/list
                then it should have the same length as 'sbrad', and will be the disc thickness as a function of that.
        :return inClouds:
            (numpy array) 3 dimensional array of cloudlet positions within the cube initialised by KinMS().


        Creates an array of line-of-sight velocities, accounting for velocity dispersion and projection.

        :param velRad:
            (numpy array) Radius vector for velocity profile (units of arcseconds).
        :param posAng_rad:
            (float or int, or array of float or int) Optional, default value is None.
            Position angle (PA) of the disc (a PA of zero means that the redshifted part of the cube is aligned
            with the positive y-axis). If single valued then the disc major axis is straight. If an array is passed
            then it should describe how the position angle changes as a function of `velrad` (so this can be used
            to create position angle warps).
        :param inc_rad:
            (float or int, or array of float or int) Optional, default value is None.
            Inclination angle of the gas disc on the sky (degrees). Can input a constant or a vector, giving the
            inclination as a function of the radius vector 'velrad' (in order to model warps etc).
        :return los_vel:
            (numpy array) Line-of-sight velocities for projected particles positioned by velRad.


        Outputs a .fits file containing the datacube and relevant header information.

        :param cube:
            (numpy array) 3 dimensional spectral cube required for saving to .fits file
        :param cent:
            (numpy array of intigers) Location of the central x and y positions (in units of pixels),
            and index of the central velocity channel.
        :return:
            None


       Calculates an array of line-of-sight velocity alterations, accounting for the effects
       of the mass of gas in the disk (in this case assuming spherical symmetry).

       :param x_pos:
           (numpy array) X position of each cloudlet. Units of arcseconds.
       :param y_pos:
           (numpy array) Y position of each cloudlet. Units of arcseconds.
       :param z_pos:
           (numpy array) Z position of each cloudlet. Units of arcseconds.
       :param massDist:
           (numpy array) Array of ([gasmass,distance]) - total gas mass in solar masses, total distance in Mpc.
       :param velRad:
           (numpy array) Radius vector for cloudlets (in units of pixels).
       :return add_to_circ_vel:
           (numpy array) Additions to the circular velocity due to the internal mass of the gas, in units of km/s.


        A helper function for generating cloudlets by running kinms_sampleFromArbDist_oneSided. Raises
        a KinMSError if generate_cloudlets is called but sbRad and sbProf are not set.

        :return:
            None


        If the array provided has a length > 1, create a warp. If it's a single value, create a flat profile.

        :param array:
            (ndarray) array containing the radial profile
        :param r_flat:
            (ndarray) Radius of each cloudlet from the kinematic centre in the plane of the disc (units of pixels)
        :return:
            ndarray with the radial profile of the disc


        Apply the projection as a result of inclination to the cloudlets.

        :param ang:
            (float) inclination angle (in degrees)
        :param x1:
            (ndarray) x-positions of the cloudlets
        :param y1:
            (ndarray) y-positions of the cloudlets
        :param z1:
            (ndarray) z-positions of the cloudlets
        :return:
            x-, y-, and z-positions of the projected cloudlets


        Apply the projection as a result of the position angle to the cloudlets.

        :param ang:
            (float) position angle (in degrees)
        :param x2:
            (ndarray) x-positions of the cloudlets
        :param y2:
            (ndarray) y-positions of the cloudlets
        :param z2:
            (ndarray) z-positions of the cloudlets
        :return:
            x-, y-, and z-positions of the projected cloudlets


        Returns the clouds that lie inside the cube.

        :param los_vel:
            (ndarray) contains the line of sight velocities of each cloudlet, in km/s.
        :param cent:
            (ndarray of length 2) contains the x and y coordinates of the centre of the object within the cube
        :param x2:
            (ndarray) x-positions of the cloudlets within the cube
        :param y2:
            (ndarray) y-positions of the cloudlets within the cube
        :return:
            arrays with the positions of the cloudlets within the cube, and the indices of these positions


        bincount is subtantially faster than histogramdd unless you need weights

        ; param vals:
            (ndarray) contains the x-, y-, and v-positions of the cloudslets in the cube in units of pixels
        ; param bins
            (ndarray) the number of pixels in x, y and v
        ; return:
            (ndarray) 3D datacube (unnormalised)


        If there are clouds to use, and we know the flux of each cloud, add them to the cube.
        If not, bin each position to get a relative flux.

        :param clouds2do:
            (ndarray) contains the x-, y-, and v-positions of the cloudslets in the cube
        :param subs:
            (ndarray) the cloudlets to add to the cube
        :return:
            spectral cube with fluxes added to the cloudlets


        Normalise cube by the known integrated flux.

        :param cube:
            (3D array) unnormalised spectral cube
        :param psf:
            (2D array) psf of the mock observations, to convolve the cube with


        Do the actual modelling of the spectral cube

        :param inc:
            (float or int, or list or array of float or int) Inclination angle of the gas disc on the sky (degrees). Can input a constant or a vector, giving the
            inclination as a function of the radius vector 'velrad' (in order to model warps etc).
        :param posAng:
            (float or int, or list or array of float or int) Position angle (PA) of the disc (a PA of zero means that the redshifted part of the cube is aligned
            with the positive y-axis). If single valued then the disc major axis is straight. If an array is passed
            then it should describe how the position angle changes as a function of `velrad` (so this can be used
            to create position angle warps).
        :param gasSigma:
            (float or int, or array or list of float or int) Optional, default is value 0.
            Velocity dispersion of the gas (units of km/s). If single valued then the velocity dispersion is
            constant throughout the disc. If an array/list is passed then it should describe how the velocity
            dispersion changes as a function of 'velrad'.
        :param diskThick:
            (float or int, or array or list of float or int) Optional, default value is 0.
            The disc scaleheight in arcseconds. If a single value then this is used at all radii. If an array/list
            then it should have the same length as 'sbrad', and will be the disc thickness as a function of that.
        :param flux_clouds:
            (array or list of float or int) Optional, default value is 0.
            This vector can be used to supply the flux of each point in 'inclouds'. If used alone then total flux
            in the model is equal to total(flux_inclouds). If 'intflux' used then this vector denotes the relative
            brightness of the points in 'inclouds'.
        :param sbProf:
            (array or list of float or int) Optional, default value is [].
            Surface brightness profile (arbitrarily scaled) as a function of 'sbrad'.
        :param sbRad:
            (array or list of float or int) Optional, default value is [].
            Radius vector for surface brightness profile (units of arcseconds).
        :param velRad:
            (array or list of float or int) Optional, defaults to 'sbRad'.
            Radius vector for velocity profile (units of arcseconds).
        :param velProf:
            (array or list of float or int) Optional, default value is [].
            Circular velocity profile (in km/s) as a function of 'velrad'.
        :param inClouds:
            (array or list of float or int) Optional, default value is [].
            If your required gas distribution is not symmetric, you may input vectors containing the position of the
            clouds you wish to simulate. This 3-vector should contain the x, y and z positions, in units of
            arcseconds from the phase centre. If this variable is used, then 'diskthick', 'sbrad' and 'sbprof' are
            ignored. Example: inclouds = [[0,0,0], [10,-10,2], ..., [xpos, ypos, zpos]].
        :param vLOS_clouds:
            (array or list of float or int) Optional, default value is [].
            This vector should contain the LOS velocity for each point defined in 'inclouds', in units of km/s. If
            not supplied then 'inclouds' is assumed to be the -face on- distribution and that 'velprof' or 'velrad'
            should be used, and the distribution projected. If this variable is used then 'gassigma' and 'inc'
            are ignored.
        :param massDist:
            (list of float) Optional, default value is [].
            List of [gasmass, distance] - total gas mass in solar masses, total distance in Mpc.
        :param intFlux:
            (float) Optional, default value is 1.
            Total integrated flux you want the output gas to have. (In units of BUNIT - default Jy/km/s).
        :param phaseCent:
            (list or array of float or int of length 2) Optional, default value is [0, 0].
            Specifies the morphological centre of the disc structure you create with respect to the central pixel
            of the generated cube.
        :param vOffset:
            (float or int) Optional, default value is 0.
            Offset from the centre of the velocity axis in km/s.
        :param vPosAng:
            (float or int, or array or list of float or int) Optional, default value is 0.
            Kinematic position angle of the disc, using the usual astronomical convention. If single valued then the
            disc kinematic major axis is straight. If an array is passed then it should describe how the kinematic
            position angle changes as a function of 'velrad'. Used if the kinematic and morphological position
            angles are not the same.
        :param vPhaseCent:
            (list of float or int of length 2) Optional, default value is [0, 0].
            Kinematic centre of the rotation in the x-y plane. Units of pixels. Used if the kinematic and
            morphological centres are not the same.
        :param restFreq:
            (float) Optional, default value =  230.542e9 (12CO(2-1)).
            Rest frequency of spectral line of choice (in Hz). Only matters if you are outputting a FITS file.
        ;param radial_motion_func:
            (callable) Optional, default is to not use.
            If a method of kinms.radial_motion is supplied then will include the effect of radial (non-circular) motions using
            that formalism. Current options include pure radial flows, along with lopsided and bisymmetric (bar-type) flows.
        :param returnClouds:
            (bool) Optional, default value is False.
            If set True then KinMS returns the created 'inclouds' and 'vlos_clouds' in addition to the cube.
        ;param toplot:
            (bool) Optional, default value is False.
            Makes a basic plot of your model to screen
        :param vSys:
            (float) Optional, default value is zero.
            Systemic velocity (km/s).
        ;param bunit:
            (string) Optional, default is Jy/beam.
            Unit for the output fits file
        :param seed:
            (array or list of float or int) Optional, default value is [100, 101, 102, 103].
            List of length 4 containing the seeds for random number generation.
        :param ra:
            (float) Optional, default value is None.
            RA to use in the header of the output cube (in degrees).
        :param dec:
            (float) Optional, default value is None.
            Dec to use in the header of the output cube (in degrees).
        :param fileName:
            (str) Optional, default value is ''.
            If you wish to save the resulting model to a fits file, set this variable. The output filename will
            be 'filename'_simcube.fits
        :return:
            ~~the cube~~


        Samples cloudlets from radial profiles provided given that inClouds is not provided in the __init__.

        :param sbRad:
                (numpy array) Radius vector for surface brightness profile (units of arcseconds).
        :param sbProf:
                (numpy array) Surface brightness profile (arbitrarily scaled) as a function of 'sbrad'.
        :param nSamps:
                (int) Number of cloudlets to use to create the model. Large numbers will reduce numerical noise (especially
                in large cubes), at the cost of increasing runtime.
        :param diskThick:
                (numpy array) The disc scaleheight in arcseconds. If a single value then this is used at all radii. If an array/list
                then it should have the same length as 'sbrad', and will be the disc thickness as a function of that.
        :param fixSeed:
                (bool) Whether to use a fixed (or random) seed (list of four integers).
        :return inClouds:
            (numpy array) 3 dimensional array of cloudlet positions within the cube initialised by KinMS().


        Returns the clouds that lie inside the cube.

        :param los_vel:
            (ndarray) contains the line of sight velocities of each cloudlet, in km/s.
        :param cent:
            (ndarray of length 2) contains the x and y coordinates of the centre of the object within the cube
        :param x2:
            (ndarray) x-positions of the cloudlets within the cube
        :param y2:
            (ndarray) y-positions of the cloudlets within the cube
        :param x_size:
            (int) size of the cube in the x-direction
        :param y_size:
            (int) size of the cube in the y-direction
        :param v_size:
            (int) size of the cube in the z-direction
        :return:
            arrays with the positions of the cloudlets within the cube, and the indices of these positions


        If there are clouds to use, and we know the flux of each cloud, add them to the cube.
        If not, bin each position to get a relative flux.

        :param clouds2do:
            (ndarray) contains the x-, y-, and v-positions of the cloudslets in the cube
        :param subs:
            (ndarray) the indices of the cloudlets in the cube
        :param x_size:
            (int) size of the cube in the x-direction
        :param y_size:
            (int) size of the cube in the y-direction
        :param v_size:
            (int) size of the cube in the v-direction
        :return:
            spectral cube with fluxes added to the cloudlets


        Do the actual modelling of the spectral cube

        :return:
            ~~the cube~~


  Host: 8.8.8.8 (google-public-dns-a.google.com)
  OpenPort: 53/tcp
  Service: domain (DNS/TCP)


    A test procedure to demonstrate the KinMS code, and check if it works on your system. This procedure demonstrates how
    to create a simulation of an exponential disk of molecular gas. The user can input values for the scalerad and inc
    variables, and the procedure will the create the simulation and display it to screen.
    :param scalerad: Scale radius for the exponential disk (in arcseconds)
    :param inc: Inclination to project the disk (in degrees)
    :return: N/A


    A test procedure to demonstrate the KinMS code, and check if it works on your system. This procedure demonstrates
    how to create a simulation of an exponential disk of molecular gas, including the effect of the potential of the gas
    on its own rotation. The user can input values for the scalerad and inc variables, and the procedure will the create
    the simulation and display it to screen.
    :param scalerad: Scale radius for the exponential disk (in arcseconds)
    :param inc: Inclination to project the disk (in degrees)
    :param gasmass: Total mass of the gas (in solar masses)
    :param distance: Distance to the galaxy (in Mpc)
    :return: N/A


    A test procedure to demonstrate the KinMS code, and check if it works on your system. This procedure makes a basic
    simulation of the molecular gas ring in NGC4324, and plots the simulation moment zero, one and PVD against the
    observed ones from the CARMA observations of Alatalo et al., 2012.
    :return: N/A


    A test procedure to demonstrate the KinMS code, and check if it works on your system. This procedure demonstrates
    how to use the "inclouds" parameter set to create simulations, in this case of a very unrealistic object. Once you
    understand this example then see the "infits" and "inclouds spiral" test for more realistic examples.
    :return: N/A


    A test procedure to demonstrate the KinMS code, and check if it works on your system. This procedure demonstrates
    how to use the "inclouds" parameter set to create simulations, in this case of molecular gas in a two armed spiral
    pattern. Any default parameters can be changed by specifying them at the command line (see KinMS.pro or the full
    details of all the available parameters).
    :return: N/A


    A test procedure to demonstrate the KinMS code, and check if it works on your system. This procedure demonstrates
    how to use an input FITS image to create a simulation of what the molecular gas may look like, with a given
    instrument (in this case CARMA). We use a GALEX (Morrissey et al., 2007) FUV image of NGC1437A, and scale it
    assuming the FUV emission comes from star-formation and thus molecular gas, and that the galaxy has a total
    integrated CO flux of 30 Jy km/s. We use the FITS image to set the surface-brightness, and impose a flat velocity
    gradient.
    :return: N/A


    A test procedure to demonstrate the KinMS code, and check if it works on your system. This procedure demonstrates
    how to create a simulation of an exponential disk of molecular gas with a velocity dispersion that varies with
    radius.
    :return: N/A


    A test procedure to demonstrate the KinMS code, and check if it works on your system. This procedure demonstrates
    how to create a simulation of an exponential disk of molecular gas with a thickness that varies with radius. Any
    default parameters can be changed by specifying them at the command line (see KinMS.pro for the full details of all
    the available parameters).
    :return: N/A


    A test procedure to demonstrate the KinMS code, and check if it works on your system. This procedure demonstrates
    how to create a simulation of a warped exponential disk of molecular gas.
    :return: N/A


    A test procedure to demonstrate the KinMS code, and check if it works on your system. This procedure demonstrates
    how to use the return clouds feature to recursivly build models - here a misaligned central and outer disc.
    :return: N/A


Check if query results are cached in the `temp_dir` directory.

    This function checks the existance of a JSON file with previously downloaded CMR query results in the `temp_dir` directory.

    Args:
        what (String): The type of data to find
        temp_dir (String): The directory containing cached query results
        params (String): Search criteria and parameter options

    Returns:
        boolean: True, if cached results were found


Retrieve cached query results from the `temp_dir` directory.

    This function retrieves previously downloaded CMR query results from a JSON file in the `temp_dir` directory.

    Args:
        what (String): The type of data to find
        temp_dir (String): The directory containing cached query results
        params (String): Search criteria and parameter options

    Returns:
        dict: JSON response content


Issue a search query to CMR and return a dict of the JSON response

    For documentation on what can be searched for on the CMR, refer to
    https://cmr.earthdata.nasa.gov/search/site/docs/search/api.html#collection-search-by-parameters
    (Parameters to this function correspond the chapter: "Find `what` by `params`").

    Results are stored in a JSON file in the `temp_dir` directory.
    Subsequent searches will return stored results, if available.

    Args:
        what (String): The type of data to find
        temp_dir (String): The directory containing cached query results
        params (String): Search criteria and parameter options

    Returns:
        dict: JSON response content


    Coadds objects specified in grouped_spats_list.

    Args:
        grouped_spats_list (List[dict]): a list of dicts mapping ``fnames`` to a list of filenames
            and ``spats`` to a list of integer spatial pixel positions.
        output_path (str): Coadded files will be written to ``output_path/Science``
        spectrograph (str): PypeIt name of spectrograph.
        user_config_lines (List[str]): User-provided PypeIt configuration.
        debug (bool, optional): Show debugging output/plots? Defaults to False.

    Returns:
        List[str]: List of filenames of coadded spectra.


    Coadds multiple 1D spectra of one object.

    Args:
        spec1dfiles (List[str]): List of spec1d files to coadd.
        objids (List[str]): List of object IDs to coadd.
        coaddfile (str): Outpath path and filename for coadd file.
        spectrograph (str): PypeIt name of spectrograph
        user_config_lines (List[str]): User-provided PypeIt configuration
        debug (bool, optional): Show debugging output/plots? Defaults to False.


    Groups coadds. Destroys input.

    Args:
        fname_to_spats (dict): maps filenames to a list of integer spatial
            positions

    Returns:
        List[Dict[str, Union[List[str], List[int]]]]: List of dicts mapping
        'fnames' to a list of filenames and 'spats' to a list of
        integer spatial positions.


    Attempts to parse input FITS file as ``OneSpec``, ``SpecObjs``, and
    DBSP_DRP final data output.

    Args:
        args (argparse.Namespace): input arguments

    Raises:
        LookupError: Raised if the input extension is not found in the input
            FITS file.
        IndexError: Raised if the input integer extension is outside of the
            valid range for indexing the input FITS file's extensions.


    Plots spectrum and error with sensible y-scale limits.

    Flux and error have units of :math:`10^{-17}\\mathrm{erg}/\\mathrm{s}/\\mathrm{cm}^2/\\overset{\\circ}{\\mathrm{A}}`.

    Args:
        wave (np.ndarray): Wavelengh array
        flux (np.ndarray): Flux array
        err (np.ndarray): Flux error array
        title (str): Plot title.


    Returns a tuple of sensible y-axis limits for plotting spectra.

    Usage:

    >>> plt.step(wave, flux)
    >>> plt.ylim(sensible_ylim(wave, flux))
    >>> plt.show()

    Args:
        wave (np.ndarray): wavelength array
        flux (np.ndarray): flux array

    Returns:
        Tuple[float, float]: bottom, top


    Splices red and blue spectra together.

    .. code-block::

        splicing_dict[target_name][position_along_slit][arm] = {
            'spec1ds': [(spec1d_filename_1, spatial_pixel_1), (spec1d_filename_2, spatial_pixel_2)],
            'coadd': coadd_filename
        }

    Args:
        splicing_dict (dict): Guides splicing.
        interpolate_gaps (bool): Interpolate across gaps in wavelength coverage?
        root (str): Path to raw data files, possibly including filename prefix.
        output_path (str): reduction output path


    Takes in red and blue spectra, adjusts overall flux level by red_mult, and
    combines overlap region.

    In the overlap region, the red spectrum is linearly interpolated to match
    the blue spectrum's wavelength spacing.

    Args:
        spec_b (fits.FITS_rec): blue spectrum
        spec_r (fits.FITS_rec): red spectrum.
        interpolate_gaps (bool): Interpolate across gaps in wavelength coverage?
        red_mult (float, optional): Factor multiplied into the red spectrum to
            match overal flux level with the blue spectrum. Defaults to 1.0.

    Raises:
        ValueError: Raised when both `spec_b` and `spec_r` are empty or None.

    Returns:
        Tuple[
            Tuple[np.ndarray, np.ndarray, np.ndarray],
            Tuple[np.ndarray, np.ndarray, np.ndarray],
            Tuple[np.ndarray, np.ndarray, np.ndarray]
        ]: (blue, red, combined) spectra, where each spectrum is a tuple of
            (wavelengths, flux, error)


    Linearly interpolate the data points (``xp``, ``yp``) with ``err_yp``
    uncertainty onto the grid ``x``.

    Args:
        x (np.ndarray): destination x data
        xp (np.ndarray): source x data
        yp (np.ndarray): source y data
        err_yp (np.ndarray): source y error data
        interpolate_gaps (bool): Interpolate across gaps in ``xp``?

    Returns:
        Tuple[np.ndarray, np.ndarray]: Interpolated y and error.


    Makes a sensitivity function.

    Args:
        standard_file (str): Filename of standard exposure.
        output_path (str): Partial path to standard exposure.
        spectrograph (str): PypeIt name of spectrograph.
        user_config_lines (List[str]): User-provided PypeIt configuration.
        debug (bool, optional): Show debugging output/plots? Defaults to False.

    Returns:
        str: Filename of sensitivity function file, or empty string on failure.


    Writes the fluxfile for fluxing.

    Uses archived sensitivity function if no standard was reduced.

    Args:
        spec1d_to_sensfunc (Dict[str,str]): maps spec1d filenames to the
            sensitivity function they should use
        output_path (str): reduction output path
        spectrograph (str): PypeIt name of spectrograph.
        user_config_lines (List[str]): User-provided PypeIt configuration.

    Returns:
        str: path to created fluxfile


    Flux spectra.

    Args:
        flux_file (str): Path to flux file
        output_path (str): reduction output path
        debug (bool, optional): Show debugging output/plots? Defaults to False.


    Verifies that RA/DEC keyword in ``header`` exists and can be parsed as an
    Angle. Optionally prompts user to correct the value.

    Args:
        fname (str): name of file being checked.
        is_ra (bool): True to check RA, False to check DEC.
        header (fits.Header): Header being checked.
        modified_str (str): String appended to the keyword's comment noting
            when the header card was modified.
        prompt_user (bool): Prompt user for RA/DEC if missing/bad?

    Returns:
        bool: True iff the RA/DEC value is good.


    Fixes FITS files found in ``path_prefix/*.fits`` or ``path_prefix*.fits``
    for common DBSP errors: empty file, extra bytes at the end, swapped
    GRATING/ANGLE values, missing/wrong RA/DEC/AIRMASS.

    Args:
        path_prefix (str): Where to look for FITS files.
        throw_errors (bool): Raise error when file cannot be automatically fixed?
        prompt_user (bool): Prompt user to fix missing/bad headers?

    Raises:
        ValueError: If ``throw_errors``, raised when ANGLE and GRATING both
            cannot be parsed as angles.

    Returns:
        List[str]: list of files with headers good enough to start reduction.


        Merges overlapping background areas.

        Call only after the user is done interacting with the GUI


        Delete a background area under (or nearby) the mouse

        The x-tolerance is hardcoded to 5 CCD pixels.


    Updates the ``airmass`` entry of ``row`` based on the ``ra`` ``dec`` and
    ``mjd`` entries.

    Args:
        row (astropy.table.Row): Row to be updated


    Opens header/metadata editing table GUI.

    Args:
        table (Table): table containing metadata
        del_files (List[str]): List of files to be deleted. Mutated!


Parses command line arguments

    Args:
        options (Optional[List[str]], optional): List of command line arguments.
            Defaults to sys.argv[1:].

    Returns:
        argparse.Namespace: Parsed arguments


    Allows for human correction of FITS headers and frame typing.

    Launches a GUI via dbsp_drp.table_edit, which handles saving updated FITS headers.
    table_edit depends on the current DBSP headers.

    Todo:
        Make table to FITS header mapping mutable

    Args:
        ps (PypeItSetup): PypeItSetup object created in dbsp_drp.reduction.setup


    Telluric correct one coadd file.

    Args:
        coadd (str): Coadd filename.
        output_path (str): reduction output path
        spectrograph (str): PypeIt name of spectrograph.
        user_config_lines (List[str]): User-provided PypeIt configuration
        debug (bool, optional): Show debugging output? Defaults to False.
        plot (bool, optional): Show debugging plots? Defaults to False.


    Opens a Matplotlib GUI for users to manually adjust the matching of overall
    red/blue flux levels, as well as interpolate over detector gaps.

    Args:
        hdul (fits.HDUList): HDUList read in from DBSP_DRP final data output file.
        fname (str): Output path and filename to write adjusted spectrum to.


    Displays a 2D spectrum on the input Matplotlib Axes, with slit edges and
    object traces and extraction FWHMs overplotted.

    Args:
        ax (plt.Axes): Axes object for plotting.
        spec (np.ndarray): 2D spectrum to plot.
        edges (Tuple[np.ndarray, np.ndarray]): Left and right slit edges,
            as arrays of the spatial pixel position of the edge for each pixel
            in the spectral direction.
        traces (List[np.ndarray]): Object traces as arrays of spatial pixel
            positions for each pixel in the spectral direction.
        fwhms (List[np.ndarray]): Extraction FWHMs for each object trace.


    Saves PNG images of each spectra at various steps in the reduction process.
    In one PNG, displayed from left to right are science image, sky model,
    sky-subtracted image, sky-subtraction residuals, sky- and
    object-subtraction residuals.

    Args:
        qa_dict (dict): Dict mapping target names to a dict containing lists of
            PNG filenames, airmasses, UTCs, and raw data filenames, from
            previous call of ``save_2dspecs``, or empty dict for first call.
        output_spec2ds (List[str]): List of spec2d filenames.
        output_path (str): reduction output path.
        spectrograph (str): PypeIt name of spectrograph.

    Returns:
        dict: updated ``qa_dict``


    Write Extraction.html page allowing for convenient viewing of PNGs saved in
    ``save_2dspecs``.

    Args:
        qa_dict (dict): Dict mapping target names to a dict containing lists of
            PNG filenames, airmasses, UTCs, and raw data filenames.
        output_path (str): reduction output path


    Grab user-provided PypeIt configuration for ``spectrograph`` from
    ``parameter_file``, which contains user-provided PypeIt configuration for
    both arms of DBSP.

    Args:
        parameter_file (str): User-provided file with their PypeIt config.
        spectrograph (str): PypeIt name of spectrograph.

    Returns:
        List[str]: User-provided PypeIt configuration for ``spectrograph``


    Searches table starting at row ``i`` in steps of ``step`` for frames within
    ``max_separation`` of ``row``. If an arc frame is found, the arc's ``calib``
    is assigned to ``row``.

    Args:
        row (Row): starting row
        i (int): index of starting row
        table (Table): table to search in and modify
        step (int): direction to look in. 1 for forwards, -1 for backwards
        max_sep (Angle): maximum separation allowed between frames pointing
            at the same object

    Returns:
        Tuple[int, int]: (distance to arc frame, calib ID) or (-1, -1) if
            no arc found.


    Writes the .pypeit file

    Args:
        context (Tuple[PypeItSetup, str]): PypeItSetup object, reduction output path
        cfg_split (str): [description]
        spectrograph (str): PypeIt name of spectrograph.
        user_config_lines (List[str]): User-provided PypeIt configuration.

    Raises:
        RuntimeError: Raised if files were not assigned a frame type.

    Returns:
        List[str]: List of PypeIt files generated.


    Runs the reduction

    Args:
        pypeit_file (str): Path to PypeIt reduction file.
        output_path (str): reduction output path
        reuse_masters (bool, optional): Reuse master calibration files (if they exist). Defaults to True.
        show (bool, optional): Show debugging/intermediate plots. Defaults to False.
        calib_only (bool, optional): Only perform calibration? Defaults to False.

    Returns:
        Tuple[set, set]: set of filenames of reduced (spec1d, spec2d) files.


    Removes ``SpecObj`` s with identical names from a FITS file containing a
    ``SpecObjs`` object, leaving one ``SpecObj`` with the duplicate name behind.

    Args:
        path (str): Path to FITS file.
        base_name (str, optional): Name of file used for logging. Defaults to "".


    Removes ``SpecObj`` s that are completely masked, i.e. no good pixels/data,
    from a FITS file containing a ``SpecObjs`` file.

    Args:
        path (str): Path to FITS file.
        base_name (str, optional): Name of file used for logging. Defaults to "".


    Verifies validity of spec1d files, fixes some, and generates and returns a
    list of pypeit files for targets that need to be rerun.

    Args:
        output_spec1ds (List[str]): List of spec1d filenames
        verification_counter (int): number of times verification has been run
        output_path (str): reduction output path

    Returns:
        List[str]: List of PypeIt files for targets that need to be rereduced.


    Runs the Manual Tracing GUI.

    Args:
        output_spec2ds (List[str]): List of spec2d files to inspect in GUI.
        output_path (str): reduction output path

    Returns:
        dict: Maps target names needing manual tracing to a dict specifying how
            they should be manually traced.


    Writes pypeit files based on the default pypeit file for this reduction,
    but with filtered targets and additional manual parameter lines.

    Args:
        old_pypeit_file (str): default pypeit file,
        targets_list (List[List[str]]): [[target1, target2], [target3, target4]]
            will result in 1 & 2 being reduced together and 3 & 4 being reduced
            together. The target names are blueNNNN-ZTF21abcd.
        manual_lines_fn (Callable[[List[str]], List[str]]): function mapping
            [target1, target2] to the cfg lines they need.
        needs_std_fn (Callable[[str], bool]): function mapping target1 -> bool.
            True if target1 needs a standard star to be reduced alongside it.

    Returns:
        List[str]: List of new PypeIt reduction files for the manually traced
            targets.


    wglwk

    Args:
        output_spec2ds (List[str]): List of spec2d files to potentially
            manually extract.
        pypeit_file (str): PypeIt reduction file for initial reduction.
        output_path (str): reduction output path.

    Returns:
        list: List of new PypeIt reduction files for the manually traced targets.


    Runs multiple reductions, returns the combined sets of output spec1d,
    spec2d files.

    Args:
        pypeit_files (List[str]): List of PypeIt reduction files to run.
        output_path (str): reduction output path

    Returns:
        Tuple[set, set]: set of filenames of reduced (spec1d, spec2d) files.


 Returns true if an input object is indexable.
    E.g. lists, dicts, or anything that can be addressed with obj[index]


Supresses write calls to stdout


Checks if an object is an instance of 'Star' from the Mors module.
    Returns False if it fails to import Mors.


    Rebins an array to a lower resolution by a factor,
    and returns the new array.
    Leftover values are added up on the last bin.

    Parameters
    ----------
    arr     : numpy.array, array of floats to rebin
    factor  : int, binning factor by which the number of elements are reduced.
    func    : callable (optional), function to combine a list of elements
            into a single element. The default behaviour is `sum`.

    Returns
    -------
    binned  : numpy.array, binned array


Initialises progress bar


Advances progress bar by one time step


Destroy progress bar object


        Wraps the function to integrate, which takes a planet state
        and advances it by one time step, into the format used
        by scipy.integrate.RK45, which expects a list of
        variables to integrate.


Advances the integration by one step and returns the new state


Converts an input stellar model into internal format.


    Given a model for the planet's core, which takes a mass to calculate
    its radius, it solves the model function to return the core mass
    from a given radius instead.
    For documentation, see `solve_envelope_model`.


    Given a model for the planet's envelope, which takes a mass fraction
    to calculate its thickness, it solves the model function
    to return the envelope mass fraction from a given thickness instead.
    It requires the core mass to be defined in the state.

    Parameters
    ----------
    env_model : Callable[[EvoState,dict],float]
        Function that takes the simulation state and extra arguments
        in a dict, and returns the envelope thickess.
    guess     : float
        Starting guess for the envelope mass fraction.
    state     : EvoState
        Simulation state - modified within the function.
    model_kw  : dict, optional
        Keyword parameters to pass to the envelope model.

    Returns
    -------
    solution : float
        Solved envelope mass fraction.
    success  : bool
        True if the solution converged, False otherwise.


    Solves for the structure of a planet given its mass and radius,
    as well as orbital and stellar parameters.
    Assumes the mass and radius are defined, but does not require
    core or envelope information.
    It can also accept variables with uncertainties and return planet parameters
    with calculated uncertainties as well, as long as the provided models
    can handle uncertainties.

    Parameters
    ----------
    state      : EvoState
        Simulation state - must have mass and radius defined.
        This instance is modified in the function.
    env_model  : Callable[[EvoState,dict], float]
        Function that calculates the envelope thickness
        from the simulation state. For documentation on
        signature, see `solve_envelope_model`.
    core_model : callable
        Function that calculates the core radius from the
        simulation state. For documentation on
        signature, see `solve_core_model`.
    fenv_guess : float, optional
        Initial guess for the envelope mass fraction.
    model_kw   : dict, optional
        Keyword arguments passed to envelope and core models.
    errors     : bool, optional
        If True, enables propagation of uncertainties.

    Returns
    -------
    state :EvoState
        Solved internal structure of the planet.
    success :bool
        Whether the solution converged.


Returns the difference in envelope thicknesses
        calculated using the core and envelope models


    Solves for the structure of a planet given its mass and radius,
    as well as orbital and stellar parameters,
    allowing the state to have quantities with uncertainties.
    Assumes the mass and radius are defined, but does not require
    core or envelope information.

    Parameters
    ----------
    planet     : Planet
        Planet instance with mass, radius, and separation defined,
        as well as core, envelope, and stellar models set.
    age        : float
        Age of the system in Myr.
    fenv_guess : float, optional
        Initial guess for the envelope mass fraction.
    model_kw   : dict, optional
        Keyword arguments passed to envelope and core models.
    error_kw  : dict, optional
        Keyword arguments to signal the core model to
        return quantities with uncertainties.

    Returns
    -------
    solved  :dict
        Solved internal structure of the planet.
    success :bool
        Whether the solution converged.


    Runs simulations of planets asynchronously.

    Parameters
    ----------
    planets: list[ph.Planet]
            Planets to evolve (with models set).
    evo_args: list[dict]
            Keyword arguments to pass to Planet.evolve on each case.
            Must have the same length as `planets`.
            See `Planet.evolve` for input parameters.

    Returns
    -------
    evos :list[pd.DataFrame],
        Results from the simulations of each planet
        in the same order in which they were passed as input.

    Examples
    --------
        # (1) Running multiple planets
        planets = [
            ph.Planet(mass=mass, radius=2, period=10).set_models(...)
            for mass in np.linspace(1, 5, num=5)
        ]
        evo_args = [{'start':10, 'end':1000} for i in range(len(planets))]
        evos = ph.planet.evolve_batch(planets = planets, evo_args = evo_args)

        # (2) Running the same planet forward and backwards in time
        age = 150 # Myr
        planet = ph.Planet(mass=7, radius=2, period=10).set_models(...)
        evo_args = [{'start':age, 'end':10}, {'start':age, 'end':1000}]
        past, future = ph.planet.evolve_batch(planets = [planet,planet], evo_args = evo_args)


Copies planet and stellar models from another Planet instance


        Solves for the internal structure of the planet
        assuming a core and envelope as distinct layers,
        using either the planet's mass and radius,
        or the core (mass or radius) and the envelope mass.

        Parameters
        ----------
            age      :float, Age in Myr of the planet, used to determine its core heat.
            errors   :bool, whether to solve the structre with uncertainties.
            error_kw :dict, arguments to pass to models to signal use of uncertainties.

        Returns
        -------
            state :EvoState, solved internal structure of the planet


        Returns the mass loss rate on the planet at a given age.

        Parameters
        ----------
            age  :float, planet age in Myr at which to compute the mass loss
            lx   :float (optional), X-ray luminosity of the host star. Overrides stellar model.
            lx   :float (optional), EUV luminosity of the host star. Overrides stellar model.
            errors   :bool, whether to compute the mass loss rate with uncertainties.
            error_kw :dict, arguments to pass to models to signal use of uncertainties.

        Returns
        -------
        mloss :float, mass loss rate on the planet in g/s


        Evolves the state of the planet in time.
        The planet parameters and models must have been set.

        Parameters
        ----------
        start, end  : float
            Initial and final age bounds for the simulation in Myr.
        method      : str | IntegratorBase, optional
            Integration method: "euler", or "rk45".
            'euler' : forward Euler method with a fixed step size.
            'rk45'  : 4th order Runge-Kutta method.
        step        : float
            Step size for the integration.
            For the euler method, thi is the fixed step size.
            For the RK45 method, this is the initial step size.
        progressbar : bool
            Displays a progress bar of the simulation using the `tqdm` module.
        min_fenv    : float
            Minimum envelope mass fraction under which a planet
            is considered to have no atmosphere.
        tqdm_position : int
            Position of the tqdm progressbar. Useful when running multiple progresbars.

        Returns
        -------
        pandas.DataFrame
            Dataframe with a column for each simulation parameter,
            and a row for the values at each simulation step.


 Internal helper to solve the planet's structure from its
        measured mass and radius alone


        Uses the envelope model to calculate the envelope thickness
        from the core mass and radius, and the envelope mass fraction.
        Parameters:
            state   :EvoState, simulation state


Computes a planet's state at a given age, based on a previous state.


Class method that initialises a state from a dictionary containing
        simulation parameters. Only a subset of parameters may be defined,
        the rest will hold `None` value.

        Parameters
        ----------
        fields  : dict[str,float]
            Parameters to initialise in the state.

        Returns
        -------
        state : EvoState
            Instance with specified parameters

        Raises
        ------
        AttributeError
            When attempting to defined a parameter
            that is not a member of the class.


        Returns a shallow copy of the state.
        Since all of the parameters are floats,
        a deep copy will yield the same result.


Returns the instance parameters as a dictionary
        The instance parameters cannot be modified through
        the returned dictionary, as it is a copy of the state.


        Returns True if all of the instance parameters are valid floats
        (neither None nor NaN) and False otherwise.


    Wraps a function `fn` that takes arbitrary keyword parameters
    so that it takes two arguments instead: an EvoState and
    extra arguments as a dictionary.
    The wrapped function retains the internal dunder name (__name__) and
    docs from the original function.

    This is useful to make model functions compatible with the evolution code,
    which passes the current simulation state together with user-defined
    keyword arguments to the models.

    Parameters
    ----------
    fn  : Callable[Any, Any]
        Function to wrap. Must allow for an arbitrary number of
        keyword arguments that may map to state parameters
        and/or model keyword arguments.
        Example:
        ```
        def my_model(mass :float, **kwargs) -> float:
            pass
        ```

    Returns
    -------
    wrapped_fn : Callable[[EvoState,dict], Any]
        Wrapped function.

    Examples
    --------
    ```
    def rocky_radius(mass :float, **kw) -> float:
        return mass**(1/3)

    rocky_fn = wrap_callback(rocky_radius)
    rcore = rocky_fn(state, model_args)
    ```


Application of Kepler's third law.
    For a system of two bodies orbiting each other, it returns either
    the orbital period (if separation specified), or orbital separation
    (if period specified) of their common orbit.
    The mass of the two bodies can be specified, but only the
    mass of the larger one is required, which is an acceptable approximation
    when the difference in mass is large.
    If both period and separation are specified, the period takes precedence.

    Parameters
    ----------
    big_mass    : float
        Mass of the more massive body in units of solar masses.
    small_mass  : float, optional
        Mass of the lighter body in units of Earth masses (different unit!)
    period      : float, optional
        Orbital period in units of days.
    sep         : float, optional
        Orbital separation in AU

    Returns
    -------
    period_or_sep : float
        Period if separation specified, or separation if period specified.

    Raises
    ------
    ValueError
        If neither period or separation are defined.


    Calculate equilibrium temperature of a planet.

    Parameters
    ----------
    fbol    : float, bolometric flux in erg/s/cm^2
    albedo  : float, Bond albedo, fraction of incident power reflected back into space

    Returns
    -------
    t_eq    : float, equilibrium temperature in K


Calculates planet density in g/cm^3

    Parameters
    ----------
    mass    : float, planet's mass in Earth masses
    radius  : float, planet's mass in Earth radii

    Returns
    -------
    density : float, in units of g/cm^3


 Calculates the maximum rotation period of a star
    from its rotational velocity at line of sight.

    Parameters
    ----------
    vsini   : float, rotational velocity times the sine
            of the inclination in km/s.
    rstar   : float, stellar radius in Solar radii.

    Returns
    -------
    prot    : float, rotation period in days


    Estimates the Rossby number of a star given its V-K color index and its rotation period in days.
    It returns the Rossby number and the turnover time in days.
    The empirical relation comes from the Wright et al 2011 paper:
            (https://ui.adsabs.harvard.edu/abs/2011ApJ...743...48W/abstract)

    Parameters
    ----------
    vkcolor  : float, V-K color index
    prot     : float, rotation period in days
    full_out : bool (optional), if True, returns both rossby number
                and turnover time
    safe     : bool (optional), enforce model limits by raising ValueError

    Returns:
    --------
    rossby  : float, rossby number


    Estimates Rossby number using stellar mass and rotation period.

    Parameters
    ----------
    mass    : float, stellar mass in Solar masses
    prot    : float, stellar spin period in days
    full_out : bool (optional), if True, returns both rossby number
            and turnover time
    safe    : float (optional), enforce model limits by raising ValueError

    Returns
    -------
    rossby  : float, rossby number


 Returns the jeans escape parameter, which quantifies
    how well bound an atmosphere is to a planet

    Parameters
    ----------
    mass    : float, planet mass in Earth masses.
    radius  : float, planet radius in Earth radii.
    lbol    : float, host star bolometric luminosity in erg/s.
    sep     : float, orbital distance of the planet in AU.

    Returns
    -------
    jeans   : float, jeans escape parameter (dimensionless)


    Returns the location of the radius valley for a given orbital period.
    Following the definition of radius valley by Van Eylen et al. (2018).

    Parameters
    ----------
    period  : float, orbital period in days.

    Returns
    -------
    radius  : float, planet radius in Earth radii at which the radius valley occurs.


    Returns the radii corresponding to the lower and upper
    edges of the Neptune desert, following Mazeh et al. (2016).

    Parameters
    ----------
    period  : float, orbital period

    Returns
    (lower,upper)   : [float,2], Radii of the lower and upper
                    edges of the Neptune desert.


    Returns the envelope thickness in Earth radii using the model
    by Lopez & Fortney (2014).
    Required parameters must be defined in the state,
    optional parameters can be provided through model keywords.

    Parameters
    ----------
    mass   : float, planet mass in Earth masses
    fenv   : float, envelope mass fraction = (mass-mcore)/mcore
    lbol   : float, bolometric luminosity of the hos star (erg/s/cm^2)
    sep    : float, orbital separation of the planet in AU
    age    : float, system age in Myr
    l14_opaque : bool (optional), enables enhanced opacity

    Returns
    -------
    renv   : float, envelope thickness in Earth radii


    Returns the envelope thickness in Earth radii using the
    analytical approximation to the MESA model by Chen & Rogers (2016).
    Required parameters must be defined in the state,
    optional parameters can be provided through model keywords.

    Parameters
    ----------
    mass   : float, planet mass in Earth masses
    fenv   : float, envelope mass fraction = (mass-mcore)/mcore
    lbol   : float, bolometric luminosity of the hos star (erg/s/cm^2)
    sep    : float, orbital separation of the planet in AU
    age    : float, system age in Myr
    cr16_water : bool (optional), use coefficients for a water core.

    Returns
    -------
    renv   : float, envelope thickness in Earth radii


    Returns the envelope thickness in Earth radii using the
    analytical model by Owen & Wu (2017).
    Required parameters must be defined in the state,
    optional parameters can be provided through model keywords.

    Parameters
    ----------
    mass   : float, planet mass in Earth masses
    fenv   : float, envelope mass fraction = (mass-mcore)/mcore
    lbol   : float, bolometric luminosity of the hos star (erg/s/cm^2)
    sep    : float, orbital separation of the planet in AU
    age    : float, system age in Myr
    rcore  : float, core radius in Earth radii

    Returns
    -------
    renv   : float, envelope thickness in Earth radii


    Calculates modified Bondi radius, the height at which the escape velocity and the sound speed are equal.

    Parameters
    ----------
    mcore :float, core mass (Earth masses)
    teq   :float, equilibrium temperature (Kelvin)

    Returns
    -------
    rbondi :float, Bondi radius (Earth radii)


    Calculates the density at the radiative-convective boundary of the atmosphere.

    Parameters
    ----------
    mcore  :float, core mass
    rcore  :float, core radius
    fenv   :float, envelope mass fraction
    renv   :float, envelope thickness
    rbondi :float, Bondi radius

    Returns
    -------
    dens_rcb :float, density at RCB


    Calculates the speed of sound in an atmosphere

    Parameters
    ----------
    teq :float, equilibrium temperature

    Returns
    -------
    vsound :float, sound speed


    Calculates the radius at which the planetary outflow becomes supersonic

    Parameters
    ----------
    mass :float, planet mass
    teq  :float, equilibrium temperature

    Returns
    -------
    rsonic :float, sonic point radius


    Calculates the opacity of the atmosphere from its density
    at the radiative-convective boundary.

    Parameters
    ----------
    dens_rcb : float, density at RCB.
    zstar    : float (optional), metallicity

    Returns
    -------
    opacity : float


    Calculates the thermal luminosity of a planet.

    Parameters
    ----------
    teq      :float, equilibrium temperature
    rbondi   :float, Bondi radius
    dens_rcb :float, density at RCB

    Returns
    -------
    planet_lum :float


Calculates the energy-limited mass loss rate on a planet powered by its thermal energy


Calculates the Bondi-limited mass loss rate on a planet


    Returns the mass loss rate predicted by the core-pwoered model.

    Parameters
    ----------
    mass   :float, planet mass
    radius :float, planet radius
    lbol   :float, bolometric luminosity of the host star
    sep    :float, orbital separation
    mcore  :float, core mass
    rcore  :float, core radius
    fenv   :float, envelope mass fraction, defined as Menv/Mcore
    renv   :float, envelope thickness

    Returns
    -------
    mloss   :float, mass loss rate in grams per second.


    Returns the mass loss rate from a planet using the
    energy-limited model.
    Required parameters must be defined in the state,
    optional parameters can be provided through model keywords.

    Parameters
    ----------
    lx      : float, X-ray luminosity of the star in erg/s
    leuv    : float, X-ray luminosity of the star in erg/s
    mstar   : float, Host star mass in Solar masses
    mass    : float, planet mass in Earth masses
    radius  : float, planet radius in Earth radii
    sep     : float, orbital separation of the planet in AU
    el_eff  : float|callable (optional),
            evaporation efficiency. It may also be a function
            that calculates and returns the efficiency, based
            on the simulation state, with signature
            identical to this function.
    el_rxuv : float|callable (optional),
            ratio of XUV to optical planet radius.
            It may also be a function that calculates
            this parameter. See the description for `el_eff`.

    Returns
    -------
    mloss  : float, mass loss rate in g/s


    Returns the ratio of XUV to optical radius for a planet's envelope
    using the model of Salz et al. (2016).
    Required parameters must be defined in the state,
    optional parameters can be provided through model keywords.

    Parameters
    ----------
    mass    : float, planet mass in Earth masses
    radius  : float, planet radius in Earth radii
    lx      : float, X-ray luminosity of the star in erg/s
    leuv    : float, X-ray luminosity of the star in erg/s
    sep     : float, orbital separation of the planet in AU


    Returns the evaporation efficiency on a planet's envelope
    using the model of Salz et al. (2016).
    Required parameters must be defined in the state,
    optional parameters can be provided through model keywords.

    Parameters
    ----------
    mass    : float, planet mass in Earth masses
    radius  : float, planet radius in Earth radii


    Returns the mass loss rate from a planet using the
    energy-limited model with the approximation by
    Salz et al. (2016) for the XUV radius.

    Parameters
    ----------
    lx      : float, X-ray luminosity of the star in erg/s
    leuv    : float, X-ray luminosity of the star in erg/s
    mstar   : float, Host star mass in Solar masses
    mass    : float, planet mass in Earth masses
    radius  : float, planet radius in Earth radii
    sep     : float, orbital separation of the planet in AU

    Returns
    -------
    mloss  : float, mass loss rate in g/s


 Calculates the mass loss rate using the hydrodynamic models
    and interpolator by Kubyshkina et al (2018).


    Calculates the atmospheric mass loss rate driven by photoevaporation
    This is based on the hydro-based expression by Kubyshkina et al (2018).

    Parameters
    ----------
        mass   : float, planet mass in Earth masses
        radius : float, planet radius in Earth radii
        lx      : float, X-ray luminosity of the star in erg/s
        leuv    : float, X-ray luminosity of the star in erg/s
        lbol   : float, bolometric luminosity in erg/s
        sep    : float, planet-star separation in AU

    Returns
    -------
        mloss  : float, mass loss rate in grams/sec


	Calculates the EUV luminosity from the X-rays
	using the empirical relation by King et al. (2018).
	Source: https://ui.adsabs.harvard.edu/abs/2018MNRAS.478.1193K/abstract

	Parameters
	----------
	lx	  : float, X-ray luminosity of the star in erg/s
	rstar   : float, radius of the star in solar radii
	energy  : str, input energy range of the X-rays in keV.
			The allowed ranges are: 0.1-2.4, 0.124-2.48, 0.15-2.4,
			0.2-2.4, and 0.243-2.4 keV.

	Returns
	-------
	leuv	: float, the EUV luminosity of the star with energy between
			from 0.0136 keV and the lower range of the input X-rays in erg/s.


Saturated power law for X-ray evolution


	Simple model for the X-ray evolution of a star,
	with a saturated phase with Lx/Lbol = `rx_sat` that lasts until age `t_sat`,
	and then decays as a power law with exponent `expn`.
	Returns a function that, when called with an age, returns the X-ray luminosity at that age.

	Parameters
	----------
		lbol    :float, stellar bolometric luminosity in erg/s
		rx_sat  :float, saturated x-ray activity level (Lx/Lbol)
		t_sat   :float, age at which star becomes unsaturated in Myr
		expn    :float, power law index for unsaturated phase

	Returns
	-------
		lx_evo  :callable, function that that returns the X-ray luminosity at a given age.

	Example
	-------
		lx_evo = ph.models.xray_evo_powerlaw(mstar=1.0, lbol=1e33, rx_sat=1e-3, t_sat=100, exp=-2)
		lx = lx_evo(age = 100)


	X-ray evolution models by Jackson et al. (2012).

	Parameters
	----------
		lbol     :float, bolometric luminosity of the star in erg/s.
		bv_color :float, B-V colour of the star

	Returns
	-------
		lx_evo   : callable that returns X-ray luminosity (erg/s) at a given age (Myr).

	Example
	-------
		lx_evo = xray_evo_jackson12(lbol = 3.8e33, bv_color = 0.71) # Sun-like star
		lx = lx_evo(age = 100) # X-ray luminosity at 100 Myr


	Estimates the Rossby number of a star in days.
	Requires its rotation period and either its V-K colour or its mass.
	The empirical relation comes from the Wright et al 2011 paper:
			(https://ui.adsabs.harvard.edu/abs/2011ApJ...743...48W/abstract)

	Parameters
	----------
	prot	 : float, rotation period in days
	mstar	: float (optional), stellar mass in solar masses
	vk	   : float (optional), V-K color index

	Returns:
	--------
	rossby  : float, rossby number


	Converts rotation period to X-ray activity
	using the rotation-activity relation by Wright et al. 2011
	for convective-radiative stars (FGK and early M dwarfs).

	Parameters
	----------
	prot	:float, Spin period of the star in days
	mstar   :float, Mass of the star in solar masses

	Returns
	-------
	xray_activity :float, X-ray activity (Lx/Lbol)


	Converts rotation period to X-ray activity
	using the rotation-activity relation by Wright et al. 2018
	for fully convective stars (late M dwarfs).

	Parameters
	----------
	prot	:float, Spin period of the star in days
	mstar   :float, Mass of the star in solar masses

	Returns
	-------
	xray_activity :float, X-ray activity (Lx/Lbol)


	Converts rotation period to X-ray activity
	using the rotation-activity relation by Johnstone et al. 2021
	for main sequence stars.

	Note: Johnstone+21 use the period-rossby number relation
	from Spada et al. (2013), which is very similar to the one
	that the `rossby_number_from_mass` function and
	Wright et al. (2011) use.

	Parameters
	----------
	prot	:float, Spin period of the star in days
	mstar   :float, Mass of the star in solar masses
	age	 :float, Age in Myr

	Returns
	-------
	xray_activity :float, X-ray activity (Lx/Lbol)


Loads dataset from disk, renames some columns, and calculates others


		Avoid loading dataset on startup to reduce import time.
		Load only when class is used.


Ensures only one valid input stellar parameter is provided


Returns a list of stellar parameters that can be interpolated


Determines spectral type from input stellar parameter


Returns all stellar parameters (except spectral type) from an input parameter.


		Returns all available stellar parameters for a star.

		Parameters
		----------
		mstar   :float|list, stellar mass in Msun.
		age	 :float|list (optional), age of the star in Myr.

		Returns
		-------
		params :dict[float]


Calculates planet radius from its mass assuming a pure rock (100% MgSiO2) composition using the model by Zeng+19


Calculates planet radius from its mass assuming a pure iron (100% Fe) composition using the model by Zeng+19


Calculates planet radius from its mass assuming an Earth-like (1/3 iron, 2/3 rock) composition using the model by Zeng+19


Calculates planet radius from its mass assuming a pure water (100% H2O) composition using the model by Zeng+19


Calculates planet radius from its mass assuming a water + rock (50% H2O+ 50% Earth-like) composition using the model by Zeng+19


    Calculates the radius of the planet's core using the relations
    by Otegi et a. (2020) based on an empirical fit to planet populations.

    Parameters
    ----------
    mcore   : float, core mass in Earth masses
    ot20_errors : bool, enables uncertainties

    Returns
    -------
    rcore   : float, core radius. It is of type uncertainties.ufloat
            if errors are enabled, and a python float otherwise.


    Calculates the radius of the planet's core using the relations
    by Fortney et a. (2007) for both rocky and icy cores.

    Parameters
    ----------
    mcore     : float, core mass in Earth masses
    ft07_iron : float (optional), iron mass fraction (0, 1)
    ft07_ice  : float (optional), ice mass fraction (0, 1).
        The iron and ice mass fractions cannot both be greater than zero.
        By default, an iron mass fraction of 1/3 is used.
        If the ice mass fraction is given a value above zero,
        a rock-ice composition will be used instead of a rock-iron composition.

    Returns
    -------
    rcore   : float, core radius.


Parse command line arguments and invoke the appropriate method.


Validates that the contents of the Harmony message provides all
        necessary parameters.

        Currently imposed rules:
        1. scaleExtent and scaleSize must be accompanied by crs.
        2. scaleExtent min values must be smaller than the max values


Processes a single input STAC item.


Generate an output file name based on the input asset URL and the
        operations performed to produce the output. Use this name to stage
        the output in the S3 location specified in the input Harmony
        message.


Create an output STAC item used to access the browse imagery and
            ESRI world file as staged in S3.

        item_assets is an array of tuples where the tuples should be: (name,
        url, role)


Write a manifest file of the output images.

        Write a file that will serve as the 'data' key for tiled output.  At
        some point we will have to find out why this is necessary, but this is
        a clever work around to that necessity.


Create a SpatioTemporal Asset Catalog (STAC). These are used as inputs
    for Harmony requests, containing the URL and other information for
    input granules.

    For simplicity the geometric and temporal properties of each item are
    set to default values.


Check the contents of the Harmony output STAC. It should have a
        single data item. The URL, title and media type for this asset will
        be compared to supplied values.


Create browse imagery from an input geotiff.

    This is the exposed library function to allow users to create browse images
    from the hybig-py library. It parses the input params and constructs the
    correct Harmony input structure [Message.Format] to call the service's
    entry point create_browse_imagery.

    Output images are created and deposited into the input GeoTIFF's directory.

    Args:
        source_tiff: str, location of the input geotiff to process.

        params: [dict | None], A dictionary with the following keys:

            mime: [str], MIME type of the output image (default: 'image/png').
                  any string that contains 'jpeg' will return a jpeg image,
                  otherwise create a png.

            crs: [dict | None], Target image's Coordinate Reference System.
                 A dictionary with 'epsg', 'proj4' or 'wkt' key.

            scale_extent: [dict | None], Scale Extents for the image. This dictionary
                contains "x" and "y" keys each whose value which is a dictionary
                of "min", "max" values in the same units as the crs.
                e.g.: { "x": { "min": 0.5, "max": 125 },
                        "y": { "min": 52, "max": 75.22 } }

            scale_size: [dict | None], Scale sizes for the image.  The dictionary
                contains "x" and "y" keys with the horizontal and veritcal
                resolution in the same units as the crs.
                e.g.: { "x": 10, "y": 10 }

            height: [int | None], height of the output image in gridcells.

            width: [int | none], width of the output image in gridcells.

        palette: [str | ColorPalette | none], either a URL to a remote color palette
             that is fetched and loaded or a ColorPalette object used to color
             the output browse image. If not provided, a grayscale image is
             generated.

        logger: [Logger | None], a configured Logger object. If None a default
             logger will be used.

    Note:
      if supplied, scale_size, scale_extent, height and width must be
      internally consistent.  To define a valid output grid:
            * Specify scale_extent and 1 of:
              * height and width
              * scale_sizes (in the x and y horizontal spatial dimensions)
            * Specify all three of the above, but ensure values are consistent
              with one another, noting that:
              scale_size.x = (scale_extent.x.max - scale_extent.x.min) / width
              scale_size.y = (scale_extent.y.max - scale_extent.y.min) / height

    Returns:
        List of 3-element tuples. These are the file paths of:
        - The output browse image
        - Its associated ESRI world file (containing georeferencing information)
        - The auxiliary XML file (containing duplicative georeferencing information)

    Example Usage:
        results = create_browse(
            "/path/to/geotiff",
            {
                "mime": "image/png",
                "crs": {"epsg": "EPSG:4326"},
                "scale_extent": {
                    "x": {"min": -180, "max": 180},
                    "y": {"min": -90, "max": 90},
                },
                "scale_size": {"x": 10, "y": 10},
            },
            "https://remote-colortable",
            logger,
        )


Create browse image from input geotiff.

    Take input browse image and return a 3-element tuple for the file paths of
    the output browse image, its associated ESRI world file and the auxilary
    xml file.


Convert multiband to a raster image.

    Return a 4-band raster, where the alpha layer is presumed to be the missing
    data mask.

    Convert 3-band data into a 4-band raster by generating an alpha layer from
    any missing data in the RGB bands.


Convert Banded data with NaNs (missing) into a uint8 data cube.

    Nearly all of the time this will simply pass through the data coercing it
    back into unsigned ints and setting the missing values to 0 that will be
    masked as transparent in the output png.

    There is a some small non-zero chance that the input RGB image was 16-bit
    and if any of the values exceed 255, we must normalize all of input data to
    the range 0-255.


Return the original input data's type.

    rastero_open retains the input dtype in the encoding dictionary and is used
    to understand what kind of casts are safe.


Convert input dataset to a 1-band palettized image with colormap.

    Uses a palette if provided otherwise returns a greyscale image.


Normalize input array and return scaled data with greyscale ColorMap.


Convert input 1-band dataset to RGB image for JPEG output.

    Uses a palette if provided, otherwise returns a greyscale RGB image.
    Returns a 3-band RGB array and None for colormap (since RGB doesn't need colormap).


Normalize input array and return as 3-band RGB grayscale image.


Scale a 1-band image with palette into RGB image for JPEG output.


Scale a 1-band image with palette into modified image and associated color_map.

    Use the palette's levels and values, transform the input data_array into
    the correct levels indexed from 0-255 return the scaled array along side of
    a colormap corresponding to the new levels.


Return requested rasterio driver for output image.


Generate the output image name.


Generate an output world file name.


Explicit check for a CRS on the input geotiff.

    Raises HyBIGError if crs is missing.


Ensure we can work with the input data file.

    Raise an exception if this file is unusable by the service.


Write raster data to output file.

    Writes the raster to an output file using metadata from the original
    source, and over-riding some values based on the input message and derived
    grid_parameters, doing a nearest neighbor resampling to the target grid.


Return the target CRS for the output image.

    If a harmony message defines a SRS, we use that as the target ouptut CRS.
    Otherwise, we try determine the best "GIBS compatible" CRS based on the
    input granule metadata.


Choose the best CRS based on the Harmony Request's SRS.

    create a CRS from the harmony srs information.
    prefer epsg to wkt
    prefer wkt to proj4

    Raise HyBIGValueError if the harmony SRS cannot be converted to a
    rasterio CRS for any reason.


Returns true if the input CRS is preferred by GIBS.


Determine the best CRS based on input metadata.


Remove alpha layer when it exists.


Return a gdal ColorPalette from a remote colortable.


Convert a GeoTIFF palette to GDAL ColorPalette.

    Reformats a palette as dictionary and loads it into a ColorPalette.

    a GeoTIFF's colormap looks like a dictionary of tiff's value to (r,g,b,[a])
    {0: (9, 60, 112, 255),
     1: (9, 65, 122, 255),
     2: (9, 80, 132, 255),
     3: (9, 100, 142, 255),...}


Return the scaleExtent for the target image.

    Returns a scale extent found in the input Message.

    Otherwise, computes a bounding box in the target CRS based on the input
    granule extent.


This selects or computes the target Dimensions.

    This routine finalizes the output grid.  The target dimensions are
    returned.  These along with the CRS and scaleExent will be used to
    selecting the correct output transformation for the final image.

    To determine the target dimensions the following occurs.

    The input harmony message format is searched for dimensions or scaleSizes:
    If dimensions (height and width) are found, they are returned.
    If scaleSize is found, it is converted to height and width and returned.

    If no scaleSize or dimensions are input. The input dataset metadata
    resolution is checked against the GIBS preferred resolutions and the best
    fit resolution along with the scaleExtent is used to compute the target
    dimensions to return.


Split the output grid if necessary.

    When the number of grid cells exceeds 8192x8192, we tile the output
    to a reasonable size: 4096x4096

    returns a list of GridParams object that completely cover the input scale
    extent tiled as needed.


Return a list of tile dimensions.

    From a list of origin locations, return the dimension for each tile.


Returns a list of boundary cells.

    The returned boundary cells are the column [or row] values for each of the
    output tiles. They should always start at 0, and end at the full_size
    input, stepping by target size until the last step, which can be any size
    including 0.


Returns true if the grid is too large for GIBS.

    From discussion, this limit is set to 8192*8192 cells.


Return best guess for output image dimensions.

    Using the information from the scaleExtent and the input dataset metadata,
    compute the height and width appropriate for the output image.

    North and South projections have matching resolutions so we just use the
    3413 resolutions for all projected data.


Return the x and y target resolutions

    The input resolution can be determined from the Affine transformation, but
    if the input dataset is projected, and the target CRS is unprojected, we
    need to convert the resolution meters into degrees.

    This routine is only called for best_guess_target_dimensions which means
    the user has not supplied any input parameters and we are trying to
    determine the dimensions for the output image.


Guess Dimensions given the input information and ICD resolutions.


Compute dimensions from inputs.

    We round the computed dimensions because we need to have integer values of
    height and width. Because of the rounding, this function could return a
    height/width that in combination with the ScaleExtent would be slightly
    inconsistent with the input res (ScaleSize).  This is ok, because for
    computed values of scaleExtent, we are already self consistent.  If there's
    a discrepancy, the user has described a scaleExtent in the input
    HarmonyMessage and has *not* specified a scaleSize. So we honor the
    scaleExtent in a previous function.


Return closest match to GIBS preferred Resolution Info.

    Cycle through all input resolutions and return the resolution_info that has
    the smallest absolute difference to any of the input resolutions.


Update collection-level summaries for a single collection.
        This includes dashboard summaries (i.e. datetime and cog_default) as well as
        STAC-conformant bbox and temporal extent.


    DynamoDB stores floats as Decimals. We want to convert them back to floats
    before inserting them into pgSTAC to avoid any issues when the records are
    converted to JSON by pgSTAC.


    Loads items into the PgSTAC database and
    updates the summaries and extent for the collections involved


Loads the collection to the PgSTAC database


    Bulk insert STAC records into pgSTAC.
    The ingestion can be items or collection, determined by the `table` arg.


Ensure we can send HEAD requests to S3 objects.


Ensure we can send HEAD requests to S3 objects in bucket.


Ensure URLs are accessible via HEAD requests.


Ensures `cog_default` key exists in item_assets in a collection


Ensures that the time_density is valid based on the value of is_periodic


Ensure collection exists in STAC


Extracts start & end or single date string from filename.


Lists the STAC items from ingestion.


Ingests a STAC item.


Updates the STAC item with the provided item.


Cancels an ingestion in queued state.


Publish a collection to the STAC database.


Delete a collection from the STAC database.


Triggers the ingestion workflow


Return claims for the provided JWT


Add correlation ids to all requests and subsequent logs/traces


Validate & decode JWT


Base64 encode next parameter for easier transportability


        Validate that the collection exists.

        Parameters:
        - collection (str): Name of the collection to be validated.

        Returns:
        - str: Name of the collection.


Bulk update DynamoDB with ingestion results.


Creates a zarr stac collection based off of the user input


        Takes a collection model,
        does necessary preprocessing,
        and loads into the PgSTAC collection table


Deletes the collection from the database


	A function that calculates the mantle adiabat temperature for given pressure
	range. Taken from Katsura (2022).

	###Parameters###
	P_input: Pressure in GPa


Extract analysis period out of data-array (1900-2015)


open and caluclate the difference between the ensemble means of two members


Open percentile da (e.g. TX10, R05 etc)


calculate mean of every srex region


calculate seasonal mean of data array, (season= 'JJA', 'SON', 'DJF' or 'JFM')


plot timeseries (of spatial mean)


calculate and plot annual mean timeseries


plot difference maps without creating a figure within function


plot row of 2 boxplot of different SREX regions, one with all pixels, one with only reservoir pixels


plot row of 2 boxplot of different SREX regions, one with all pixels, one with all land and one with only reservoir pixels


plot the seasonal cycle averaged over reservoir grid cells for different thresholds


calculate pvalue ing the two-sided, paired, non-parametric Wilcoxon signed rank test


Add hatching to plot, indicating statistical significance


 function to check field significance with False Discovery Rate
        Wilks 2006, J. of Applied Met. and Clim.
        p_val = P-values at every grid point,
        h_val = 0 or 1 at every grid point, depending on significance level
        code translated from R to python from Lorenz et al. (2016)
        https://github.com/ruthlorenz/stat_tests_correlated_climdata/blob/master/FStests/false_discovery_rate_package.R


function to calculate bin statistics for the whole ensemble


    Use `pypcaf.nextpow2` to pad the signal you pass to FFT.

    Parameters
    ----------
    n : `int`

    Returns
    -------
    m : `int`
        Exponent of next higher power of 2.


    Finds the highest (or maximum) plateau region in data, the plateau has
    length ``n``, then among the ``n`` points returns its maximum.

    Parameters
    ----------
    X : `~numpy.ndarray`
        One dimensional array where the maximum needs to be found.
    n : `int`
        Number of points in the plateau region. It is also named
        ``region_order``.

    Returns
    -------
    idx_max : `int`
        Index or position in the ``X`` array where the maximum of a plateau of
        length ``n`` is located.


    Given a one dimensional times array, ``times``, the function computes its
    FFT to find a better period than the given one, ``T_init``. Be aware that
    depending on the signal-to-noise of the times array, may or may not find a
    correct value. For really noisy signals do not use this function.

    Parameters
    ----------
    times : `~numpy.ndarray`
        One dimensional times array with certain hidden periodicity, e.g.
        pulsar period.
    dt : `float`
        times bin.
    T_init : `float`
        Initial period.

    Returns
    -------
    T_est : `float`
        Estimated period from the ``times`` array, found by a FFT analysis.


    Computes the root-mean-square value for an array.

    Parameters
    ----------
    X : `~numpy.ndarray`
        One or two dimensional array.


    Global value signal-to-noise, named Confidence Paramerter (PC). Quantifies
    the goodness fo a merit function after the PCA-Folding has been executed.
    It isolates the peak by a ``frac`` portion of the whole array. Then it
    computes its average and tandard deviation excluding the peak region.

    Parameters
    ----------
    merit : `~numpy.ndarray`
        One dimentional array which contains the merit function, computed
        trhough the eigenvector and eigenvalues, output from the PCA-Folding.
        The merit function determines the best period found in PCA-Folding.
    idx_max : `int`
        Position of the maximum value in the merit function (or maximum in a
        plateau region, depending on ``region_finder``). This index is
        then used to compute the estimated period from the selected
        ``iteration`` (see `pypcaf.find_period` function).
    frac : `float`
        Porcentage of the region to isolate the maximum peak.

    Returns
    -------
    sigma : `float`
    mean : `float`
    cp : `float`


    Classical folding algorithm with waterfall (diagram) implementation. The
    ``times`` array is reshaped respect to a specific period, ``T``, and placed
    as a waterfall diagram with a number of division of ``num_div`` or ``M``.
    The number of divisions represents the number of elements in a row (and
    later it will represent the number of eigenvalues from in a waterfall PCA).

    Parameters
    ----------
    times : `~numpy.ndarray`
        One dimensional times array with certain hidden periodicity, e.g.
        pulsar period.
    dt : `float`
        times bin.
    T : `float`
        Period used to compute the waterfall matrix, :math:`N \\timess M`. ``N``
        is strictly dependent on the period and the times bin used.
    num_div : `int`
        Number of divisions made to the times array, which corresponds to the
        number of elements in a row of the waterfall matrix.

    Returns
    -------
    remainder : `~numpy.ndarray`
        Remainder of the folding, ready to use in the `~pypcaf.light_curve`
        light-curve.
    waterfall : `~numpy.ndarray`
        :math:`N \\timess M`. ``N`` matrix (two dimensional array). The
        waterfall matrix depends on the four inputs from the `~pypfac.folding`
        function. i.e. ``times``, ``dt``, ``T``, ``num_div``.


    Newer and faster folding algorithm with waterfall (diagram)
    implementation. The ``times`` array is reshaped respect to a specific
    period, ``T``, and placed as a waterfall diagram with a number of division
    of ``num_div`` or ``M``. The number of divisions represents the number of
    elements in a row (and later it will represent the number of eigenvalues
    from in a waterfall PCA).

    Parameters
    ----------
    times : `~numpy.ndarray`
        One dimensional times array with certain hidden periodicity, e.g.
        pulsar period.
    dt : `float`
        times bin.
    T : `float`
        Period used to compute the waterfall matrix, :math:`N \\timess M`. ``N``
        is strictly dependent on the period and the times bin used.
    num_div : `int`
        Number of divisions made to the times array, which corresponds to the
        number of elements in a row of the waterfall matrix.

    Returns
    -------
    remainder : `~numpy.ndarray`
        Remainder of the folding, ready to use in the `~pypcaf.light_curve`
        light-curve.
    waterfall : `~numpy.ndarray`
        :math:`N \\timess M`. ``N`` matrix (two dimensional array). The
        waterfall matrix depends on the four inputs from the `~pypfac.folding`
        function. i.e. ``times``, ``dt``, ``T``, ``num_div``.