        Crate a plot of the fitted adjustments (interpolated residuals from
        before and after applying model correction factors) that are finally
        applied to the observations.

        Parameters
        -------
        ax : plt.Axes, optional (default: None)
            Use this axis object instead to create the plot in

        Returns
        -------
        fig : plt.figure or None
            The figure that was created


        Create a figure of the 2 linear models, save it if a path is passed.

        Parameters
        -------
        image_path : str
            File that the figure is saved as
        axs : list
            To use preset axes, pass them here, must contain 2 axes
        supress_title : bool
            Do not plot a title

        Returns
        -------
        plot_coll_figure : plt.figure
            The figure object
        axs : plt.axes
            Axes of the figure


        Apply adjustments to values with the respective dates.
        Parameters
        ----------
        values_to_adjust : pd.Series
            Values where the adjustments are applied
        adjustments : pd.Series
            Adjustments that are applied

        Returns
        -------
        adjusted_values : pd.Series
            Values with applied adjustments


        Adjusts the passed values based on differences in the linear models of the
        object.

        Parameters
        -------
        values_to_adjust : pd.Series, optional (default: None)
            Values to which the additive (intercept diff) and multiplicative
            (slope ratio) correction parameters are applied.
        corrections_from_core : bool, optional (default: True)
            Apply the model corrections to the values from the homogeneous core
            instead to all values_to_adjust. Then applies the corrections
            to all values_to_adjust. If this is not selected the corrections are
            applied directly and the adjustments are not repeated to the extended
            time frame.
        values_to_adjust_freq : str, optional (default: D)
            Temporal resolution of the values that should be adjusted (D or M)
        resample_corrections : bool, optional (default: True)
            Adjustments are M-resampled then interpolation to match the
            temporal resolution of the daily values_to_adjust.
        interpolation_method : str, optional (default: linear)
            To fit constant, linear or a spline pass the method as for scipy.interp1d
            https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html
            To fit a least squares polynomial, pass "polyN" where N is the order of
            the polynomial.

        Returns
        -------
        adjusted_values : pd.Series
            The passed values after applying the corrections from to model
            differences.


        Calculate differences in the model parameters for the 2 passed models.

        Parameters
        ----------
        adj_model : LinearRegression
            Model parameters of the model from data that is adjusted
            must contain 'slope' and 'inter' as keys and valid values.
        ref_model : LinearRegression
            Model parameters of the model for data that is not adjusted
            must contain 'slope' and 'inter' as keys and valid values.

        Returns
        -------
        slope_ratio : float
            Ratio of the slopes of the 2 models based on which model is to be
            corrected later.
        inter_diff : float
            Difference in the models intercepts, based on which model is to be
            corrected later.


        Create daily values from monthly ones by interpolation

        Parameters
        ----------
        start : datetime
            First date of the interpolated series
        end : datetime
            Last date of the interpolted series
        samples : pd. Series
            Some values and dates that are used as nodes for the interpolation
        interpolation_method :
            To fit constant, linear or a spline pass the method as for scipy.interp1d
            https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html
            To fit a least squares polynomial, pass "polyN" where N is the order of
            the polynomial.

        Returns
        -------


        TODO: clean up

        Adjusts the candidate column for the selected period (before, after
        break time) relatively to the reference column, so that the regression
        properties would fit.

        Parameters
        -------
        startdate : datetime
            First datetime for which we find adjustmetns
        enddate : datetime
            Last date for which we find adjustments
        resample_corrections: bool
            Adjustments are M-resampled before interpolation/before application to the input
        interpolation_method : str or None, optional (default: poly2)
            To fit constant, linear or a spline pass the method as for scipy.interp1d
            https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html
            To fit a least squares polynomial, pass "polyN" where N is the order of
            the polynomial.

        Returns
        -------
        adjustments : pd.Series
            Adjustments to apply to the observations.


Specific for each child class, meta-info for plotting


Creates plot styles based on the success of an adjustment step


        Take the input candidate and reference and build a dataframe
        with columns 'candidate', 'reference' and

        Parameters
        -------
        candidate : pd.Series
            The candidate data set
        reference : pd.Series
            The reference data set
        dropna : bool, optional (default: True)
            Drop all lines, where either candidate or reference is nan, so the
            joined df contains no nans at all.

        Returns
        -------
        joined_df : pd.DataFrame
            The joined input data and difference time series


        Checks if the passed group is either 0 or 1, otherwise raises an exception.
        Used to set a main group (e.g. that is adjusted)

        Parameters
        -------
        group_no : int
            Group (0=before, 1=after break) of the group to make the main group

        Returns
        --------
        group_no : int
            Index (0 or 1) of the main group
        other_no : int
            Index (0 or 1) of the second group


        Scales the 'reference' column to the 'candidate' column via fitting
        of regression parameters.

        Parameters
        -------
        frame : DataFrame
            The DataFrame with the candidate and reference data
        method : str, optional (default: 'linreg')
            Method for bias correction as described in pytesmo
        group : int or None, optional (default: None)
            0 or 1, if a group is selected, bias is calculated only for values
            of the group and applied to the whole frame, if None is selected,
            bias is calculated from and applied to the full frame.

        Returns
        -------
        df_reference : pd.DataFrame
            The bias corrected input data frame reference column


        Rename the candidate, reference and adjusted data column if the exist
        in the passed data frame

        Parameters
        ----------
        df : pd.DataFrame
            The data frame in which the candidate, reference, adjusted are searched
        can_name : str, optional (default: None)
            If a name is passed, the candidate column is renamed
        ref_name : str, optional (default: None)
            If a name is passed, the reference column is renamed
        adj_name : str, optional (default: None)
            If a name is passed, the adjusted column is renamed if it exists.

        Returns
        -------
        df_renamed : pd.DataFrame
            The renamed input df data frame with the 2 (rep. 3) columns


        Adds a new column to the passed dataframe for the difference values
        between candidate and reference in the main data frame

        Parameters
        -------
        input_df : pd.DataFrame
            Dataframe that contains a candidate and reference column.

        Returns
        -------
        df_Q : pd.DataFrame
            Difference Series between candidate and reference


        Plot the passed frame only.

        Parameters
        ----------
        frame : pd.DataFrame
            Frame to read the time series from
        title : str, optional (default: None)
            Title that is used for the plot, if None is passed, it gets no title.
        only_success : bool, optional (default: False)
            Only plot the adjusted candidate if adjustment removed the break
            and all checks passed.
        ax : matplotlib.axes.Axes, optional (default: None)
            Axes that is used for the plot
        save_path : str, optional (default: None)
            Path to file where the image is stored.

        Returns
        -------
        ax : matplotlib.axes.Axes
            Plot axes


        Create a plot of candidate and reference time series for the tested period.
        Indicates whether a break was found or not.
        Calculate time series stats for comparison and save the plot

        Parameters
        -------
        frame: pd.DataFrame
            The dataframe that is plotted
            eg self.df_original, or self.df_frame etc.
        kind : str, optional (default: 'box')
            Select 'box' or 'line 'to plots stats as line plots or box plots
        save_path : str, optional (default: None)
            Path to file where the image is stored
        title : str, optional (default: None)
            Title for the plot, if None is passed, it gets no title.
        stats: bool, optional (default: False)
            If True, adds stats in a text box to the empty panels of the figure.

        Returns
        -------
        fig_frame_ts : plt.figure
            Figure of the time series and stats plots


        Take the input data (self.df_original) and fit all values with a single
        regression model.

        Returns
        -------
        model : LinearModel
            The linear model for all values


        Calculates the sse (sum of squared residuals) function around the break time.
        2 linear models are calculated for multiple potential break times
        (margin around self.breaktime).
        SSEs for the 2 models are summed, to get an overall SSE for the function

        A break is most likely where the SSE function has a minimum (the 2 models fit best).
        This function can be used to confirm a detected break at a certain date,
        or search for a break in a prior known time period.

        Parameters
        -------
        input_df : pandas.DataFrame
            Data for which the residuals are calculated, must contain a reference data col
        n_margin : int
            Margin describes the number of dates (BEFORE AND AFTER self.breaktime)
            for which 2 regression models are calculated.
        use_adjusted_values : bool
            If this is true, force to use the 'adjusted' column in df
        filter_p : float
            For both models drop the passed percent (0-100) of worst candidate
            (high absolute difference) values compared to reference.

        Returns
        -------
        sse : pd.Series
            Series of sums of SSE of 2 linear models, for before and after the
            tested break time.
        min_date : datetime
            Date with the minimum SSE (where the break is)


        Calculates the autocorrelations of the residuals for a single linear model.
        If this varies for low lags it indicates the existence of a break.

        Parameters
        -------
        lags : list
            List of lags that are used for the autocorrelation function
            (unit same as self.df_original)
        use_adj_col : bool
            Force to use the self.adjusted_col_name column in
        Returns
        -------
        autocorr : pandas.Series
        Series of autocorrelation values for the selected lags


        Plot data and model as scatter plot

        Prameters
        -------
        axs : matplotlib.Axes.axes
            Axes object that is used for plotting

        Returns
        -------
        ax : matplotlib.Axes.axes
            The plot axes


        Performs percentile based filtering based on differences between
        candidate and reference.
        Stores the filtered values in the model data frame (self.df_model)

        Returns
        -------
        df_model : pd.DataFrame
            The filtered (or unfiltered) dataframe.


        Filter data in the selected frame based on the difference values
        (Q-column) and the current filter settings.

        Parameters
        ----------
        frame : pandas.DataFrame
            The frame, that will be filtered based on Q

        Returns
        -------
        df_filtered : pd.DataFrame
            The filtered input data (input data that hast filter mask value 0)
        masked_values : pd.DataSeries
            Series of flags according to the objects input data


        Calculate the actual (non) linear model for the candidate and
        reference data of the object using support vector regression from sklearn.

        Parameters
        -------
        C : float, optional (default = 1.)
            Penalty parameter C of the error term.

        Returns
        -------
        model : sklearn.svm.SVR
            Model between candidate and reference


        Calculate auto-correlation function for the errors of the current model.

        Parameters
        -------
        lags : list
            Time lags used for the auto correlation function.
            E.g: [0,1,2] returns the auto-correlation values with for shifts over
            0, 1 and 2 time units.

        Returns
        -------
        autocorr : pandas.Series
            Auto correlation function for the current residuals with the selected
            lag(s).


Returns the coefficient of determination R^2 of the prediction.

        The coefficient R^2 is defined as (1 - u/v), where u is the residual
        sum of squares ((y_true - y_pred) ** 2).sum() and v is the total
        sum of squares ((y_true - y_true.mean()) ** 2).sum().
        The best possible score is 1.0 and it can be negative (because the
        model can be arbitrarily worse). A constant model that always
        predicts the expected value of y, disregarding the input features,
        would get a R^2 score of 0.0.


        Calculate the root mean squared error from the residuals between the
        observed and predicted values.

        Returns
        -------
        rmse : float
            Root mean squared errors


        Calculate the sum of squared errors of the current model

        Returns
        -------
        sse : float
            Sum of squared residuals


        Calculate the median/mean of errors of the current model

        Parameters
        -------
        median : bool
            Use the median instead of the mean of the residuals

        Returns
        -------
        mse : float
            Median of the squared residuals


        Calculate the median/mean of squared errors of the current model

        Parameters
        -------
        median : bool
            Use the median instead of the mean of the residuals

        Returns
        -------
        mse : float
            Median or mean of the squared residuals


        Calls functions for performing adjustment specific checks.

        Parameters
        -------
        min_group_range : int, optional (default:None)
            Minimum covered days by either adjustment group (range between first
            and last day, not individual observations).
        pearsR_sig : tuple or None, optional (dafault: None)
            Minimum r and maximum p for pearson correlation between candidate and
            reference OF EACH GROUP, to attempt adjustment.
            At low correlation the linear model is not representative of the data.
        coverdiff_max : float, optional (default: None)
            Between 0 and 1, how large the difference in relative temporal
            coverage for any month may be.

        Returns
        -------
        error_code_adjust : int
            The error code for the check that failed
        error_text_adjust : str
            The text for the check that failed


For monthly data, the time frame and break time has to be adapted


        Check the coverage of the candidate data of the 2 groups.
        Create an error, if the coverage comparison fails or is below the
        selected threshold

        Parameters
        ----------
        coverdiff_max : float, between 0 and 1
            The maximum difference for day/month that the coverage of the 2 groups
            may differ.
        try_fix : bool
            Fix the coverage differences by dropping unequal months in both
            groups and the re-test.


        Check if the SM error of the 2 groups is compareable.
        High error might lead to unfitting linear models.

        Returns
        -------


        Check if each group spans over a sufficiently long time period.

        Parameters
        ----------
        min_days : int
            Number of days that have to be covered by each group.
            Rhe range between first and last observation, not the number
            of actual observations counts!

        Returns
        -------


        Check if the correlation of the 2 groups is above the passed threshold

        Parameters
        ----------
        min_corr : float
            minimum correlation that is necessary
        max_p : float
            significance that is necessary

        Returns
        -------


        Checks if the adjustment raised an error or not.

        Parameters
        -------
        error_codes_pass : list
            List of error codes that dont lead to the checks to fail.

        Returns
        -------
        checks_pass : bool
            Indicates whether all checks passed or not.


        Calls the chosen implementation of the linear regression model with the
        properties that were chosen for this class.

        Parameters
        -------
        implementation : str
            Identifies the implementation for the model calculation


Implement a RANSAC based linear regression estimation


Implement a Theil-Sen based linear regression estimation


        Calculates the regression model between candidate and reference

        Parameters
        ----------
        candidate_data : np.array
            Candidate values as array
        reference_data : np.array
            Reference data as array

        Returns
        -------
        b : np.array
            Model parameters (intercept, slope)
        n : int
            Number of elemets
        placeholder1 : None
            This is just so the outputs are the same as for the scipy version.
        placeholder2 : None
            This is just so the outputs are the same as for the scipy version.
        placeholder3 : None
            This is just so the outputs are the same as for the scipy version.
        candidate_modeled : np.array
            Application of the linear model to the reference data yields the
            modeled candidate
        residuals : np.array
            Residuals between candidate and modeled candidate


        Calculates the regression model between candidate and reference based
        on the scipy.stats module.

        Parameters
        ----------
        candidate_data : np.array
            Candidate values as array
        reference_data : np.array
            Reference data as array

        Returns
        -------
        b : np.array
            Model parameters (intercept, slope)
        n : int
            Number of elemets
        r_value : float
            Correlation coefficient
        p_value : float
            Two-sided p-value for a hypothesis test whose null hypothesis is
            that the slope is zero.
        std_err : float
            Standard error of the estimate
        candidate_modeled : np.array
            Application of the linear model to the reference data yields the
            modeled candidate
        residuals : np.array
            Residuals between candidate and modeled candidate


        Calculates the regression model between candidate and reference based
        on the scipy.stats module.

        Parameters
        ----------
        candidate_data : np.array
            Candidate values as array
        reference_data : np.array
            Reference data as array
        fit_intercept : bool
            Fit the intercept also.

        Returns
        -------
        b : np.array
            Model parameters (intercept, slope)
        n : int
            Number of elemets
        r_value : float
            Correlation coefficient
        p_value : float
            Two-sided p-value for a hypothesis test whose null hypothesis is
            that the slope is zero.
        std_err : float
            Standard error of the estimate
        candidate_modeled : np.array
            Application of the linear model to the reference data yields the
            modeled candidate
        residuals : np.array
            Residuals between candidate and modeled candidate


        Plot data and model as scatter plot

        Parameters
        -------
        plot_data : bool, optional (default: True)
            Add the data points as a scatter plot.
        plot_model : bool, optional (default: True)
            Add the candidate predictions from the model as a line plot (linear)
        ax : matplotlib.Axes.axes
            Axes object that is used for plotting
        vmax : float, optional (defaul: None)
            Set the maximum (we add 15%) of the 2 axes that are plotted
        plot_stats : bool, optional (default: True)
            Plot the stats of the model (N, slope, int) at the bottom in a box.
        scatter_style : (str, float, str), optional (default: ('o', 0.4, 'blue'))
            (marker_style, marker_alpha, marker_color)
            Styling for the scatter plot part of the figure (the observations).
        model_style : (str, float, str), optional (default: ('o', 0.4, 'blue'))
            (linestyle, linewidth, color)
            Styling for the line plot part of the figure (the predictions).
        oneoneline: bool, optional (default: True)
            Plot the one by one line

        Returns
        -------
        ax : matplotlib.Axes.axes
            The plot axes


        Calculate autocorrelation function for the residuals of the current model.

        Parameters
        -------
        lags : list or int, optional (default: 0)
            Time lags used for the auto correlation function

        Returns
        -------
        autocorr : pandas.Series
            Auto correlation function for the current residuals with the selected
            lag(s).


        Calculate the sum of squared errors (residuals) the the current model

        Returns
        -------
        sse : float
            Sum of squared residuals


        Find the quantiles for the passed values using the CDF.
        CDF(x) = q, eg. for a norm-dist CDF(data_mean) = ~50

        Parameters
        -------
        data : np.array
            Observations that are looked up in the CDF to get their quantiles

        Returns
        -------
        quant : np.array
            Quantiles for the data values using the cdf


Fit a Normal Distribution


Fit a wakeby distribution


Fit a Generalized Normal Dist


Fit a Pearson type 3 distribution


Fit a Generalised Pareto distribution


Fit a Generalised Extreme Value distribution


        Kolmogorov-Smirnoff test that finds the best fitting CDF of the selected
        types.

        Parameters
        -------
        types : list or None
            List of possible pdf types as in the LMoments package.

        Returns
        -------
        name : str
            name of the best fitting cdf
        cdf : partial
            CDF as from LMoments
        pdf : partial
            PDF as from LMoments
        para : list
            Lmoments cdf/pdf parameters


        Get CDF values at deciles and the category edges

        Parameters
        -------
        i : int
            Decile number (1 to 10)

        Returns
        -------
        y : float
            CDF value at the decile (quantile)
        bin : tuple
            src value for the beginning and end of the decile bin.
            Start of d1 and end of d10 will be nan


        Plot the probability distribution function of this object

        Parameters
        -------
        plot_empirical : bool, optional (default: True)
            Add the observations as points to the plot of the theoretical, fitted PDF.
        name : str, optional (default: None)
            Name of the plotted data that is shown in the plot title and legend.
        xlabel : str, optional (default: 'SM')
            Name of the variable that is shown as the label of the X axis.
        style : tuple or str, optional (default: None)
            (color, linestyle) or a string (c--)
            Tuple of color and linestyle that is used when creating the plot,
            or the short form of a color and line combination.
        ax : plt.axes, optional (default: None)
            Use this axes to create the plot in, if None is passed we create a
            figure and ax.


        Plot the cumulative distribution function of this object

        Parameters
        -------
        plot_empirical : bool, optional (default: True)
            Add the observations as points to the plot of the theoretical, fitted CDF.
        name : str, optional (default: None)
            Name of the plotted data that is shown in the plot title and legend.
        xlabel : str, optional (default: 'SM')
            Name of the variable that is shown as the label of the X axis.
        style : tuple or str, optional (default: None)
            (color, linestyle) or a string (c--)
            Tuple of color and linestyle that is used when creating the plot,
            or the short form of a color and line combination.
        ax : plt.axes, optional (default: None)
            Use this axes to create the plot in, if None is passed we create a
            figure and ax.


General Usecase that fits some dist to some random test data.


        Sort the break times according to the base period (start).

        Parameters
        -------
        times : np.array
            List of break times that should be sorted according to the base period
        base_breaktime : int
            Identifies the base breaktime, for which the time frame is created first.
            eg 0 would start with the last period and return other periods
            towards the beginning
            eg -1 would start with the first period and return other periods
            towards the end
            eg 2 would start with the 3rd last period, return other periods
            towards the end, then return other periods towards the beginning.

        Returns
        -------
        bt_before : np.array
            Break times before the base break time
        bt after : np.array
            Break times after the base break time


        Iterates over break times and removes break times that lead to time frames
        smaller than the passed threshold.

        Parameters
        -------
        breaktimes : list
            List of breaktimes that should be filtered
        days_min : int
            minimum number of days that a set (timeframe_start - breaktime,
            breaktime - timeframe_end) must contain.

        Returns
        -------
        breaktimes : list
            The filtered list of breaktimes


        Takes subsequent breaktimes and creates time frames using the dataset
        start and end

        Parameters
        ----------
        breaktimes : np.array
            List of break times that are used beside the dataset range for
            creating time frames
        base_breaktime : int
            Identifies the base breaktime, for which the time frame is created
            first.
            eg 0 would start with the last period and return other periods towards
            the beginning
            eg -1 would start with the first period and return other periods towards
            the end
            eg 2 would start with the 3rd last period, return other periods
            towards the end, then return other periods towards the beginning.

        Returns
        -------
        timeframes_left : np.array
            Tuples of datetimes that indicate the start and end of each time
            frame left of the base break time
        timeframes_right : np.array
            Tuples of datetimes taht indicat the start and end of each time
            frame right of the base break time
        breaktimes : np.array
            The (new) breaktimes (in case they were re-ordered), otherwise the
            input breaktimes


        Reduces cci_breaks version breaktimes to the breaktimes that are not
        in skip_breaktimes

        Parameters
        -------
        indices_to_ignore : list
            Integeres of breaktimes that should be ignored

        Returns
        -------
         breaktimes : np.array
            The reduced break times


        Takes the objects break times and filters them according to the postion
        of the passed gp on the objects grid

        Parameters
        ----------
        gpi : int
            Filtering of the objects break times is done based on this GPI

        Returns
        -------
        filtered_breaktimes : np.array
            The list of filtered break times


        Turns datetime objects to strings

        Parameters
        -------
        datetimes : list or datetime
            Dates to convert

        Returns
        -------
        datestrings: list
            The converted dates


        Turns string objects to datetimes

        Parameters
        -------
        datestrings : list or str
            Strings to convert

        Returns
        -------
        datetimes: list
            The converted strings


        Checks if current break times and time frames are positional dependent

        Returns
        -------
        status : bool
            True if breaktimes are position dependent else False


        Return the maximum of break times (if there are multiple, contradicting
        conditions, select the condition that contains most values)

        Returns
        -------
        breaktimes : np.array
            The maximum breaktimes


        Get the according break time for the passed time frame

        Parameters
        ----------
        gpi : int
            GPI to get breaktime for
        timeframe : tuple
            timeframe to get breaktime for

        Returns
        -------
        breaktime : datetime or str
            Breaktime for the selected timeframe at the location


        Get the according time frame for the passed break time at the passed location

        Parameters
        ----------
        gpi : int or None
            GPI to get time frame for
        breaktime : datetime.datetime or str
            breaktime to get timeframe for

        Returns
        -------
        timeframe : tuple
            Time frame for the selected breaktime at the location


        Sorts the passed array of breaktimes or timeframes in ASCENDING ORDER

        Parameters
        ----------
        times : np.array
            Array of breaktimes, or array of lists of time frames.

        Returns
        -------
        sorted : np.array
            Sorted array of breaktimes or timeframes


    Use the passed cdf to quantize the passed observations respectively.

    Parameters
    -------
    cdf : FitCDF
        CDF object that is used to look up the quantiles for ds
    ds : pd.Series
        Values that are looked up
    n_bins : int, optional (default : None)
        Number of equally sized bins that the the quantized values are distributed into

    Returns
    -------
    df_binned : pd.DataFrame
        Dataframe with the quantile and bin for each passed value


        Predict the candidate for the adjust period using the reference for the
        adjust period and the regression model.

        Parameters:
        regress : HigherOrderRegression
            The regression object that contains the model to use to make predictions
        ds : pd.Series
            Reference observations that are used to create predictions with the model

        Returns
        -------
        pred : pd.Series
            The predicted candidate values


        Fit regression models of degree 1 or 2 to the data, based on the
        correlation find the type that fits the data best.

        Parameters
        -------
        group : int
            Group number (0 or 1 = before or after break) for which to find the
            model.
        poly_orders : list, optional (default: [1,2])
            List of poly degrees that are created and compared in terms of sse.
        thresR : float, optional (default : 0.8)
            Threshold for the linear correlation. If R_p is above this
            one, we select a linear model, else a non-linear one.
        thresR : float, optional (default : 0.05)
            Threshold for the linear correlation p value. If p is above this
            one, we select a non-linear model.

        Returns
        -------
        best_regress : HigherOrderRegression
            The regression obect of the model that was fitting best
        best_p : int
            The poly order of the best fitting model
        metric : dict
            the selected metric and how large it was for the best fitting model


        Fit regression models of degree 1, 2 and 3 to the data, based on the
        distribution of the residuals find the type that fits the data best.

        Parameters
        -------
        group : int
            Group number (0 or 1 = before or after break) for which to find the
            model.
        poly_orders : list, optional (default: [1,2,3])
            List of poly degrees that are created and compared in terms of sse.
        alpha : float, optional (default: 0.05)
            Compare the residual distributions and in case the metric got smaller
            check if the mean of the residuals got smaller and if it did, check
            if the decrease is statistically significant with p < alpha.

        Returns
        -------
        best_regress : HigherOrderRegression
            The regression obect of the model that was fitting best
        best_p : int
            The poly order of the best fitting model
        metric : dict
            the selected metric and how large it was for the best fitting model


        Resample the main data frame to the selected temporal resolution.
        Rescale then the reference column again.

        Parameters
        -------
        rescale : bool, optional (default: True)
            Re-scale the resampled time series, to correct for biases different
            to the original series.

        Returns
        -------
        df_adjust_resampled : pandas.DataFrame
            The resampled, re-scaled data frame.


        (Box) Plot of the (binned) residuals and the LOWESS fit

        Parameters
        -------
        box : bool, optional (default:True)
            Plot the quantile binned boxes
        ax : plt.Axes, optional (default: None)
            Use this axis object instead to create the plot in
        raw_plot : bool
            Create a plot without labels and legend


        Create a figure of the 2 regression models, save it if a path is passed.

        Parameters
        -------
        plot_both : bool, optional (default: True)
            Plot also model for the group that is predicted (model not used)
        image_path : str, optional (default: None)
            Path where the figure is stored at, if None is passed no fig is stored.
        axs : list, optional (default: None)
            To use preset axes, pass them here, must contain exactly 2 axes
        supress_title : bool, optional (default: False)
            Do not create plot title if this is set to True.

        Returns
        -------
        plot_coll_figure : plt.figure
            The figure object


        Create regression models for data in the the passed groups

        Parameters
        -------
        group : int
            Create the regression model for this group (0 = before, 1=after break)
        poly_order : int
            Order of the polynom that is fitted.

        Returns
        -------
        regress : HigherOrderRegression
            The regression model object


        Adjusts the candidate column for the selected period (before, after
        break time) relatively to the reference column, so that the regression
        properties fit, then recalculates the regression model with the new
        values.

        Parameters
        -------
        values_to_adjust : pd.Series
            Must contain 2 columns, 1 for the candidate and 1 for the reference
            The names of the columns must be the same as in self.df_adjust
            If None is passed, the init. passed values are used.
        use_separate_cdf : bool, optional (default: False)
            Do not use the CDF of the candidate training set but find another
            CDF for all values_to_adjust, to which the quantile corrections
            from the core frame are applied to.

        ------adjustment kwargs--------
        alpha : float, optional (default: 0.6)
            smoothing factor for adjustment from residuals or bins
        from_bins : bool, optional (default: False)
            Interpolate the bin means for the corrections and not the residuals
            directly.

        Returns
        -------
        candidate_adjusted : pd.Series
            The adjusted input values to adjust


        Plots a collection of the CDF for the predicted and the training candidate
        data (reference period) and the observed data (adjusted period).Plots
        are combined in one subplot here.

        Parameters
        -------
        plot_empirical : bool, optional (default: True)
            Add the observations as points to the plot of the theoretical, fitted CDF.
        ax : plt.axes, optional (default: None)
            An axes object to use instead of creating a new figure and ax.

        Returns
        -------
        fig : plt.figure or None
            The figure, if one was created, else None


        Plots a collection of the PDF for the predicted and the training candidate
        data (reference period) and the observed data (adjusted period). Plots
        are combined in one subplot here.

        Parameters
        -------
        plot_empirical : bool, optional (default: True)
            Add the observations as points to the plot of the theoretical, fitted CDF.
        ax : plt.axes, optional (default: None)
            An axes object to use instead of creating a new figure and ax.

        Returns
        -------
        fig : plt.figure or None
            The figure, if one was created, else None


        Plots a collection of the PDF for the predicted and the training candidate
        data (reference period) and the observed data (adjusted period). Plots
        are separated in subplots here.

        Parameters
        -------
        plot_empirical : bool, optional (default: True)
            Add the observations as points to the plot of the theoretical, fitted CDF.

        Returns
        -------
        fig : plt.figure or None
            The figure that was created


        (Box) Plot of the (binned) residuals and the LOWESS fit. Boxes are only
        shown when corrections come from the binned values.

        Parameters
        -------
        ax : plt.Axes, optional (default: None)
            Use this axis object instead to create the plot in
        raw_plot : bool
            Create a plot without labels and legend

        Returns
        -------
        fig : plt.figure or None
            The figure that was created


        Interpolate the residuals with a linear LOESS (all values not just bin
        means)

        Parameters
        -------
        alpha : float
            Between 0 and 1. Smoothing parameter for the LOWESS fit.
            The fraction of the data used when estimating each y-value.

        Returns
        -------
        f : interp1d
            Function to calculate adjustments


        Takes a set of values to adjust and applies corrections based on the
        corrections that were found for the frame from the residuals.
        The cdf of the candidate training part is used to apply the corrections to
        if not chosen to calculate a new CDF for the values to adjust.

        Parameters
        -------
        values_to_adjust : pd.Series
            Observations that are corrected
        use_separate_cdf : bool, optional (default: False)
            Do not use the CDF of the candidate training set but find a separate
            L-moments CDF for the values to adjust to apply the quantile corrections
            to.
        separate_cdf_types : list or None, optional (default: None)
            List of potential CDFs that are tested, if None are passed, all
            implemented ones are used. This should correspond with the Adjustment
            Class.

        Returns
        -------
        ds_adjusted : pd.Series
            The adjusted input values to adjust.


    Sort/rank the passed dataframe  by the 'name'-column, drop duplicate
    'name'-values if chosen.

    Parameters
    -------
    indata : pd.DataFrame
        Series of SM observations over time
    name : str, optional (default: 'can')
        Name of the column that the CDF is based on
    drop_dupes : bool, optional (default: False)
        Drop candidate duplicates (after freq calc), so that there are no duplicate
        CFs in the return data_cf.

    Returns
    -------
    data : pd.DataFrame
        The input ds with additional columns for count, freq, ranks
        Contains duplicates.
    data_cf : pd.DataFrame
        data sorted by CF (index), if chosen without duplicates


        Parameters
        ----------
        axs : matplotlib.Axes.axs, optional (default: None)
            Axes put the plot into
        raw_plot : bool, optional (default: False)
            Create a plot without title and interface, labels and legend.


        Plot the empirical distributions for CAN and REF, BEF and AFT break.

        Parameters
        -------
        groups : iterable, optional (default: [0,1])
            List of groups. eg. [0,1] = [HSP1, HSP2], [1]=HSP1 etc.
        axs : plt.Axes, optional (default: None)
            Use these axes to plot the groups
            Must have the same size as the selected list of groups
        raw_plot : bool, optional (default:False)
            Plot without labels, title and legend


        Plots a collection of the PDFs for before and after the break time for
        the selected variables.

        Parameters
        -------
        names : list, optional (default: ['can', 'ref', 'D'])
            list of parameters (can, ref or D) which are plotted
        cumulative : bool, optional (default: False)
            True to create sums of values.

        Returns
        -------
        figure_collection :
            The pdf compare collection


        Plot the mode for the chosen part.

        Parameters
        ----------
        period : str
            'before' or 'after' or 'diff' to plot the according period
        ax : plt.ax
            Use this axes object
        vlines : bool, optional (default: True)
            Plot the vertical .. lines between the categories
        scatter_style : tuple, optional (default:('.', 3, 'orange'))
            0 : marker type, 1 : marker size, 2 : marker color
        bar_style : tuple, optional (default:('/', 0.8, 'blue'))
            0 : bar hatch style, 1 : bar alpha, 2 : bar color
        vline_style : tuple, optional (default:('/', 0.8, 'blue'))
            0 : vlines color, 1 : main vlines linestyle, 2 : middle vlines linestyle
        label : str, optional (default: None)
            A label for the bars
        show_qc : bool, optional (default: False)
            Also plot an axis with the category number.


        Create 2 plots for the categories for data before and after the break

        Parameters
        -------
        image_path : str, optional (default: None)
            Directory where the image is stored to
        axs : list , optional (default: None)
            List of axes object
        names : list, optional (default: None)
            Names of vars to plot, if axs are passed, lengths must correspond
        supress_title : bool
            Do not create plot title


        Plot the pdfs of the passed data

        Parameters
        ----------
        data : pd.DataFrame
            DataFrame that contains the column with NAME
        style : str
            Color and list style
        ax : plt.axes
            Axes to add the plot
        name : str
            Name of the column in the dataframe
        dist_fit : stats.dist
            Distribution to fit to the data
        cumulative : bool
            True to create sums of values.

        Returns
        -------
        ax


        Transferts the percentils of the object to the candidate and reference
        data in the passed frame

        Parameters
        ----------
        group : int
            Group for which the percentiles shall be calculated
        calc_for : str
            Select whether the percentiles shall be calculated for the category
            middles ("mid"), or the category edges ("edge"), or the whole
            category ("cat") via the mean of all percentiles within the cat.
        frame : pd.DataFrame
            Frame from which the data is used for the percentile calculation

        Returns
        -------
        can_percentiles : np.array
            Candidate values at the percentiles
        ref_percentiles : np.array
            Reference values at the percentiles
        adj_percentiles : np.array
            Reference values at the percentiles


Specific for each child class of adjustment base, allows plotting


        Split a df by the cum freq in the index
        So that each part contains the same range of frequencies.
        The number of values in each group will vary, as there are not equally
        many values in each CF range.

        Parameters
        ----------
        df : pd.DataFrame
            Data over the normalized CF range (0-1)

        Returns
        -------
        parts : list
            List of parts for the data frame for each quantile category


        Split data frames in quantile range parts

        Parameters
        ----------
        data0_cf : pd.DataFrame
            Data before the break
        data1_cf : pd.DataFrame
            Data after the break

        Returns
        -------
        mq_cand_0 : list
            List of DataFrames for each quantile category for data before the break
        my_cand_1 : list
            List of DataFrames for each quantile category for data after the break


        Calculate category means for the median CF of each category and set
        values at 0 and 1 for interpolation,

        Parameters
        ----------
        mq_cand : list
            List of category DataFrames

        Returns
        -------
        D_mean : pd.DataFrame
            The model DataFrame


        Calculates frequencies and difference values for the selected quantiles

        Parameters
        ----------
        mq_cand0 : list
            List of sub-frames for the quantile categories for data before the break time
        mq_cand1 : list
            List of sub-frames for the quantile categories for data before the break time

        Returns
        -------
        d_mean0 : pandas.DataFrame
            Value of data before the break time
        d_mean1 : pandas.DataFrame
            Value of data after the break time


        Use the Adjustment class to adjust the candidate data of the object.

        Parameters
        -------
        values_to_adjust : pd.Series, optional
            Candidate values to which the adjustments are applied
        interpolation_method : str, optional (default : 'cubic')
            Specifies the kind of interpolation as a string
            ('linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
            'previous', 'next', where 'zero', 'slinear', 'quadratic' and 'cubic'
            refer to a spline interpolation of zeroth, first, second or third
            order; 'previous' and 'next' simply return the previous or next value
            of the point) or as an integer specifying the order of the spline
            interpolator to use.

        Returns
        -------
        adjusted_values : pd.Series
            The adjusted candidate values


        Calculate differences in the category means for the 2 groups

        Returns
        -------
        cat_diffs : pd.DataFrame
            Category differences between D0 and D1


        Adjust the candidate values based on SM adjustments per CF.
        Connection between adjustments (CF) and candidate values (dates) is
        done via the candidate ranks.

        Parameters
        -------
        interpolation_method : str, optional (default: 'cubic')
            Specifies the kind of interpolation as a string
            ('linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
            'previous', 'next', where 'zero', 'slinear', 'quadratic' and 'cubic'
            refer to a spline interpolation of zeroth, first, second or third
            order; 'previous' and 'next' simply return the previous or next value
            of the point) or as an integer specifying the order of the spline
            interpolator to use.

        Returns
        -------
        ds_adjusted : pd.Series
            The adjusted input series


        Calculate SM adjustements for for CFs of can_adj by interpolation the
        category means differences.

        Parameters
        -------
        interpolation_method : str, optional (default : 'cubic')
            Specifies the kind of interpolation as a string
            ('linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
            'previous', 'next', where 'zero', 'slinear', 'quadratic' and 'cubic'
            refer to a spline interpolation of zeroth, first, second or third
            order; 'previous' and 'next' simply return the previous or next value
            of the point) or as an integer specifying the order of the spline
            interpolator to use.
        Returns
        -------
        adjustments : pd.DataFrame
            DataFrame that contains the adjustment value for each CF and the
            respective rank of the candidate, that it will adjust.


        Crate a plot of the interpolated corrections

        Parameters
        -------
        ax : plt.Axes, optional (default: None)
            Use this axis object instead to create the plot in
        cf: bool, optional (default: True)
            Plot adjustments over CF, otherwise plot the adjustments over time.


        Take the input candidate and reference and returns only data for the
        time frame.

        Parameters
        -------
        time : (datetime.datetime, datetime.datetime) or datetime.datetime
            Start and end date of the subset that is extracted from the candidate
            and reference, or a single break time, then the according time frame
            is searched and used.
        dataframe : pd.DataFrame
            The dataframe from which the subset is taken

        Returns
        -------
        df_frame : pandas.DataFrame
            Data for the selected time frame, cut from self.df_original


        Extend the passed time frame across untestable parts in the initial test
        object. So that data at untestable break times is adjusted together with
        later break times.

        Parameters
        ------
        timeframe : np.array
            the current time frame that is being extended

        Returns
        -------
        adjustframe : tuple
            The new, extended time frame that is used for adjustment, not for
            modelling


        Extend the passed time frame across homogeneous break times of this object
        that have already been adjusted

        Parameters
        ------
        timeframe : np.array
            the current time frame that is being extended

        Returns
        -------
        timeframe : tuple
            The new, extended time frame for adjustment


        Create a plot of candidate, adjusted candidate and reference time series
        for the whole gpi time series.
        Calculate time series stats for comparison and save the plot

        Parameters
        -------
        save_path : str, optional (default: None)
            Path where the image is stored
        prefix: str, optional (default: None)
            Prefix for the name of the plot file to create.
        resample : str, optional (default: 'D')
            Resamples the time series to the given temporal resolution, does
            not influence the statistics, only visual
        ax : plt.axes, optional (default: None)
            Axes object, if this is passed the plot is a new subplot for
            the passed ax.
        legend : bool, optional (default: True)
            Set True to plot the legend for the current plot


        Show the frame figure plot if it was created

        Parameters
        -------
        save_path : str, optional (default: None)
            Path where the image is created.
        prefix : str, optional (default: None)
            Prefix for the name of the plot file to create.


        Saves the linear model plots collections to file or shows them

        Parameters
        ----------
        save_path : str
            Path where the image is created.
        prefix : str, optional (default: None)
            Prefix for the name of the plot file to create.

        Returns
        ----------
        model_figures : None or dict
            If no path is given, the dictionary with the figures is returned.


        Saves the time series stats plots to file or shows them

        Parameters
        ----------
        save_path : str, optional (default: None)
            Path where the image is created.
        prefix : str, optional (default: None)
            Prefix for the name of the plot file to create.


        Create the input dataframe for the current break time and time frame
        for the adjustment object. The input df may be different to the model frame
        data in cases where more than the frame data is used for adjustment.
        i.e where the model is used to adjust more values then were originally
        used to create the model.
        The original time frame (that indicates the range for modelling and testing
        is unchanged!)

        Parameters
        ----------
        breaktime : datetime
            Current break time that is being tested and adjusted
        extended_reference : bool
            If True, the time frame from the break time is extended across
            homogeneous break times
        adjust_group : int
            Group that is being adjusted (0 is before break, 1 is after break)

        Returns
        -------
        input_df : pd.DataFrame
            A subset of self.df_original that is cut to fit the range of
            values that should be used for adjustment and testing.


        Test for a break in the time series time frame (from the passed break time).
        Attempt to adjust a detected break and return the adjusted time series.

        Parameters
        ----------
        input_df : pd.DataFrame
            Subset of self.df_original, dataframe for testing and adjustment
        timeframe : list or None
            Start and end of the frame data used for testing and modelling
        breaktime : datetime
            Time of the possible break, for testing and time frame creation
        max_retries : int, optional (default: 5)
            Retries the adjustment multiple times, in case that the break was not
            removed.

        Returns
        -------
        adjust_obj : TsRelBreakAdjust
            Current adjustment object


        Add the results from the passed adjust object to the store of this class
        for the passed break time.

        Parameters
        ----------
        adjust_obj : TsRelBreakAdjust
            The adjustment object
        breaktime : datetime
            Break time for which the data is stored


        Add plots to the collections, if there are collections

        Parameters
        ----------
        adjust_obj : TsRelBreakAdjust
            The adjustment object for the current iteration
        i : int
            Counter for the break times that were already processed


        Iterate over all break times and test and adjust the candidate using
        the passed parameters.

        Parameters
        ----------
        extended_reference : bool, optional (default: True)
            If True, the time frame from the break time is extended across
            homogeneous break times

        Returns
        -------
        candidate_adjusted : pd.Series
            The multi break adjusted candidate series


        Check if the candidate has changed during adjustment or if adjustment
        did not have any impact.

        Returns
        -------
        has_changed : bool
            True if the adjustment changed the time series, False if not


    This function loads real observations from the ESA CCI SM v04.4 COMBINED dataset and the MERRA2 model.
    An additive/multiplicative break can be introduced by the user.
    GPI is a location identifier for a single cell point in the ESA CCI SM data grid.


Plot the amplitude heatmap, snr, errors, or the fit model.
        Parameters
        ----------
        lightcurve_aperture: 2D Boolean array, or None
        If not specified user the self.maxsignal_aperture will be used, if a user specified aperture is used it must be the same shape as the TPF.
        save: str, or None
            'filename.png' if you want to save the png of the plot
        figuresize: size of plot


Plot the amplitude heatmap, snr, errors, or the fit model.
        Parameters
        ----------
        frequencylist_index: int
        method: 'amp', 'snr', 'errors', 'model', 'residual'
        save: str, or None
            'filename.png' if you want to save the png of the plot
        figuresize: size of plot


Function to convert between HEALpix level 6 to Galactic l,b values


    returns the g and grp (input for selection function) for specific grvs and g-grp values
    Only takes scalar magnitudes!


returns grvs from g and grp


This comes from the GDR2 release paper if g-grp < 1.4


        This queries the completeness function for single values
        INPUT:
           g = G magnitude
           rp = RP magnitude
           l = Galactic Longitude
           b = Galactic Latitude
        OUTPUT:
           completeness = function between 0 and 1


        This queries the completeness function in array form
        INPUT:
           g = G magnitude
           rp = RP magnitude
           l = Galactic Longitude
           b = Galactic Latitude
        OUTPUT:
           completeness = function between 0 and 1


    uses the files from Ronald Drimmel (DR2 completeness from xmatch with 2MASS)
    to create a file that has the same structure as the completeness counts


this gives the magnitude at which p from (0,1) percent of the sources has been seen


This is for random downloaded format: stack files to one file and delete them afterwards


function that creates the matrix that contains the starcounts per hpx and mag bin


    returns the number by which to divide the source_id in order to get a hpx number of a specific hpx level
    INPUT:
       healpix_number: the healpix level, ranging from 0 to 12, an integer
    OUTPUT:
       the gaia source id factor to get a specific hpx dicretization


returns the number of pixels for a specific level


    A function that splits GDR2 ADQL queries into hpx chunks using the source_id and saves them in individual files as they arrive from the server into 'folder'.

    Input:
       service: which TAP service should be used. For choice there is one of the following:
           CDS - this is the vizier service
           ARI - this is the ARI Gaia service
           ESA - this is the ESA service (did not seem to work with pyvo so far)
           GDR2light - this is the GAVO service for Gaia DR2 light (only the main columns are included, bad if you need quality flags)
           GDR2mock - this is also hosted by GAVO and contains the GDR2 mock data which is a model Galaxy with a gmag limit of 20.7
           GeDR3mock - this is also hosted by GAVO and contains the GeDR3mock data which is a new Galaxy model with a gmag limit of 20.7
           GEDR3light - this is the GAVO service for Gaia EDR3 light including distances by Bailer-Jones+ (2020)
       hpx_level: into how many chunks the catalogue should be chopped.-1 = 1, 0 = 12, 1 = 48, 2 = 192 and so on
       folder: Where to store the downloaded data
       Select_what: the ADQL syntax for which rows one is interested, eg. 'parallax, ROUND(phot_g_mean_mag,1) as gmag'
       under_condition = the selection criteria, starting with 'AND' because it follows the healpix condition, for example 'AND phot_g_mean_mag<17 AND astrometric_excess_noise < 1'
       join_text: An additional entry after the table selection before the WHERE condition which can be used to specify crossmatches to other tables
       verbose: Since the queries can get timely you might want to get some feedback how far the download has proceeded
       test_1st_hpx_only: In order to not overload the services we should first test our query on a single hpx and in case it works and it is what we want we can run the other hpx by setting this to 'False'.


    Functions return 1-dimensional numpy arrays.
    Scalar inputs return length-1 arrays.
    DATA input: DIC and ALk in mol/kg, in situ temperature, pressure.


Geofm-bench main function.

    Args:
        cfg (DictConfig): main_config


Return the *first* file that ends with `suffix`; None if nothing found.


    Balances and selects indices from a segmentation dataset based on the specified strategy.

    Args:
    dataset : GeoFMDataset | GeoFMSubset
        The dataset from which to select indices, typically containing geospatial segmentation data.

    strategy : str
        The strategy to use for selecting indices. Options include:
        - "stratified": Proportionally selects indices from each class bin based on the class distribution.
        - "oversampled": Prioritizes and selects indices from bins with lower class representation.

    label_fraction : float, optional, default=1.0
        The fraction of labels (indices) to select from each class or bin. Values should be between 0 and 1.

    num_bins : int, optional, default=3
        The number of bins to divide the class distributions into, used for stratification or oversampling.

    logger : object, optional
        A logger object for tracking progress or logging messages (e.g., `logging.Logger`)

    ------

    Returns:
    selected_idx : list of int
        The indices of the selected samples based on the strategy and label fraction.

    other_idx : list of int
        The remaining indices that were not selected.


    Balances and selects indices from a regression dataset based on the specified strategy.

    Args:
    dataset : GeoFMDataset | GeoFMSubset
        The dataset from which to select indices, typically containing geospatial regression data.

    strategy : str
        The strategy to use for selecting indices. Options include:
        - "stratified": Proportionally selects indices from each bin based on the binned regression distributions.
        - "oversampled": Prioritizes and selects indices from bins with lower representation.

    label_fraction : float, optional, default=1.0
        The fraction of indices to select from each bin. Values should be between 0 and 1.

    num_bins : int, optional, default=3
        The number of bins to divide the regression distributions into, used for stratification or oversampling.

    logger : object, optional
        A logger object for tracking progress or logging messages (e.g., `logging.Logger`). If None, no logging is performed.

    ------

    Returns:
    selected_idx : list of int
        The indices of the selected samples based on the strategy and label fraction.

    other_idx : list of int
        The remaining indices that were not selected.


    Create a logger.
    Use a different log file for each process.


Convert time in seconds to time in hours, minutes and seconds
    e.g. 10239 -> (2, 50, 39)


    Computes the mean, standard deviation, maximum, and minimum values for a set of raster images.

    Parameters:
    split_file_path (str): Path to the CSV file containing the list of image files.
    data_root_path (str): Root directory where the image files are stored.

    Returns:
    tuple: A tuple containing the mean, standard deviation, maximum, and minimum values.


    This module provides a utility function for creating a multi-step learning rate scheduler.

    Functions:
        MultiStepLR(optimizer: Optimizer, total_iters: int, lr_milestones: list[float]) -> LRScheduler
            Creates a MultiStepLR scheduler with specified milestones and decay factor.

    Args:
        optimizer (Optimizer): The optimizer for which to schedule the learning rate.
        total_iters (int): The total number of iterations for training.
        lr_milestones (list[float]): A list of fractions representing the milestones at which the learning rate will be decayed.

    Returns:
        LRScheduler: A PyTorch learning rate scheduler that decays the learning rate at specified milestones.


Collate function for torch DataLoader
        args:
            batch: list of dictionaries with keys 'image' and 'target'.
            'image' is a dictionary with keys corresponding to modalities and values being torch.Tensor
            of shape (C, H, W) for single images, (C, T, H, W) where T is the temporal dimension for
            time series data. 'target' is a torch.Tensor
        returns:
            dictionary with keys 'image' and 'target'


check dimension (C, T, H, W) of data


check if data size is equal


Tracking the meta statistics/info for next processor.


Train the model for n_epochs then evaluate the model and save the best model.


Train model for one epoch.

        Args:
            epoch (int): number of the epoch.


Save the model checkpoint.

        Args:
            epoch (int): number of the epoch.
            is_final (bool, optional): whether is the final checkpoint. Defaults to False.
            is_best (bool, optional): wheter is the best checkpoint. Defaults to False.
            checkpoint (dict[str, dict  |  int] | None, optional): already prepared checkpoint dict. Defaults to None.


Load model from the checkpoint.

        Args:
            resume_path (str | pathlib.Path): path to the checkpoint.


Compute the loss.

        Args:
            logits (torch.Tensor): logits from the model.
            target (torch.Tensor): target tensor.

        Raises:
            NotImplementedError: raise if the method is not implemented.

        Returns:
            torch.Tensor: loss value.


Update the best checkpoint according to the evaluation metrics.

        Args:
            eval_metrics (dict[float, list[float]]): metrics computed by the evaluator on the validation set.
            epoch (int): number of the epoch.


Compute logging metrics.

        Args:
            logits (torch.Tensor): logits output by the decoder.
            target (torch.Tensor): target tensor.

        Raises:
            NotImplementedError: raise if the method is not implemented.

        Returns:
            dict[float, list[float]]: logging metrics.


Log the information.

        Args:
            batch_idx (int): number of the batch.
            epoch (_type_): number of the epoch.


Reset the training stats and metrics.


Compute logging metrics.
        For multi-label:
        - Uses sigmoid activation and top-k selection.
        For single-class:
        - Uses argmax and converts predictions to one-hot encoding.

        Args:
            logits (torch.Tensor): logits from the decoder.
            target (torch.Tensor): target tensor.


Compute the loss.

        Args:
            logits (torch.Tensor): logits from the decoder.
            target (torch.Tensor): target tensor.

        Returns:
            torch.Tensor: loss value.


Compute logging metrics.

        Args:
            logits (torch.Tensor): loggits from the decoder.
            target (torch.Tensor): target tensor.


Compute logging metrics.

        Args:
            logits (torch.Tensor): logits from the decoder.
            target (torch.Tensor): target tensor.


Forward function for feature maps before classifying each pixel with
        ``self.cls_seg`` fc.

        Args:
            inputs (list[Tensor]): List of multi-level img features.

        Returns:
            feats (Tensor): A tensor of shape (batch_size, self.channels,
                H, W) which is feature map for last layer of decoder head.


Compute the segmentation output.

        Args:
            img (dict[str, torch.Tensor]): input data structured as a dictionary:
            img = {modality1: tensor1, modality2: tensor2, ...}, e.g. img = {"optical": tensor1, "sar": tensor2}.
            with tensor1 and tensor2 of shape (B C T=1 H W) with C the number of encoders'bands for the given modality.
            output_shape (torch.Size | None, optional): output's spatial dims (H, W) (equals to the target spatial dims).
            Defaults to None.

        Returns:
            torch.Tensor: output tensor of shape (B, num_classes, H', W') with (H' W') coressponding to the output_shape.


Compute the segmentation output for multi-temporal data.

        Args:
            img (dict[str, torch.Tensor]): input data structured as a dictionary:
            img = {modality1: tensor1, modality2: tensor2, ...}, e.g. img = {"optical": tensor1, "sar": tensor2}.
            with tensor1 and tensor2 of shape (B C T H W) with C the number of encoders'bands for the given modality,
            and T the number of time steps.
            output_shape (torch.Size | None, optional): output's spatial dims (H, W) (equals to the target spatial dims).
            Defaults to None.

        Returns:
            torch.Tensor: output tensor of shape (B, num_classes, H', W') with (H' W') coressponding to the output_shape.


Forward function for change detection.


Run kNN predictions with optional multi-label Top-M strategy.


Adapter for the number of channels of the input features.

        Args:
            features (list[torch.Tensor]): list of features of shape (B C T H W)
            from different layers of the encoder.

        Returns:
            list[torch.Tensor]: list of adapted features of shape (B C' T H W)


    Split the input image tensor into four quadrants based on the integer i.
    To use if Pastis data does not fit in your GPU memory.
    Returns the corresponding quadrant based on the value of i


Download the dataset.

        Raises:
            NotImplementedError: raise if the method is not implemented


Adapted from: https://cloud.google.com/storage/docs/samples/storage-transfer-manager-download-bucket#storage_transfer_manager_download_bucket-python
    Download all of the blobs in a bucket, concurrently in a thread pool.

    The filename of each blob once downloaded is derived from the blob name and
    the `destination_directory `parameter.

    Directories will be created automatically as needed, for instance to
    accommodate blob names that include slashes.


Decompress a zip file with a progress bar and remove the symlink.


Prithvi requires a specific image size, so we reshape before transforming.


        Finds all filenames in data_path and all its subdirs.
        Loads them into a numpy array of samples.
        Only looks 1 subdirectory deep (e.g. doesn't look recursively
        in directories of directories).

        Args:
            self: self
            data_path: string filepath where data is stored
        Returns:
            numpy.array of loaded samples from data_path and all of its subdirs


Right pads or crops tensor to GRID_SIZE.


Load the encoder weights.

        Args:
            logger (Logger): logger to log the information.

        Raises:
            NotImplementedError: raise if the method is not implemented.


Print warning messages for missing or incompatible parameters

        Args:
            missing (dict[str, torch.Size]): list of missing parameters.
            incompatible_shape (dict[str, tuple[torch.Size, torch.Size]]): list of incompatible parameters.
            logger (Logger): logger to log the information.


Foward pass of the encoder.

        Args:
            x (dict[str, torch.Tensor]): encoder's input structured as a dictionary:
            x = {modality1: tensor1, modality2: tensor2, ...}, e.g. x = {"optical": tensor1, "sar": tensor2}.
            If the encoder is multi-temporal (self.multi_temporal==True), input tensor shape is (B C T H W) with C the
            number of bands required by the encoder for the given modality and T the number of time steps. If the
            encoder is not multi-temporal, input tensor shape is (B C H W) with C the number of bands required by the
            encoder for the given modality.
        Raises:
            NotImplementedError: raise if the method is not implemented.

        Returns:
            list[torch.Tensor]: list of the embeddings for each modality. For single-temporal encoders, the list's
            elements are of shape (B, embed_dim, H', W'). For multi-temporal encoders, the list's elements are of shape
            (B, C', T, H', W') with T the number of time steps if the encoder does not have any time-merging strategy,
            else (B, C', H', W') if the encoder has a time-merging strategy (where C'==self.output_dim).


Download the model if the weights are not already downloaded.


Sine-cosine positional embeddings from MoCo-v3, adapted back to 1d

    Returns positional embedding of shape (1, N, D)


Sine-cosine positional embeddings as used in MoCo-v3

    Returns positional embedding of shape (1, N, D) where N = W*H


Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
    Implementation from timm: https://github.com/huggingface/pytorch-image-models/blob/main/timm/layers/drop.py


Crop and resize an image

        :param img: Image to crop and resize
        :param flip: Whether to flip the image
        :return: Flipped image (if flip = True)


Crop and resize an image

        :param img: Image to crop and resize
        :param crop_coords: Coordinates of the crop (top, left, h, w)
        :param target_size: Coordinates of the resize (height, width)
        :return: Cropped and resized image


Truncated depth standardization

        :param depth: Depth map
        :param thresh: Threshold
        :return: Robustly standardized depth map


Convert instances dict to list of lists where each list takes the form:
        [xmin, ymin, xmax, ymax, class_name, score]


Crop and resize bounding boxes

        Args:
            bboxes: Bounding boxes to crop and resize
            crop_coords: Coordinates of the crop (top, left, h, w)
            orig_size: Size of the original image

        Returns:
            Cropped and resized bounding boxes


Convert bounding boxes to a string

        Args:
            bboxes: Bounding boxes

        Returns:
            String representation of the bounding boxes


        Initialize parts of embedding module that are dependent on dimension of tokens.
        Should be called when setting up FourM.

        Args:
            dim_tokens: Dimension of tokens
            init_std: Standard deviation of init


        Forward pass through embedding module, transforming sequence of ids to sequence of embeddings.
        Creates corresponding modality and positional embeddings and adds them to the dict.

        Args:
            d (dict[str, torch.Tensor]): Modality dict with at least the following keys:
                - 'tensor' (torch.Tensor): Input token sequence for each batch. Shape (B, L) where B is the batch size and L is the sequence length.
                - 'input_mask' (torch.Tensor): Mask for valid tokens in the input sequence (set to 0 for valid tokens and 1 otherwise). Shape (B, L).

        Returns:
            dict[str, torch.Tensor]: Modality dict with added keys:
                - 'x' (torch.Tensor): Embedded token sequence. Shape (B, L, D) where D is the embedding dimension.
                - 'emb' (torch.Tensor): Sum of positional and modality embeddings for the input sequence. Shape (B, L, D).


        Initialize parts of module that are dependent on dimension of tokens.
        Should be called when setting up FourM.

        Args:
            dim_tokens: Dimension of tokens
            init_std: Standard deviation of init


        Forward pass through embedding module, transforming image tokens to a sequence of embeddings.
        Creates corresponding modality and positional embeddings and adds them to the dict.

        Args:
            d (torch.Tensor, dict[str, torch.Tensor]): Modality dict with at least the following key:
                - 'tensor' (torch.Tensor): Input image tokens for each batch. Shape (B, H, W) where B is the batch size, and H, W are height and width of the tokenized image.                - 'input_mask' (torch.Tensor): Mask for valid tokens in the input sequence (set to 0 for valid tokens and 1 otherwise). Shape (B, L).

        Returns:
            dict[str, torch.Tensor]: Modality dictionary with added keys:
                - 'x' (torch.Tensor): Embedded token sequence. Shape (B, H*W, D).
                - 'emb' (torch.Tensor): Sum of positional and modality embeddings for the input sequence. Shape (B, H*W, D).


        Initialize parts of encoder that are dependent on dimension of tokens.
        Should be called when setting up FourM.

        Args:
            dim_tokens: Dimension of tokens
            init_std: Standard deviation of init


        Forward pass through embedding module, transforming image to sequence of tokens.
        Creates corresponding modality and positional embeddings and adds them to the dict.

        Args:
            d (torch.Tensor, dict[str, torch.Tensor]): Modality dict with at least the following key:
                - 'tensor' (torch.Tensor): Input image for each batch. Shape (B, C, H, W) where B is the batch size, C is the number of channels, and H, W are height and width of the image.

        Returns:
            dict[str, torch.Tensor]: Modality dict with added keys:
                - 'x' (torch.Tensor): Embedded token sequence. Shape (B, (H / PH) * (W / PW), D), where PH and PW are the patch sizes
                - 'emb' (torch.Tensor): Sum of positional and modality embeddings for the input sequence. Shape (B, (H / PH) * (W / PW), D)


        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
        images. This method is also adapted to support torch.jit tracing.

        Adapted from:
        - transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding
        - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
        - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211


        Forward pass through embedding module, transforming sequence of ids to sequence of embeddings.
        Creates corresponding modality and positional embeddings and adds them to the dict.

        Args:
            d (Dict[str, torch.Tensor]): Modality dict, with at least the following keys:
                - 'tensor' (torch.Tensor): Token sequence for each batch. Shape (B, L) where B is the batch size and L is the sequence length.
                - 'target_mask' (torch.Tensor): Mask for valid tokens in the target sequence (set to 0 for valid tokens and 1 otherwise). Shape (B, L).

        Returns:
            Dict[str, torch.Tensor]: Modality dict with added keys:
                - 'x' (torch.Tensor): Embedded token sequence. Shape (B, L, D) where D is the embedding dimension.
                - 'emb' (torch.Tensor): Sum of positional and modality embeddings for the target sequence. Shape (B, L, D).
                - 'ids' (torch.Tensor): Original token sequence from input dict. Shape (B, L).


        Forward pass through output projection layer, transforming sequence of embeddings to logits.

        Args:
            x (torch.Tensor): Output tokens from the decoder. Shape (B, M, D)

        Returns:
            torch.Tensor: Logits for each token in the sequence. Shape (B, M, V)


        Forward pass through the embedding module, transforming tokenized spatial inputs to embeddings.
        Creates corresponding modality and positional embeddings and adds them to the dict.

        Args:
            d (Dict[str, torch.Tensor]): Modality dict, with at least the following key:
                - 'tensor' (torch.Tensor): Modality tokens for each batch (e.g. from tokenized images). Shape (B, H, W) where B is the batch size, H and W are height and width after tokenization.

        Returns:
            Dict[str, torch.Tensor]: Modality dict with added keys:
                - 'x' (torch.Tensor): Embedded token sequence, which is replaced by mask tokens in the 4M decoder. Shape (B, H*W, D) where D is the embedding dimension.
                - 'emb' (torch.Tensor): Sum of positional and modality embeddings for the token sequence. Shape (B, H*W, D).
                - 'ids' (torch.Tensor): Reshaped token sequence from input dict, flattened in the spatial dimensions. Shape (B, H*W).


Weight initialization following MAE's initialization scheme


        Forward pass of the model.

        Args:
            d (dict, torch.Tensor): Dict of inputs or input tensor with shape (B, C, H, W)

            Alternatively, keyword arguments with modality=tensor.

        Returns:
            list[torch.Tensor]: List of transformer layer outputs. Shape (B, L, D).


    Update patch embeddings weights for each provided modality by selecting the pretrained weights for each band.
    Args:
         model (TerraMindViT): model
         bands (dict[str, list]): Bands with format {<modality>: [<band names>]}
         pretrained_bands (dict[str, list]): Pretrained bands of the model with format {<modality>: [<band names>]}


Manually filter pre-trained weights for TerraMind ViT to enable strict weight loading.


    Args:
        x: (B, H, W, C)
        window_size (int): window size

    Returns:
        windows: (num_windows*B, window_size, window_size, C)


    Args:
        windows: (num_windows*B, window_size, window_size, C)
        window_size (int): Window size
        H (int): Height of image
        W (int): Width of image

    Returns:
        x: (B, H, W, C)


        Args:
            x: input features with shape of (num_windows*B, N, C)
            mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None


initialize the base weights and dynamic mlp weights


    Adjusts the keys in the state dictionary by replacing 'backbone.backbone' prefix with 'backbone'.

    Args:
        state_dict (dict): Original state dictionary with 'backbone.backbone' prefixes.

    Returns:
        dict: Modified state dictionary with corrected prefixes.


        Find and load pretrained SatlasPretrain weights, based on the model_identifier argument.
        Option to load pretrained FPN.


Wrapper function to convert luminosity from erg/s to 10^50 erg/s.


:return: maximum non-rotating mass in solar masses (Mtov) for the equation of state


:return: maximum speed of sound in units of c


        :param mass: mass array in solar masses
        :return: return radius in meters


        :param central_pressure:
        :return: mass in solar masses and dimensionless tidal deformability


        :param central_pressure_array: array of central pressure in SI units
        :param maximum_mass_lower_limit: 2.01 solar masses, Throw out EOS's that are below this value.
        Users should enforce this at the prior level.
        :return: dimensionless tidal deformability


        :param central_pressure: central pressure in SI units
        :param mass: neutron star masses in solar masses
        :param maximum_mass_limit:
        :return: lambda for the given mass array


    Helper function to setup the plotting result

    :param model: model string or model function
    :param model_kwargs: keyword arguments passed to the model
    :param parameters: parameters to plot
    :param transient: transient object
    :return: a tuple of model, parameters, and result


    Plot a lightcurve for a given model and parameters

    :param transient: transient object
    :param parameters: parameters to plot
    :param model: model string or model function
    :param model_kwargs: keyword arguments passed to the model
    :return: plot_lightcurve


    Plot a multiband lightcurve for a given model and parameters

    :param transient: transient object
    :param parameters: parameters to plot
    :param model: model string or model function
    :param model_kwargs: keyword arguments passed to the model
    :return: plot_multiband_lightcurve


    Plot evolution parameters for a given evolving_magnetar result

    :param result: redback result
    :param random_models: number of random models to plot
    :return: fig and axes


    Plot a spectrum for a given model and parameters

    :param model: Model string for a redback model
    :param parameters: dictionary of parameters/alongside model specific keyword arguments.
        Must be one set of parameters. If you want to plot a posterior prediction of the spectrum,
        call this function in a loop.
    :param time_to_plot: Times to plot (in days) the spectrum at.
        The spectrum plotted will be at the nearest neighbour to this value
    :param axes: None or matplotlib axes object if you want to plot on an existing set of axes
    :param kwargs: Additional keyword arguments used by this function.
    :param colors_list: List of colors to use for each time to plot. Set randomly unless specified.
    :return: matplotlib axes


    Plot the Gaussian Process lightcurves

    :param transient: A transient object
    :param gp_output: The output of the fit_gp function
    :param axes: axes, ideally you should be passing the axes from the plot_data methods
    :param band_colors: a dictionary of band colors; again ideally you should be passing the band_colors from the plot_data methods
    :return: axes object with the GP lightcurves plotted


    Fit a Gaussian Process to the temperature and radius data

    :param data: DataFrame containing the temperature and radius data output of the transient.estimate_bb_params method.
    :param kernelT: george kernel for the temperature
    :param kernelR: george kernel for the radius
    :param plot: Whether to make a two-panel plot of the temperature and radius GP evolution and the data
    :param kwargs: Additional keyword arguments
    :param inflate_errors: If True, inflate the errors by 20%, default is False
    :return: Temperature and radius GP objects and plot fig and axes if requested


    Generates new transient data based on Gaussian Process (GP) predictions for the given time array
    and transient object. Depending on the data mode of the transient object
    (e.g., 'flux_density', 'flux', 'magnitude', or 'luminosity'), this function updates the data
    accordingly, adjusting errors and scaling by frequency if necessary.

    :param gp_out: The GP output object containing the Gaussian Process model, scaled data,
                   and other related attributes.
    :type gp_out: object
    :param t_new: Array of new time values for which GP predictions are to be generated.
    :type t_new: array-like
    :param transient: The transient object containing the original observation data and related
                      properties such as data mode and unique frequencies or bands.
    :type transient: object
    :param kwargs: Additional parameters to modify behavior, such as:

                   - **inflate_y_err** (bool): Flag to indicate whether to inflate GP errors.
                   - **error** (float): Multiplier for adjusting GP error inflation.

    :return: A new transient object with data updated using GP predictions.
    :rtype: object


    Find the nearest value in an array to a given value.

    :param array: array to search
    :param value: value to search for
    :return: array element closest to value and index of that element


Download the pointing tables from zenodo.


    Convert redback data band names to sncosmo compatible band names

    :param bands: List of bands.
    :type bands: list[str]
    :param warning_style: How to handle warnings. 'soft' will raise a warning, 'hard' will raise an error.
    :return: An array of sncosmo compatible bandnames associated with the given bands.
    :rtype: np.ndarray


    Check the validity of the kwargs passed to a model

    :param kwargs:
    :return:


    Wrapper for citation function to allow functions to have a citation attribute
    :param r: proxy argument
    :return: wrapped function


    Calculate the effective width in Hz from the effective wavelength in Angstrom

    :param effective_width: effective_width in Angstrom
    :param effective_wavelength: effective wavelength in Angstrom
    :return: effective width in Hz


    Calculate the fall back timescale for a SMBH disrupting a stellar mass object
    :param binding_energy_const:
    :param mbh_6: SMBH mass in 10^6 solar masses
    :param stellar_mass: stellar mass in solar masses
    :return: fall back time in seconds


    Calculate the normalisation for smoothly joining two models together at a reference time.

    :param unique_frequency: An array of unique frequencies. Can be None in which case we assume there is only one normalisation.
    :param model_1: must be redback model with a normalisation parameter
    :param model_2: any redback model
    :param tref: time which transition from model_1 to model_2 takes place
    :param model_1_dict: dictionary of parameters and values for model 1
    :param model_2: dictionary of parameters and values for model 1
    :return: normalisation, namedtuple corresponding to the normalisation for the specific frequency.
    Could be bolometric luminosity, magnitude, or frequency


    Convert flux density from erg/s/cm^2/Hz to erg/s/cm^2/Angstrom.

    :param f_nu: flux density in erg/s/cm^2/Hz
    :param wavelength_A: wavelength in Angstrom
    :return: flux density in erg/s/cm^2/Angstrom


    :param wavelength: wavelength in Angstrom
    :return: frequency in Hertz


    :param frequency: frequency in Hertz
    :return: wavelength in Angstrom


    Perform k-correction

    :param frequency: observer frame frequency
    :param redshift: source redshift
    :param time: observer frame time
    :return: k-corrected frequency and source frame time


    Convert MJD to JD

    :param mjd: mjd time
    :return: JD time


    Convert JD to MJD

    :param jd: jd time
    :return: MJD time


    Convert JD to date

    :param jd: jd time
    :return: date


    Convert MJD to date

    :param mjd: mjd time
    :return: data


    Convert date to JD

    :param year:
    :param month:
    :param day:
    :return: JD time


    Convert date to MJD

    :param year:
    :param month:
    :param day:
    :return: MJD time


    Calculate the deceleration timescale for an afterglow

    :param e0: kinetic energy of afterglow
    :param g0: lorentz factor of afterglow
    :param n0: nism number density
    :return: peak time in seconds


    Calculate flux density from AB magnitude assuming monochromatic AB filter

    :param magnitudes:
    :return: flux density


    Calculate AB magnitude from flux density assuming monochromatic AB filter

    :param fluxdensity:
    :return: AB magnitude


    Calculate flux density from Vega magnitude assuming Vega filter

    :param magnitudes:
    :param zeropoint: Vega zeropoint for a given filter in Jy
    :return: flux density in mJy


    Calculate Vega magnitude from flux density assuming Vega filter

    :param fluxdensity: in mJy
    :param zeropoint: Vega zeropoint for a given filter in Jy
    :return: Vega magnitude


    Function to compute the error associated with the flux measurement of the
    transient source, computed based on the observation databse determined
    five-sigma depth.

    Parameters:
    -----------
        fiveSigmaDepth: float
            The magnitude at which an exposure would be recorded as having
            an SNR of 5 for this observation.
        bandflux_ref: float
            The total flux that would be transmitted through the chosen
            bandfilter given the chosen reference system.
    Returns:
    --------
        bandflux_error: float
            The error associated with the computed bandflux.


    Convert apparent magnitude to absolute magnitude assuming planck18 cosmology.

    :param app_magnitude: AB/Vega apparent magnitude
    :param redshift: redshift
    :param kwargs: Additional kwargs
    :param cosmology: Cosmology object if not using default
    :return: absolute magnitude


    Convert absolute magnitude to apparent

    :param magnitude: AB absolute magnitude
    :param distance: Distance in parsecs


checks that an element exists on a website, and provides an exception


    Calculate flux density error from magnitude error

    :param magnitude: magnitude
    :param magnitude_error: magnitude error
    :param reference_flux: reference flux density
    :param magnitude_system: magnitude system
    :return: Flux density error


    Calculate flux error from magnitude error

    :param magnitude: magnitude
    :param magnitude_error: magnitude error
    :param reference_flux: reference flux density
    :return: Flux error


    Bands to zero point

    :param bands: list of bands
    :return: zeropoint for magnitude to flux density calculation


    Convert magnitude to flux

    :param magnitude: magnitude
    :param bands: bandpass
    :return: flux


    Function to propagate the flux error to the mag system.

    Parameters:
    -----------
        bandflux: float
            The total flux transmitted through the bandfilter and recorded by
            the detector.
        bandflux_error: float
            The error on the flux measurement from the measured background
            noise, in this case, the five sigma depth.

    Outputs:
    --------
        magnitude_error: float-scalar
            The flux error propagated into the magnitude system.


    Convert flux to magnitude

    :param flux: flux
    :param bands: bandpass
    :return: magnitude


    Looks up the reference flux for a given band from the filters table.

    :param bands: List of bands.
    :type bands: list[str]
    :return: An array of reference flux associated with the given bands.
    :rtype: np.ndarray


    Converts a list of bands into an array of frequency in Hz

    :param bands: List of bands.
    :type bands: list[str]
    :return: An array of frequency associated with the given bands.
    :rtype: np.ndarray


    Converts a list of bands into an array of effective width in Hz

    :param bands: List of bands.
    :type bands: list[str]
    :return: An array of effective width associated with the given bands.
    :rtype: np.ndarray


    Converts a list of frequencies into an array corresponding band names

    :param frequency: List of bands.
    :type frequency: list[str]
    :return: An array of bandnames associated with the given frequency.
    :rtype: np.ndarray


    Calculate credible intervals from samples

    :param samples: samples array
    :param interval: credible interval to calculate
    :return: lower_bound, upper_bound, median


    Calculates the median and error bars for a one-dimensional sample array.

    This function computes the median, lower, and upper error bars based on the
    specified quantiles. It returns these values along with a formatted string
    representation.

    :param samples: An array of numerical values representing the sample data. The
        input must not be empty.
    :type samples: list or numpy.ndarray
    :param quantiles: A tuple specifying the lower and upper quantile values. For
        example, (0.16, 0.84) represents the 16th percentile as the lower quantile
        and the 84th percentile as the upper quantile. Default is (0.16, 0.84).
    :type quantiles: tuple
    :param fmt: A format string for rounding the results in the formatted output.
        Default is '.2f'.
    :type fmt: str
    :return: A namedtuple containing the median, lower error bar, upper error bar,
        and a formatted string representation.
    :rtype: MedianErrorBarResult
    :raises ValueError: If the input `samples` array is empty.


    Kernel Density Estimation with Scipy

    :param x: samples
    :param bandwidth: bandwidth of the kernel
    :param kwargs: Any extra kwargs passed to scipy.kde
    :return: gaussian kde object


    Cumulative distribution function

    :param x: samples
    :param plot: whether to plot the cdf
    :param args: extra args passed to plt.plot
    :param kwargs: extra kwargs passed to plt.plot
    :return: x, y or plot


    Bin TimeTaggedEvents into bins of size bin_size

    :param ttes: time tagged events
    :param bin_size: bin sizes
    :return: times and counts in bins


    Find the path of some data in the package

    :param path:
    :return:


    Uses Barnes+2016 and interpolation to calculate the r-process thermalisation efficiency
    depending on the input mass and velocity
    :param mej: ejecta mass in solar masses
    :param vej: initial ejecta velocity as a fraction of speed of light
    :return: av, bv, dv constants in the thermalisation efficiency equation Eq 25 in Metzger 2017


    Uses interpolation from Tanaka+19 to calculate
    the electron fraction based on the temperature independent gray opacity
    :param kappa: temperature independent gray opacity
    :return: electron_fraction