Compute redshift bin edges.

        Returns
        -------
        array floats
            We devide the cosmic time history of the Universe in equally spaced
            bins of cosmic time of self.MODEL['delta_t'] (100 Myr default) an compute the
            redshift corresponding to edges of these bins.


Compute redshift bin centers.

        Returns
        -------
        array floats
            We devide the cosmic time history of the Universe in equally spaced
            bins of cosmic time of self.MODEL['delta_t'] (100 Myr default) an compute the
            redshift corresponding to center of these bins.


Compute the cosmic star formation rate density.

        This is an abstract method that must be implemented by subclasses.
        The implementation should calculate and return the cosmic star formation
        rate density at the given redshift(s).

        Parameters
        ----------
        z : float or array-like
            Cosmological redshift.

        Returns
        -------
        float or array-like
            The cosmic star formation rate density at the given redshift(s).

        Raises
        -------
            NotImplementedError: If the subclass does not implement this method.


Return the mean metallicity at redshift z.

        This is an abstract method that must be implemented by subclasses.
        The implementation should calculate and return the mean metallicity
        at the given redshift(s).

        Parameters
        ----------
        z : float or array-like
            Cosmological redshift.

        Returns
        -------
        float or array-like
            The mean metallicity at the given redshift(s).

        Raises
        -------
            NotImplementedError: If the subclass does not implement this method.


Compute the star formation rate fraction (fSFR) at a given redshift
        using the specified metallicity bins.

        This is an abstract method that must be implemented by subclasses.
        The implementation should calculate and return the fractional SFR per
        metallicity bins at the provided redshift (z).

        Parameters
        ---------
        z : float or array-like
            The redshift(s) at which to compute the star formation rate.
        metallicity_bins : list or array-like
            The metallicity bin boundaries or labels used in the computation to
            account for different metallicity contributions.

        Returns
        -------
        float or array-like
            The calculated star formation rate at the given redshift(s) and
            metallicity bins in Msun/yr.

        Raises:
            NotImplementedError: If the subclass does not implement this method.


Distribute the SFR over the metallicity bins using the CDF

        Parameters
        ----------
        cdf_func : function
            The cumulative density function to use.
        metallicity_bins : array
            Metallicity bins edges in absolute metallicity.

        Returns
        -------
        ndarray
            Fraction of the SFR in the given metallicity bin at the given redshift.


The cosmic star formation rate density at a given redshift.

        Follows the Madau & Dickinson (2014) cosmic star formation rate
        density formula.

        Parameters
        ----------
        z : float or np.array
            Cosmological redshift.

        Returns
        -------
        float or array
            The cosmic star formation rate density at the given redshift.


Return the standard deviation of the log-normal metallicity
        distribution

        Either recognised the strings "Bavera+20" (sigma=0.5)
        or "Neijssel+19" (sigma=0.39) or a float value.

        Returns
        -------
        float
            The standard deviation of the log-normal metallicity distribution.


The mean metallicity at a given redshift

        Follows Madau & Fragos (2017) mean metallicity evolution

        Parameters
        ----------
        z : float or np.array
            Cosmological redshift.

        Returns
        -------
        float or array
            The mean metallicity at the given redshift.


Fraction of the SFR at a given redshift z in a given metallicity
        bin as described in Bavera et al. (2020).

        Parameters
        ----------
        z : np.array
            Cosmological redshift.
        metallicity_bins : array
            Metallicity bins edges in absolute metallicity.

        Returns
        -------
        ndarray
            Fraction of the SFR in the given metallicity bin at the given
            redshift.


Calculate the mean metallicity at a given redshift

        Overwrites the mean_metallicity method of MadauBase class.

        Parameters
        ----------
        z : float or array-like
            Cosmological redshift.

        Returns
        -------
        float or array-like
            The mean metallicity at the given redshift(s).


Fraction of the SFR at a given redshift z in a given metallicity bin
        as described in Neijssel et al. (2019).

        Overwrites the fSFR method of MadauBase class.

        Parameters
        ----------
        z : np.array
            Cosmological redshift.
        metallicity_bins : array
            Metallicity bins edges in absolute metallicity.

        Returns
        -------
        ndarray
            Fraction of the SFR in the given metallicity bins at the
            given redshift.


Load IllustrisTNG SFR dataset into the class.

        Parameters
        ----------
        verbose : bool, optional
            Print information about the data loading.


The cosmic star formation rate density at a given redshift.

        Parameters
        ----------
        z : float or np.array
            Cosmological redshift.

        Returns
        -------
        float or array
            The cosmic star formation rate density at the given redshift(s).


Calculate the mean metallicity at a given redshift

        Parameters
        ----------
        z : float or array-like
            Cosmological redshift.

        Returns
        -------
        float or array-like
            The mean metallicity at the given redshift(s).


Calculate the fractional SFR as a function of redshift and
        metallicity bins.

        Parameters
        ----------
        z : float or array-like
            Cosmological redshift.
        metallicity_bins : array
            Metallicity bins edges in absolute metallicity.

        Returns
        -------
        ndarray
            Fraction of the SFR in the given metallicity bin at the given redshift.


Load the data from the Chruslinska+21 models.
        Transforms the data to the format used in the classes.

        Parameters
        ----------
        verbose : bool, optional
            Print information about the data loading.


Convert the oxygen to hydrogen abundance ratio to absolute metallicity

        Parameters
        ----------
        FOH : float or array-like
            The oxygen to hydrogen abundance ratio.

        Returns
        -------
        float or array-like
            The absolute metallicity.


Calculate the fractional SFR as a function of redshift and metallicity bins

        Parameters
        ----------
        z : float or array-like
            Cosmological redshift.
        metallicity_bins : array
            Metallicity bins edges in absolute metallicity.

        Returns
        -------
        ndarray
            Fraction of the SFR in the given metallicity bin at the given redshift.


Load the redshift data from a Chruslinsk+21 model file.

        Returns
        -------
        time : array
            the center of the time bins
        redshift : array
            the redshifts corresponding to the time bins
        delt : array
            the width of the time bins


Read the sub-model data from the file

        The data structure is as follows:
        - mass per unit (comoving) volume formed in each z (row) - FOH (column) bin

        Returns
        -------
        array
            Mass formed per unit volume in each redshift and FOH bin


Interpolate the cosmic star formation rate density at the given redshift(s)

        Parameters
        ----------
        z : float or array-like
            Cosmological redshift.

        Returns
        -------
        float or array-like
            The cosmic star formation rate density at the given redshift(s).


Load the data from the Zavala+21 models
        Transforms the data to the format used in the classes.


Calculate the SFR per metallicity bin at a given redshift(s)

    Parameters
    ----------
    z : float or array-like
        Cosmological redshift.
    met_bins : array
        Metallicity bins edges in absolute metallicity.
    SFH_MODEL : dict
        SFH model parameters.

    Returns
    -------
    SFH : 2D array
        Star formation history per metallicity bin at the given redshift(s).


Infer key from list of allowed keys.

    Parameters
    ----------
    available_keys : iterable object of str, e.g. list of str
        Collection of available keys.
    allowed_keys : iterable object of str, e.g. list of str
        Collection of allowed keys.

    Returns
    -------
    key : str
        The first matched key.


Set GRB energy conversion efficiency factor.


Compute GRB beaming factor.


Compute the GRB energy.


Compute the GRB isotropic equivalent energy.


Compute the GRB isotropic equivalet luminosity.


Create a BinaryPopulation instance from an inifile.

        Parameters
        ----------
        path : str
            Path to an inifile to load in.

        verbose : bool
            Print useful info.

        Returns
        -------
        BinaryPopulation
            A new instance of a BinaryPopulation.


Evolve a binary population.

        Parameters
        ----------
        indices : list, optional
            Custom binary indices to use. Default is range(number_of_binaries).
            If running with MPI, indices are split between processes if given.
        breakdown_to_df : bool, True
            Breakdown a binary after evolution, converting to dataframe and
            removing the binary instance from memory.
        tqdm : bool, False
            Show tqdm progress bar during evolution.

        Returns
        -------
        None


Evolve binaries in a population, catching warnings/exceptions.


Save BinaryPopulation to hdf file.


Get a valid filename for the temporary file.


Combine various temporary files in a given folder.

        Parameters
        ----------
        absolute_filepath : str
            Absolute path to the file to be saved.
        file_names : list
            List of absolute paths to the temporary files.


Add a binary instance internaly.


Remove a binary instance.


Breakdown to a pandas DataFrame.

        Breakdown a binary into more convenient data type, store it, and
        remove the BinaryStar instance from self.


Convert all binaries to dataframe.


Convert all binaries to oneline dataframe.


Find any failed binaries in the population.


Generate a binary by drawing from the binary_generator.

        This can be a callable or a generator.


Load a BinaryStar instance from an hdf file of a saved population.

        Parameters
        ----------
        indices : int, list
            Selects the binaries to load.
        where : str
            Query performed on disk to select history and oneline DataFrames.
        restore : bool
            If true, restore binaries back to initial conditions.


Save binaries to an hdf file using pandas HDFStore.

        Any object dtype columns not parsed by infer_objects() is converted to
        a string.

        Parameters
        ----------
        fname : str
            Name of hdf file saved.
        mode : {'a', 'w', 'r', 'r+'}, default 'a'
            See pandas HDFStore docs
        complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
            Compression library. See HDFStore docs
        complevel : int, 0-9, default 9
            Level of compression. See HDFStore docs
        kwargs : dict
            Arguments for `BinaryStar` methods `to_df` and `to_oneline_df`.

        Returns
        -------
        None


Generate all random varibles.


Return a binary for evolution in a population.

        Parameters
        ----------
        index : int
            Sets binary index. Defaults to number of generated binaries.

        Returns
        -------
        binary : BinaryStar


        Gives relative weight to each system in `data` based on its proximity to the points on the grid.
        Each system in `data` should have a primary mass `m1`, mass ratio `q`, redshift `z`, and effective spin `chieff`
        This function will determine detection probabilities using nearest neighbor algorithm in [log(m1), q, log(z), chieff] space
        Need to specify bounds (based on the trained grid) so that the grid and data get normalized properly

        data : Pandas dataframe
            Data you wish to predict detection probabilities for.
            Required series in the dataframe:
                'm1' : primary source-frame mass
                'q' : mass ratio (secondary mass/primary mass)
                'z' : redshift of merger
                'chieff' : effective inspiral spin

        verbose : boolean
            Adds verbosity.


normalizes data on range [a,b]


Randomly generate a population of binaries at ZAMS.

    Parameters
    ----------
    orbital_scheme : str (default: 'period')
        The scheme to use to get either orbital periods or separations
    **kwargs : dictionary
        kwargs from BinaryPopulation class

    Returns
    -------
    orbital_scheme_set : ndarray of floats
        Randomly drawn orbital separations/periods depending on the scheme
    eccentricity_set : ndarray of floats
        Randomly drawn eccentricities
    m1_set : ndarray of floats
        Randomly drawn primary masses
    m2_set : ndarray of floats
        Randomly drawn secondary masses


Randomaly generate orbital periods for a sample of binaries.


Generate random orbital separations.

    Use the scheme defined in this particular instance of BinaryPopulation.

    Parameters
    ----------
    number_of_binaries : int
        Number of binaries that require randomly sampled orbital separations
    orbital_separation_min : float
        Minimum orbital separation in solar radii
    orbital_separation_max : float
        Maximum orbital separation in solar radii
    log_orbital_separation_mean : float
        Mean of the lognormal distribution.
    log_orbital_separation_sigma : float
        Standard deviation of the lorgnormal distribution.
    orbital_separation_scheme : string
        Distribution from which the orbital separations are randomly drawn

    Returns
    -------
    orbital_separations : ndarray of floats
        Randomly drawn orbital separations


Generate random eccentricities.

    Use the scheme defined in this particular instance of BinaryPopulation.

    Parameters
    ----------
    number_of_binaries : int
        Number of binaries that require randomly sampled orbital separations
    eccentricity_scheme : string
        Distribution from which eccentricities are randomly drawn
    **kwargs : dictionary
        kwargs from BinaryPopulation class

    Returns
    -------
    eccentricities : ndarray of floats
        Randomly drawn eccentricities


Generate random primary masses.

    Use the scheme defined in this particular instance of BinaryPopulation.

    Parameters
    ----------
    number_of_binaries : int
        Number of binaries that require randomly sampled orbital separations
    primary_mass_min : float
        Minimum primary mass
    primary_mass_max : float
        Maximum primary mass
    primary_mass_scheme : string
        Distribution from which the primary masses are randomly drawn

    Returns
    -------
    primary_masses : ndarray of floats
        Randomly drawn primary masses


Generate random secondary masses.

    Use the scheme defined in this particular instance of BinaryPopulation.

    Parameters
    ----------
    primary_masses : ndarray of floats
        Previously drawn primary masses
    number_of_binaries : int
        Number of binaries that require randomly sampled orbital separations
    secondary_mass_min : float
        Minimum secondary mass
    secondary_mass_max : float
        Maximum secondary mass
    secondary_mass_scheme : string
        Distribution from which the secondary masses are randomly drawn

    Returns
    -------
    secondary_masses : ndarray of floats
        Randomly drawn secondary masses


    Getting the binary fraction depending on the scheme. The two possible option are a constant binary fraction
    and a binary fraction based on the values given in Moe and Di Stefano (2017).

    Parameters:
    --------------------
    binary scheme: string
        Determines if the value of the binary fraction will be constant or not
    binary fraction const: int
        Gives the value the constant value of the binary if the constant scheme is choosen.

    Returns
    ------------------
    binary fraction: int


Interpolator to compute the cosmological redshift given the cosmic time.

    Returns
    -------
    CubicSpline object
        Returns the trained SciPy CubicSpline interpolator object.


A GRB selection function to create a transient population of LGRBs.

    This function requires a wrapper function to be used to create a transient population, because
    of the extra parameters that are needed to be passed to the function (S1_S2).

    >>> def GRB_selection_wrapper(history_chunk, oneline_chunk, formation_channels_chunk=None):
    ...     return GRB_selection(history_chunk, oneline_chunk, formation_channels_chunk, S1_S2='S1')

    This is an example function for selecting LGRBs and some of their properties.
    Additional properties from the history or oneline can be added to the transient population.
    The output dataframe contains the following columns:
    - time : the time of the event
    - metallicity : the metallicity of the event
    - S1_m_disk_radiated : the mass of the disk radiated by the first star
    - S2_m_disk_radiated : the mass of the disk radiated by the second star

    Columns with pre and post SN data:
    - S1_mass : the mass of the first star
    - S2_mass : the mass of the second star
    - S1_spin : the spin of the first star
    - S2_spin : the spin of the second star
    - orbital_period : the orbital period of the binary
    - eccentricity : the eccentricity of the binary

    Parameters
    ----------
    history_chunk : pd.DataFrame
        The history chunk of the population.
    oneline_chunk : pd.DataFrame
        The oneline chunk of the population.
    formation_channels_chunk : pd.DataFrame (can be made optional)
        The formation pathway chunk of the population.
    S1_S2 : str
        The star that will be the progenitor of the GRB. Can be either 'S1' or 'S2'.

    Returns
    -------
    pd.DataFrame
        A DataFrame containing the transient population of LGRBs with the columns mentioned above.

    Example
    -------

    >>> GRB_selection_wrapper(pop.history[0], pop.oneline[0], pop.formation_channels.loc[0])
    >>> pop.create_transient_population(GRB_selection_wrapper, name='GRB_S1')


Calculate the effective spin of two masses.

    Parameters
    ----------
    m_1 : np.ndarray
        The mass of the first BH.
    m_2 : np.ndarray
        The mass of the second BH.
    a_1 : np.ndarray
        The spin of the first BH.
    a_2 : np.ndarray
        The spin of the second BH.
    tilt_1 : np.ndarray
        The tilt of the first BH.
    tilt_2 : np.ndarray
        The tilt of the second BH.

    Returns
    -------
    np.ndarray
        The effective spin of the BHs.


Calculate the mass ratio of two masses.


A BBH selection function to create a transient population of BBHs mergers.

    This is an example function for selecting BBH mergers and some of their properties.
    Additional properties from the history or oneline can be added to the transient population.
    The output dataframe contains the following columns:
    - time : the time of the event
    - metallicity : the metallicity of the event
    All other columns are optional.

    Parameters
    ----------
    history_chunk : pd.DataFrame
        The history chunk of the DCO population.
    oneline_chunk : pd.DataFrame
        The oneline chunk of the DCO population.
    formation_channels_chunk : pd.DataFrame (can be made optional)
        The formation pathway chunk of the DCO population.

    Returns
    -------
    df_transients : pd.DataFrame
        A DataFrame containing the transient population of BBHs.
        This DataFrame contains the following columns:
        - time : the time of the event
        - metallicity : the metallicity of the event


Calculate the observability of a DCO population.

    Parameters
    ----------
    sensitivity : float
        The sensitivity of the detector.
        Available sensitivities are (for Hanford, Livingston, Virgo network):
        - 'O3actual_H1L1V1' : aligo_O3actual_H1.txt, aligo_O3actual_L1.txt, avirgo_O3actual.txt
        - 'O4low_H1L1V1' : aligo_O4low.txt, aligo_O4low.txt, avirgo_O4high_NEW.txt
        - 'O4high_H1L1V1' : aligo_O4high.txt, aligo_O4high.txt, avirgo_O4high_NEW.txt
        - 'design_H1L1V1' : AplusDesign.txt, AplusDesign.txt, avirgo_O5high_NEW.txt

        GW detector sensitivity and network configuration you want to use, see arXiv:1304.0670v3
        detector sensitivities are taken from: https://dcc.ligo.org/LIGO-T2000012-v2/public

    Note: The population must have the following columns:
    - S1_mass : the mass of the first BH

    For the following columns, the function will try to calculate them if they are not present:
    - q : the mass ratio
    - chi_eff : the effective spin of the BHs

    For q, S2_mass must be present.
    For chi_eff, S1_Mass, S2_mass, S1_spin, S2_spin, S1_spin_orbit_tilt_at_merger, S2_spin_orbit_tilt_at_merger must be present.

    These have to be present and a valid value. If not, the function will raise an error!


Compute the initial total mass of the population.

     Parameters
    ----------
    simulated_mass, simulated_mass_single, simulated_mass_binaries : float
        Total simulated mass, simulated mass of binary systems and simulated
        mass of single stars, respectively.
    f_bin: float
        The binary fraction of your population in "nature".
        If not provided, the default value is set to 0.7

     Parameters are expected to be provided as keyword arguments (kwargs):
     --------
     primary_mass_min: float
         minimum initial mass of the primary star
     primary_mass_max: float
         maximum initial mass of the primary star
     binary_fraction_const: float
         Binary fraction used in the simulations
     primary_mass_scheme: string
         Kroupa2001 or Salpeter options
     secondary_mass_scheme: string
         mass ratio distribution

    ----------

    Returns
    -------
    underlying_total_mass: float
        The underlying total mass of the population: float
    f_corr_single_stars, f_corr_binaries; float
        Correction factors for singles and binaries, respectively.


Print the columns in the `oneline` and `history` keys in an HDF5 file.

    Parameters
    ----------
    path : str
        The fullpath of the HDF5 file.


Decide the HDF5 chunk size when searching for n_binaries.


Select a subset of columns based on a substring or array of substrings.

    Parameters
    ----------
    columns : array of str
        The original columns to be filtered.
    patterns : str or array of str
        The pattern or list of patterns, where pattern is a substring.

    Returns
    -------
    array of str
        Subset of the columns on the basis of the inclusion of substring(s).


Function to check an hdf5 file

            Parameters
            ----------
            path : str
                Location of the hdf5 file
            required_data : dict (optional)
                A dictionary where the keys are references to objects/datasets
                in the hdf5 file and the items are the ndarrays to be checked
                against (if the item is None, only the existence of the object
                is checked)
            required_attrs : dict (optional)
                A dictionary where the keys are references to attributes in the
                hdf5 file and the items are lists of strings to be part of this
                attribute


Function to check the EXTRA_COLUMNS

            Parameters
            ----------
            EXTRA_COLUMNS : dict
                New columns to check through.
            n_runs : int
                Count of runs.
            keys : list of str
                List of keys in EXTRA_COLUMNS.
            run_range : None or size 2 tuple (default: None)
                The range of entries to check. If None it checks 0 till
                n_runs-1.


Function to check the EXTRA_COLUMNS of single star girds

            Note: The non-core collapse runs 0 and 6 will be skipped.

            Parameters
            ----------
            EXTRA_COLUMNS : dict
                New columns to check through.
            n_runs : int
                Count of runs.
            keys : list of str
                List of keys in EXTRA_COLUMNS. All 'S2' and the 'mt_history'
                will be checked for being not there.


Create a concrete subclass of SFHBase for testing.


Create mock data for the IllustrisTNG class.


Create an IllustrisTNG model instance with mocked data.


Create mock data for the Chruslinska21 class.


Create a Chruslinska21 model instance with mocked data.


Create mock data for the Zavala21 class.


Create files of one MESA run

    Parameters
    ----------
    path : str
        The path to the directory containing all the runs.
    idx : int
        Run index. (1, 3, 4, 5, 8, 11, 14, and 17 have a special meaning)
    binary_run : bool (default: True)
        If `True` files of a binary run are created, otherwise run of a single
        star.
    with_histories : bool (default: True)
        If `True` creates history files.
    with_profiles : bool (default: True)
        If `True` creates final profile files.

    Returns
    -------
    str
        Path to the added run.


Derive a flow chart from POSYDON's standard one and modify it.

    Parameters
    ----------
    FLOW_CHART : dict or None
    CHANGE_FLOW_CHART : dict or None

    Returns
    -------
    dict
        Modified flow chart.


Read run structure, expecting the POSYDON collaboration format.


Return the joined path of `folder` and `filename`, if exists.


Report what data or metadata were found.


Get a list of all the folders with MESA runs.

        Returns
        -------
        dict view
            Containing all the paths of MESA runs.


Read grid structure, expecting the POSYDON collaboration format.


Infer the columns found in the grid's history data files.

        Parameters
        ----------
        BH_cols : array-like
            Which columns to consider from `binary_history`.
        H1_cols : array-like
            Which columns to consider from `history1`.
        H2_cols : array-like
            Which columns to consider from `history2`.

        Returns
        -------
        list
            The names of the columns in history data. Columns in `history1` and
            `history2` are prefixed with `star1_` and `star2_` respectively.


Print parts of metadata files for inspection.

    Parameters
    ----------
    path : str
        Path of file containing the metadata.
    max_lines : int or None (default: None)
        Maximum number of lines to print. If None, print all of them.
    max_chars_per_line: int or "warp" (default: 80)
        If integer, it is the maximum number of character to be printed
        (e.g., useful when printing MESA output). If "warp", no truncation.


Read grid point values given the MESA run directory.

    Parameters
    ----------
    mesa_dir : str
        Path of MESA directory.

    Returns
    -------
    dict
        Initial values of all the variables in inlist_grid_points.


Use the name of the directory for inferring the main initial values.

    Parameters
    ----------
    mesa_dir : str
        Path of MESA directory.

    Returns
    -------
    tuple
        v1, single star (1 item): only initial mass
        v2, single star (2 items): initial mass and metallicity
        v1, binary (3 items): primary and secondary initial mass and initial
            orbital period
        v2, binary (4 items): primary and secondary initial mass, initial
            orbital period, and metallicity


Scrub binary and star histories of a MESA run in one go.

    Parameters
    ----------
    tables : list
        All history tables to be returned scrubbed.
    models : list
        Model number columns corresponding to each table in `tables`.
    ages : list
        Age columns corresponding to each table in `tables`.

    Returns
    -------
    list
        The list of scrubbed tables, ensuring monotonicity in age, and
        overlap in model numbers.


Scrub histories from the initial steps without RLO mass transfer.

    Parameters
    ----------
    bh : np.array
        The `binary_history` array.
    h1 : np.array
        The `history1` array.
    h2 : np.array
        The `history2` array.

    Returns
    -------
    tuple or ndarrays, or None
        The binary, history1 and history2 arrays after removing the leading
        steps without RLO overflow mass transfer from star1 or star2. If an
        RLO phase is not detected, a warning is raised, and returns `None`.


Scrub histories to stop when central helium and carbon abundance are
    below the stopping criteria.

    Parameters
    ----------
    bh : np.array
        The `binary_history` array.
    h1 : np.array
        The `history1` array.
    h2 : np.array
        The `history2` array.
    Ystop : float (default: THRESHOLD_CENTRAL_ABUNDANCE)
        The He abundance threshold for stopping
    XCstop : float (default: THRESHOLD_CENTRAL_ABUNDANCE_LOOSE_C)
        The C abundance threshold for stopping

    Returns
    -------
    tuple
        The binary, history1 and history2 arrays after removing the final
        steps after He depletion. If the stopping criteria are not reached
        the histories will be returned unchanged. Finally, the new termination
        flag 1 is returned.


Assign None values to all core collapse properties.

        Parameters
        ----------
        EXTRA_COLUMNS : dict of lists
            Each new column should be a list in this dictionary. This
            dictionary will get modified by this function.
        star_i : int (1 or 2)
            Index of the star.
        SN_MODEL_NAME : str or list of str, or None (default: None)
            SN_MODEL key like the ones given in SN_MODELS.py.


Print quantities at core collapse.

        Parameters
        ----------
        star : SingleStar object
            The star whose quantities to print.
        SN_MODEL_NAME : str or None (default: None)
            Name of the supernova model. If None, print pre SN values.


Compute post processed quantity of any grid.

    This function post processes any supported grid and computes:
    - Core collapse quantities for 5 prescriptions given the fiducial POSYDON
    assumption given in SN_MODEL:
      for each prescrition we store the compact object state (WD/NS/BH),
      SN type (WD, ECSN, CCSN, PISN, PPISN), fallback mass fraction f_gb,
      compact object mass and spin.
    - Core masses at he-depletion (used in Patton core collapse)
    - Mass envelopes for common envelope step.

    Parameters
    ----------
    grid : PSyGrid
        MESA grid in PSyGrid format.
    index : None, int, or list with two int (default: None)
        If None, loop over all indicies otherwise provide a range, e.g. [10,20]
        or a single index, e.g. 42.
    star_2_CO : bool (default: True)
        If 'False' star 2 is not a compact object.
    SN_MODELS : list of dict (default are the models defined in SN_MODELS.py)
        List of supported core collapse model assumptions.
    single_star : bool (default: False)
        If `True` the PSyGrid contains single stars.
    verbose : bool (default: False)
        If `True` print the results of each core collapse on screen.

    Returns
    -------
    MESA_dirs: list
        List containing the path to each run corresponding to the post
        processed values. This is used to ensure one to one mapping when
        appending the extra columns back to a grid.
    EXTRA_COLUMNS: dict
        Dictionary containing all post processed quantities.


Append post processed quantity to a grid.

    This function appends the quantities computed in post_process_grid to any
    grid. Note that this function ensures you can append the quantities only if
    the grid follows the order of MESA_dirs_EXTRA_COLUMNS.

    Parameters
    ----------
    grid : PSyGrid
        MESA grid in PSyGrid format.
    MESA_dirs_EXTRA_COLUMNS: list
        List containing the path to each run corresponding to the post
        processed values. This is used to ensure one to one mapping when
        appending the extra columns back to a grid.
    EXTRA_COLUMNS: dict
        Dictionary containing all post processed quantities.


(Re)set attributes to defaults, except `filename` and `verbose`.


Convert compression information from the config.


Search for EEP files and remember found ones.

        Parameters
        ----------
        path : str
            It is the path of the base directory to start the search for EEP
            files.


Print text if verbose is True.

        Parameters
        ----------
        something : str
            The printed text.


Store the grid's configuration in a ConfigFile object.

        Parameters
        ----------
        **grid_kwargs : dict
            Keyword arguments to overwrite default GRIDPROPERTIES.


Create a new PSyGrid object from a MESA grid and save it on disk.

        Parameters
        ----------
        MESA_grid_path : str
            The path of the top directory where the input grid is located.
        psygrid_path : str or None (default: None)
            The path of the HDF5 file to be created (or overwritten). If not
            provided, it is assumed that it was defined during initialization.
        overwrite : bool (default: False)
            Whether to overwrite the HDF5 file if it already exists.
        slim : bool (default: False)
            If `True`, only the metadata and initial/final values are stored.
        warn : str (default: 'end')
            How warnings are handled. If "normal", then warnings are shown when
            they occur. If "end", they are collected and shown at the end. If
            "suppress", then warnings are not shown at all.
        fmt : str (default: 'posydon')
            Format specifier. Linked to data-types, filename conventions, etc.
            passed to GridReader
        **grid_kwargs : dict
            Configuration of the new grid, passed as additional arguments.


Generate a PSyGrid instance from a path to MESA data.

        Parameters
        ----------
        MESA_path : str
            The path of the directory with the MESA runs.
        hdf5 : h5py.File object
            Object containing an open hdf5 file.
        slim : bool (default: False)
            Whether to include runs' history/profile data in the HDF5 file.
        fmt : str (default: 'posydon')
            Format specifier. Linked to data-types, filename conventions, etc.
            passed to GridReader


Get columns to be saved or `None` if setting is 'all').


Add a new numerical column in the final values array.

        Parameters
        ----------
        colname : str
            Name of the new column.
        array : ndarray like
            Data of the new column.
        where : str (default: 'final_values')
            Name of the element to add the column to. Currently only
            'final_values' allowed.
        overwrite : bool (default: True)
            Flag, whether an existing column should be replaced or an error
            should be raised.


Update the final values in the HDF5 file.


Close and reopen the hdf5 file.

        Parameters
        ----------
        writeable : bool (default: False)
            Flag, whether to open the hdf5 file in write mode or read only.


Load up a previously created PSyGrid object from an HDF5 file.

        Parameters
        ----------
        filepath : str or None (default: None)
            Location of the HDF5 file to be loaded. If not provided, assume
            it was defined during the initialization (argument: `filepath`).


Close the HDF5 file if open.


Create a CSV file with the PSyGrid initial values to rerun.

        This methods allows you to create a CSV file with the psygrid initial
        values you want to rerun.

        Parameters
        ----------
        path_to_file : str (default: './')
            The path to the directory where the new `grid.csv` file will be
            saved. If the directory does not exist it will be created.
        runs_to_rerun : list of integers or None (default: None)
            Array containing the indecies of the psygrid runs you want to rerun
            e.g., runs_to_rerun = [2,3]
        termination_flags : str or list of str or None (default: None)
            The runs with this termination flag will be rerun.
            e.g. termination_flags='max_number_retries'
        new_mesa_flag : dict or None (default: None)
            Dictionary of flags with their value to add as extra columns to the
            `grid.csv`. The user can specify any arbitrary amount of flags.
            e.g. new_mesa_flag = {'varcontrol_target': 0.01}
        flags_to_check : str or list of str or None (default: None)
            The key(s) of flags to check the termination_flags against.
            e.g. check_flags = 'termination_flag_1'


Plot a 2D slice of x_var_str vs y_var_str of one or more runs.

        Parameters
        ----------
        x_var_str : str
            String of the initial value to plot on the x axis. Allowed strings
            are `psygrid.initial_values.dtype.names`.
        y_var_str : str
            String of the initial value to plot on the y axis. Allowed strings
            are `psygrid.initial_values.dtype.names`.
        z_var_str : str or None (default: None)
            String of the initial value to plot on the z axis (displayed as
            a color). Allowed strings are
            `psygrid.final_values.dtype.names`, `psygrid.history1.dtype.names`,
            `psygrid.binary_history.dtype.names`.
        termination_flag : str (default: 'termination_flag_1')
            Termination flag to display, allowed values are:
            "termination_flag_1", "termination_flag_2", "termination_flag_3",
            "termination_flag_4", "all".
        grid_3D : bool or None (default: None)
            If `True`, the psygrid object is a 3D grid and needs to be sliced.
        slice_3D_var_str : str or None (default: None)
            Variable along which the 3D space will be sliced. Allowed values
            are `psygrid.initial_values.dtype.names`.
        slice_3D_var_range : tuple or a list of tuples or None (default: None)
            Range between which you want to slice the variable slice_3D_var_str
            e.g., `(2.5,3.)`. In case of a list of tuples, one will get a large
            plot with one subplot for each tuple in the list.
        grid_4D : bool or None (default: None)
            If `True`, the psygrid object is a 4D grid and needs to be sliced.
        slice_4D_var_str : str or None (default: None)
            Variable along which the 4D space will be sliced. Allowed values
            are `psygrid.initial_values.dtype.names`.
        slice_4D_var_range : tuple or a list of tuples or None (default: None)
            Range between which you want to slice the variable slice_4D_var_str
            e.g., `(2.5,3.)`. In case of a list of tuples, one will get a large
            plot with one subplot for each tuple in the list.
        extra_grid : object or array of objects or None (default: None)
            If subset of the grid was rerun a or an extention was added, one
            can overlay the new psygrid by passing it here.
        slice_at_RLO : bool (default: False)
            If `True`, the object plots the tracks until onset of Roche Lobe
            overflow.
        MARKERS_COLORS_LEGENDS : dict or None (default: None)
            Each termination flag is associated with a marker shape, size,
            color and label (cf. `MARKERS_COLORS_LEGENDS` in
            `plot_defaults.py`).
        max_cols : int (default: 3)
            Defines the maximum number of columns of subplots. Default: 3
        legend_pos : SubplotSpec: int or tuple (default: (3,3))
            Defines which subplots won't contain an axis but are used to
            display the legend there. Default: (3, 3)
        verbose : bool (default: False)
            If `True`, the object reports by printing to standard output.
        **kwargs : dict
            Dictionary containing extra visualisation options (cf.
            `PLOT_PROPERTIES` in `plot_defaults.py`.


Plot a 1D track of x_var_str vs y_var_str.

        Parameters
        ----------
        idx : int or list of int
            Index or indices of runs to plot.
        x_var_str : str
            String of values to plot on the x axis. Allowed strings are the
            one in `psygrid.history.dtype.names` where "history" needs to be
            chosen accordingly.
        y_var_str : str or list of str
            String or list of stringvalues to plot on the y axis. Allowed
            strings are the one in `psygrid.history.dtype.names` where
            "history" needs to be chosen accordingly.
        z_var_str : str or None (default: None)
            String of values to plot on the z axis (displayed with a color).
            Allowed strings are the one in `psygrid.history.dtype.names` where
            "history" needs to be chosen accordingly.
        history : str (default: 'binary_history')
            The x, y, z variables are read from either: "binary_history",
            "history1", "history2".
        verbose : bool (default: False)
            If `True`, the object reports by printing to standard output.
        **kwargs : dict
            Dictionary containing extra visualisation options
            (cf. `PLOT_PROPERTIES` in `plot_defaults.py`).


Plot the HR diagram of one or more runs.

        Parameters
        ----------
        idx : int or list of int
            Index or indices of runs to plot.
        history : str (default: 'history1')
            Which history is going to be used. The options are:
            "binary_history", "history1", or "history2".
        states : bool (default: False)
            If true the HR diagram shows the stellar state with a color map.
        verbose : bool (default: False)
            If `True`, the object reports by printing to standard output.
        **kwargs : dict
            Dictionary containing extra visualisation options
            (cf. `PLOT_PROPERTIES` in `plot_defaults.py`).


Return the name of the group in the hdf5 file.

        Returns
        -------
        str
            The name of the hdf5 group.


Downsample history data of a run.

    Parameters
    ----------
    bh : record array
        The binary history table.
    h1 : record array
        The history of star 1.
    h2 : record array
        The history of star 2.
    params : ConfigFile
        A ConfigFile instance holding the downsampling parameters.

    Returns
    -------
    tuple of record arrays
        The three record arrays corresponding to the downsample binary,
        star 1, and star2 histories.


Downsample a profile table.

    Parameters
    ----------
    profile : record array
        The profile data with column names defined.
    params : ConfigFile
        A ConfigFile instance holding the downsampling parameters.

    Returns
    -------
    record array
        The downsampled profile.


Join two or more PSyGrid HDF5 files into one.

    Parameters
    ----------
    input_paths : str or list of str
        The path to the grid files to be joined.
    output_path : str
        Path of the new grid file with the joined gird.
    compression : str (default: 'gzip9')
        Compression details.
    description : str (default: 'joined')
        Desciption of the new joined gird.
    verbose : bool (default: True)
        If `True`, the objects reports by printing to standard output.


Return the final state of the star from the star history data.

    Parameters
    ----------
    history : np.array
        MESA history of the star.
    mass : np.array
        Mass history of the star.
    model_index : int (default: -1)
        Index of the model in history for which the state will be computed.
        By default it is the end of the evolution (last model).

    Returns
    -------
    state : str
        The state of the star.


Use the first two termination flags to infer the interpolation class.

    Parameters
    ----------
    tf1 : str
        Termination flag 1 (end condition).
    tf2 : str
        Termination flag 2 (mass transfer).

    Returns
    -------
    str
        Interpolation class.


Rescale a matrix so that all dimensions span from 0 to 1.

        Parameters
        ----------
        array : array like
            Data collection to be rescaled (along first axis).
        return_minmax : bool (default: False)
            It True, the minimum and maximum are returned as second and thrid
            item.

        Returns
        -------
        ndarray
            The rescaled data.
        (float)
            Value of the minimum (only returned if return_minmax is True).
        (float)
            Value of the maximum (only returned if return_minmax is True).


Speak to the standard output, only if `.verbose` is True.

        Parameters
        ----------
        message : str
            The printed text.


Rescale the parameter space from 0 to 1.


Extract the downsampled array.

        Parameters
        ----------
        scale_back : bool (default: True)
            If true scale back to actual values otherwise use values scaled
            to [0,1].

        Returns
        -------
        t : ndarray
            Independent data.
        X : ndarray
            Dependent data.


Find the rows of the data that constitute the "down-sample".

        Parameters
        ----------
        max_err : float or None (default: None)
            Maximum relative error to be allowed.
        max_interval : float or None (default: None)
            Maximum step in the independent variable.

        Note: if `max_interval` is negative, it's value is the relative ratio
              between maximum allowed dm and initial-final change.


Perform the downsampling and return the result.

        Parameters
        ----------
        max_err : float or None (default: None)
            Maximum relative error to be allowed.
        scale_back : bool (default: True)
            If true scale back to actual values otherwise use values scaled
            to [0,1].
        max_interval : float or None (default: None)
            Maximum step in the independent variable.

        Returns
        -------
        t : ndarray
            Independent data.
        X : ndarray
            Dependent data.


Plot the 2D pannel.

        Parameters
        ----------
        ax : object
            matplotlib figure axes.
        extra_grid_call : bool
            If `True`, one ore more extra grids are passed.


Add extra initial values.


Udpdate markers, colors and legend.

        Parameters
        ----------
        termination_flag : string
            Termination flag to display, allowed values are:
            "termination_flag_1", "termination_flag_2", "termination_flag_3",
            "termination_flag_4".
        MARKERS_COLORS_LEGENDS : dict
            Each termination flag is associated with a marker shape, size,
            color and label.


Update all values to plot.

        Parameters
        ----------
        termination_flag : string
            Termination flag to display, allowed values are:
            "termination_flag_1", "termination_flag_2", "termination_flag_3",
            "termination_flag_4".


Plot the 2D panels.

        Parameters
        ----------
        axs : array of axes
            matplotlib figure axes. Its dimensions should be stored in
            self.n_cols and self.n_rows.
        legend_idxs : list of indices
            Tells where to place the legend instead of a plot.


Add not pre defined stuff to DEFAULT_MARKERS_COLORS_LEGENDS.

    Parameters
    ----------
    MARKERS_COLORS_LEGENDS : dict of lists
        Dictionary with flags as keys given a list with marker, size, color,
        and legend text for each flag.
    flag : str
        The flag itself.


Plot the GRB rate density from Perley et al. (2016)

    plot the long gamma-ray burst rate density from Perley et al. (2016)
    if ax is None, it plotted on the latest axis, otherwise it is added to the given axis

    Parameters
    ----------
    ax : matplotlib.axes.Axes (optional)
        Axes object to plot the data on


Plot the population synthesis data over a grid slice

    Outputs one or multiple plots of the population synthesis data over a grid slice.
    Either stores the plots in a directory or shows them.

    Parameters
    ----------
    pop : Population
        Population object
    grid_type : str
        Grid type to get data for.
        Options are 'HMS-HMS', 'CO-HMS_RLO', 'CO-HeMS', 'CO-HeMS_RLO'.
    met_Zsun : float
        Metallicity of the population in solar units
    termination_flag : str
        Termination flag for the grid
    slices : list (optional)
        List of slices to plot
    channel : str (optional)
        Formation channel to be plotted
    plot_dir : str (optional)
        Directory to save the plots
    prop : str (optional)
        Property to plot on top of the grid slice
    prop_range : list (optional)
        Range of the property to plot
    log_prop : bool (optional)
        Logarithmic scale for the property
    alpha : float (optional)
        Transparency of the data points
    s : float (optional)
        Size of the data points
    show_fig : bool (optional)
        Show the figure
    save_fig : bool (optional)
        Save the figure
    close_fig : bool (optional)
        Close the figure
    plot_extension : str (optional)
        File extension for saving the plot
    verbose : bool (optional)
        Print information


Plot the population data based on the grid slice parameters

    Parameters
    ----------
    data : DataFrame
        Population data
    slice_3D_var_str : str
        String of the 3D variable to slice the grid
    slice_3D_var_range : list
        Range of the 3D variable to slice the grid
    prop : str (optional)
        Property to plot on top of the grid slice
    prop_range : list (optional)
        Range of the property to plot
    log_prop : bool (optional)
        Logarithmic scale for the property
    alpha : float (optional)
        Transparency of the data points
    s : float (optional)
        Size of the data points


Plot the 1D pannel.

        Parameters
        ----------
        ax : object
            matplotlib figure axes.
        i : int
            Index of the run to plot.
        y_var_str : str
            String or list of stringvalues to plot on the y axis.


Update all values to plot.

        Parameters
        ----------
        y_var_str : str
            String or list of stringvalues to plot on the y axis.


Constant radius lines for the HR diagram.


Plot and HR diagram.


Method that computes both interpolation and classification errors


 Method that formats keys for plots

        Parameters
        ----------
        s : str
            string to be formatted


 Method that finds labels in classifier

        Parameters
        ----------
        key : str
            name of the classifier

        Returns
        -------
        list of class labels


 Method that plots distribution of specified error for given keys and
        optionally saves it.

        Parameters
        ----------

        err_type : str
            Either relative or absolute, default is relative
        keys : list
            A list of keys for which the errors will be shown, by default is all of them
        save_path: str
            The path where the figure should be saved to
        close_fig: bool
            Flag whether figure should be closed


 Method that plots confusion matrices to evaluate classification

        Parameters
        ----------
        key : str
            The key for the classifier of interest
        params : dict
            Extra params to pass to matplolib, x_labels (list), y_labels (list), title (str)
        save_path : str
            The path where the figure should be saved to
        close_fig: bool
            Flag whether figure should be closed


Method that lists classifiers available


Method that lists out keys available


Get the combination of interpolation classion and termination flag 2.


Combine 2 dictionaries of SimplifiedInfo.

    data_to[].state_after take the value of data_from[].state_before.

    Parameters
    ----------
    data_to : dictionary of SimplifiedInfo
        Informations who will be udpated.
    data_from : dictionary of SimplifiedInfo
        Informations who will be combined.


Convert dictionnary of SimplifiedInfo with values as `.state_before`.

    Parameters
    ----------
    row : dictionnary
        Dictionnary of value to convert.

    Returns
    -------
    dictionnary of SimplifiedInfo
        Dictionnary of SimplifiedInfo containing the value as
        SimplifiedInfo.state_before.


Check if 2 numbers are equal up to epsilon.

    Parameters
    ----------
    nb_1 : int, float, double
        Value 1 to compare.
    nb_2 : int, float, double
        Value 2 compare.
    epsilon : int, float, double
        Difference allowed.

    Returns
    -------
    bool
        True if numbers are equal up to epsilon, False if not.


For each row in dataframe, calculate the separation.

    Parameters
    ----------
    data : pandas.DataFrame
        Complete dataframe without 'separation'.

    Returns
    -------
    Array of float
        Array of calculated separations, len(array) == nb rows.


Take a screen of the displayed window.


Get binary data and calculate missing columns.

        Parameters
        ----------
        index : int
            Binary index to load.


Preset the binary.


Update the display according to current_index and present_mode.


Add columns for Detailled/Reduced/Simplified View.


Add columns for Diagram View.


Prepare widget to display as basic (non-simplified) data.

        Parameters
        ----------
        row : dictionary
            Dataframe's row needing to be formated.

        Returns
        -------
        Array of Infos
            Array containing derivated struct of Infos to create correspondong
            widget.


Format the information 'data_name' for simplfied view.

        This is done according to whether it exists or not, and if there is a
        before/after.

        Parameters
        ----------
        dataset : dictionary of SimplifiedInfo
            Dictionary containing all infos to format.
        name : str
            Name of the info to format.
        infos : type
            Struct to create coresponding widget.
        side : bool
            Indicate on which side display the information, False = Left


Prepare widget informations to display as simplified data.

        Parameters
        ----------
        data : dictionary of SimplifiedInfo
            Infos formated to be displayed in widgets.

        Returns
        -------
        Array of Infos
            Array containing derivated struct of Infos to create corresponding
            widgets.


Normalize 1 of the 2 distances in simplified_distance.

        Use the max_distance, according to whether it exists or not,
        if it's NaN or 0.

        Parameters
        ----------
        simplified_distance : SimplifiedInfo
            Struct containing distances of the current state.
        max_distance : float
            Description of parameter `max_distance`.

        Returns
        -------
        float
            Normalized current star distance.


Format the information 'data_name' for diagram view.

        This is done according to whether it exists or not, and if there is
        a before/after.

        Parameters
        ----------
        dataset : dictionary of SimplifiedInfo
            Dictionary containing all infos to format.
        data_name : str
            Name of the info to format.
        diagram_infos : StateInfos
            Struct to create coresponding widget.


Prepare widget information to display basic (non-simplified) data.

        Parameters
        ----------
        data : dictionary of SimplifiedInfo
            Infos formated to be displayed in widgets.
        max_distance : float
            Max distance between 2 star, used to set normalized distance
            for this state.

        Returns
        -------
        Array of Infos
            Array containing derivated struct of Infos to create corresponding
            widgets.


Format and display data in the Detailled View.

        Parameters
        ----------
        data : pandas.DataFrame
            Data to display in detailled view.


Reduce the dataframe given by folowing hardcoded rules.

        If the row has same time (within 10,000 years) as the previous one,
        each info is combined with the previous info in a SimplifiedInfo struct
        giving a dictionary with same row's key, full of SimplifiedInfo, which
        are the simplified row.

        Parameters
        ----------
        data : pandas.DataFrame
            Data to simplify.

        Returns
        -------
        Array of dictionary of SimplifiedInfo
            Each dictionary hold same keys of 1 data's row, but with
            SimplifiedInfo as value.
            Array length =/= row's number in data because some infos are
            combined in SimplifiedInfo.


Format and display data in the Reduced View.

        Parameters
        ----------
        data : pandas.DataFrame
            Data to display in reduced view.


Simplify the dataframe given by folowing hardcoded rules.

        If the row isn't interesting, each info is combined with the previous
        info in a SimplifiedInfo struct, giving a dictionary with same row's
        key, full of SimplifiedInfo, which are the simplified row.

        Parameters
        ----------
        data : pandas.DataFrame
            Data to simplify.

        Returns
        -------
        Array of dictionary of SimplifiedInfo
            Each dictionary hold same keys of 1 data's row, but with
            SimplifiedInfo as value.
            Array length =/= row's number in data because some infos are
            combined in SimplifiedInfo.


Format and display data in the Simplified View.

        Parameters
        ----------
        data : pandas.DataFrame
            Data to display in simplified view.


Format and display data in the Diagram View.

        Parameters
        ----------
        data : pandas.DataFrame
            Data to display in diagram view.


Prepare option showed only in special situation.


Prepare the different options there callback.


Help to create GraphVisualizerCase from CaseInfos.

    Parameters
    ----------
    infos : CaseInfos
        Infos to create the widget.

    Returns
    -------
    GraphVisualizerCase
        Created widget with given infos.


Paint an event.


Help to create GraphVisualizerPoint from PointInfos.

    Parameters
    ----------
    infos : PointInfos
        Infos to create the widget.

    Returns
    -------
    GraphVisualizerPoint
        Created widget with given infos.


Resize the event.


Paint the event.


Help to create GraphVisualizerState from StateInfos.

    Parameters
    ----------
    infos : StateInfos
        Infos to create the widget.

    Returns
    -------
    GraphVisualizerState
        Created widget with given infos.


Add one item in the column, connect it to previous if needed.

        Parameters
        ----------
        item : GraphVisualizerItem
            Widget to add in column.


Delete all widget in the column, keep the title.


Delete everythings (widget + title), reset logical column used.


Add widget to the logical column used.

        Parameters
        ----------
        widget : QWidget
            Widget to add.


Draw the surface.


Create a column according to the column_type.

        It takes account for the column_span of the logical column.

        Parameters
        ----------
        column_type : columnTYPE
            Type of the column to add.
        column_span : int
            Nb of logical column used.

        Returns
        -------
        int
            ID of created column.


Add all lines based on all elements in `infos`.

        For each info in infos, create the corresponding widget and add it to
        the column with corresponding id (given in each info), only 1 widget
        per column by call, if one column haven't any widget associated,
        column skip this row.

        Parameters
        ----------
        infos : Array of Infos
            Array with derivated struct of Infos to create the different
            widget for this line.


Clear all delete each column.


Render this widget in a picture and save it a filename.

        Parameters
        ----------
        filename : str
            Destination file of the picture.


Load dataframe as CSV with .gz compression.


Add columns for multiple Diagram View.


Return a list of filenames of the picture (or centered_text) from the list of
        StateInfos/CaseInfos for a given column


Conpare two Infos objects (can be CaseInfos or StateInfos)


Remove consecutive horizontally duplicated state to get the tree view
        (recursively)


move states in a range of columns from far right to center
        also setting the sum of same states's frequencies appearance to be printed


Hierarchy PresenterMode for the moment is only PresenterMode.DIAGRAM


Add columns for Diagram view set column minimum width and add index to _columns_indexes


Adding oblic edges to be painted as ConnectedItem from edges added in self._edges


Star the visualization.

        Returns
        -------
        VisualizerInterface
            Return the interface with current window, binded visualizer widget
            and option window. Expose callbacks.


Prepare all displayed option on MenuBar.


function to be given as key argument to DataFrameGroupBy.apply()


a more relevant parser imo but turns out to take more time than than groupby/apply


Extracts profile data from one MESA run.
        Args:
            grid (obj) : PSyGrid object.
            ind (int) : index of run to be scraped.
            hms_s2 (Boolean) : option to get profiles of star 2 in HMS-HMS grid
        Returns:
            scalars (array-like) : dictionary containing initial
                                   m1, m2, p, mass transfer class,
                                   final star_state, final total_mass.
            profiles (array-like) : all N specified profiles, shape (N,200).


Save extracted profile data.
        Args:
            filename (str) : path/name of '.pkl' file where the data will be saved.


Load and process extracted profile data.
        Args:
            filename (str) : path/name of '.pkl' file to be loaded.
            valid_split (float) : percentage of training data used for validation set


Trains models for density, H mass fraction, and He mass fraction profile models.
        Args:
            IF_interpolator (str) : path to '.pkl' file for IF interpolator.
            train_density (Boolean) : option to train Density model
            train_comp (Boolean) : option to train Composition model
            density_epochs (int) : number of epochs used to train density profile model
            density_patience (int) : patience parameter for NN callback in density profile model
            comp_bounds_epochs (int) : number of epochs used to train composition profiles model
            comp_bounds_patience (int) : patience parameter for NN callback in composition profiles model
            loss_history (Boolean) : option to return training and validation loss histories
            hms_s2 (Boolean) : option to do profiles of star 2 in HMS-HMS grid
            depth (int) : depth of neural network for principal component weights
            width (int) : width of neural network for principal component weights
            depthn (int) : depth of neural network for normalizing value
            widthn (int) : width of neural network for normalizing value
            learning_rate (float) : learning rate for neural network training
        Returns:
            self.dens.loss_history (array-like) : training and validation loss history for density profiles.
                                                  Returned first if both models are trained.
            self.comp.loss_history (array-like) : training and validation loss history for composition profiles
                                                  Returned second if both models are trained.


Predict density, H mass fraction, and He mass fraction profiles from inputs.
        Args:
            inputs (array-like) : positive linear-space initial conditions of N binaries to predict, shape (N,3).
            density (Boolean) : option to train Density model
            comp (Boolean) : option to train Composition model
        Returns:
            mass_coords (array-like) : linear-scale mass enclosed profile coordinates.
                                       Returned first.
            density_profiles (array-like) : log-scale density profile coordinates.
                                            Returned second if density model is trained.
            h_profiles (array-like) : H mass fraction profile coordinates.
                                      Returned after mass_coords (and density_profiles) if composition model is trained.
            he_profiles (array-like) : He mass fraction profile coordinates.
                                       Returned after h_profiles if composition model is trained.


Save complete profiles interpolation model.
        Args:
            filename (str) : path/name of '.pkl' file where the model will be saved.


Load interpolation model, which can be used for predictions.
        Args:
            filename (str) : path/name of '.pkl' file to be loaded.


Enforce monotonicity in profiles such as density that must monotonically decrease
        Args:
            profiles (array-like) : N profiles to be post-processed for monotonicity
        Returns:
            profiles_mono (array-like) : post-processed profiles


Trains NN models.
        Args:
            loss (object) : loss function for training.
            prof_epochs (int) : number of epochs used to train neural network
            prof_patience (int) : patience parameter for callback in neural network
            learning_rate (float) : learning rate for neural network training


Predicts profile for n sets of given inputs, in array of shape (n,3).
        Args:
            inputs (array-like) : positive linear-space initial conditions of N binaries to predict, shape (N,3).
        Returns:
            mass_coords (array-like) : linear-scale mass enclosed profile coordinates.
            density_profiles (array_like) : log-scale density profile coordinates.


Creates and trains NNs to predict boundary points for each star 1 state.
        Args:
            training_epochs (int) : number of epochs used to train neural networks
            training_patience (int) : patience parameter for callback in neural networks
            depth (int) : depth of neural network
            width (int) : width of neural network
            learning_rate (float) : learning rate for neural network training
        Returns:
            b_models (array-like) : dictionary containing boundary models.
            loss_history (array-like) : training and validation loss histories


Predict a profile for a single binary
        Args:
            initial (array-like) : initial position of binary
            center_H (float) : center H mass fraction
            surface_H (float) : surface H mass fraction
            center_He (float) : center He mass fraction
            surface_He (float) : surface He mass fraction
            star_state (str) : final star state
        Returns:
            H (array-like) : predicted H mass fraction profile
            He (array-like) : predicted He mass fraction profile


Predict H mass fraction profiles from inputs.
        Args:
            inputs (array-like) : positive linear-space initial conditions of N binaries to predict, shape (N,3).
        Returns:
            mass_coords (array-like) : linear-scale mass enclosed profile coordinates.
            h_profiles (array_like) : H mass fraction profile coordinates.
            he_profiles (array_like) : He mass fraction profile coordinates.


Fit a transform of 1D numpy array x.

        Computes the parameters that define the transform.

        Parameters
        ----------
        x : numpy.ndarray
            expects a 1D array and finds norm values of columns

        method : str
            Scaling method. Possible values: 'min_max', 'max_abs', 'standarize'
            and their log versions 'log_min_max', 'neg_log_min_max',
            'log_max_abs', 'log_standarize', 'neg_log_standarize'.

        lower : float
            lower range value of x_t after (log_)min_max scaling
        upper : float
            upper range value of x_t after (log_)min_max scaling


Transform x using the already obtained normalization values.

        `self.fit()`` must be called first.
        lower/upper will only be taken into account for (log_)min_max
        normalization. In this case, the transformed x will have
        min(x_transf) = lower, max(x_transf) = upper

        Parameters
        ----------
        x : numpy.ndarray
            values to normalize

        Returns
        -------
        numpy.ndarray
            transformed version of x


Fit and transform the array x according to the chosen scaling.

        lower/upper will only be taken into account for (log_)min_max
        normalization. In this case, the transformed x will have
        min(x_transf) = lower, max(x_transf) = upper

        Parameters
        ----------
        x : numpy.ndarray
            expects a 1D array and finds norm values of columns
        method : str
            scaling method. Possible values: 'min_max', 'max_abs', 'standarize'
            and the log versions 'log_min_max', 'log_max_abs', 'log_standarize'

        lower : float
            lower range value of x_t after (log_)min_max scaling
        upper : float
            upper range value of x_t after (log_)min_max scaling

        Returns
        -------
        numpy.ndarray
            transformed version of x


Revert the scaling using the stored transform parameters.

        Parameters
        ----------
        x_t : numpy.ndarray
            expects a 1D array to unnormalize given the fitted transform.

        Returns
        -------
        numpy.ndarray
            denormalized x using the stored parameters.


Save complete interpolation model.

        Parameters
        ----------
        filename : str
            path/name of '.pkl' file where the model will be saved.


Load interpolation model to be used for predictions.

        filename : str
            path/name of pickle file to be loaded.


Evaluate given a binary object.


Convert grid object into data matrix.

        For this, the object will extract the columns indicated by the fields
        given in in_keys and out_keys, stacking them into a the matrix
        `self.XYT`. This matrix will have size N x (self.n_in).

        Parameters
        ----------
        grid : posydon.grids.psygrid.PSyGrid
            Grid of binaries to convert to data matrix.

        Returns
        -------
        numpy.ndarray
            data matrix with self.n_in columns that correspond to the inputs.


Normalize matrix X given the scaling options given by scaling.

        The normalized matrix will be stored as a class attribute.
        The function also stores DataScaler objects that allow for later
        denormalization of variables.


Normalize using learned scalers (_normalize) and apply to matrix X.

        X must have self.n_in columns and be a 2D nparray.

        Parameters
        ----------
        X : numpy.ndarray
            The input matrix to be normalized and of size [N x self.n_in].

        Returns
        -------
        numpy.ndarray
            The normalized test matrix of the same size as X where each column
            has been scaled independently.


Perform min-max scaling.

    Parameters
    ----------
    x : array_like
        The array that requires min-max rescaling.
    xmin : float
        The lower limit of the range to scale.
    xmax : float
        The upper limit of the range to scale.

    Returns
    -------
    ndarray
        The rescaled array of `x`.


Restore the original array of min-max rescaled array.

    Parameters
    ----------
    x : array_like
        The array which have been min-max rescaled.
    xmin : float
        The lower limit of the min-max range.
    xmax : float
        The upper limit of the min-max range.

    Returns
    -------
    ndarray
        The original array of `x` that have been min-max rescaled.


Successively perform min-max rescaling on the last dimension of `u`.

    Parameters
    ----------
    u : array_like
        The array which last dimension requires min-max rescaling.
    lim : sequence of tuple
        The tuples have length 2 and contains the limits on
        the min-max rescaling.
        There should be one tuple for each array in the last dimension.
    inv : bool
        If `False` then the standard min-max rescaling will be performed.
        If `True` then the inverse min-max rescaling
        to restore and array will be performed.

    Returns
    -------
    ndarray
        The rescaled/original array with the same shape as `u`.


Load the requested data to `grid_data`.

        Parameters
        ----------
        *args
            Associated initial masses
            which corresponding data should be loaded.


Infer the xfer_fraction from the system and mass-transfer rate.


Apply an "unequality constraint" (type 2) if needed.

    Parameters
    ----------
    fv_dict : dict
        The final values dictionary.
    key_sets : list of lists
        List of collections of keys connected with >= inequalities (descending
        order). E.g., if one constraint is `a >= b >= c`, then key_sets is
        [[a, b, c], ...].
    star : int
        For which star (1 or 2), the constraint will be applied. E.g.,
        `star_{}_mass` will be either `star_1_mass` or `star_2_mass`.
    log : bool
        If True, then the largest parameter (first key), is given in log10
        scale, while all the rest are in linear scale.

    Returns
    -------
    dict
        The sanitized version of `fv_dict`.


Normalize quantities should their sum does not have the expected value.

    Parameters
    ----------
    fv_dict : dict
        The final values dictionary.
    sum_keys : array-like
        Which quantities should add up to a specific value.
    constraint : float or str
        If float, then the sum of the quantities should be eqaul to that.
        If str, the fieldname of the quanity that the sum is constrained by.

    Returns
    -------
    dict
        The sanitized version of the final values dictionary.


Report possible issues with the order of application of constraints.

    TODO: this needs to be updated for the new types of constraints.


Find out which constraints can be applied.

    Find out which constraints can be applied based on the out_keys
    specified by the user. This function assumes that the keys for star 1
    have a corresponding key in star 2 when applicable.

    Parameters
    ----------
    out_keys : list of strings
        The keys specified in the IFInterpolator

    Returns
    -------
    list of dicts
        A list of constraints that can and will be applied


Apply constraints in final values returned from the IF interpolator.

    Parameters
    ----------
    fvalues : dict
        Dictionary containing the final values returned from the initial-final
        interpolator evaluation method.
    constraints : list of dicts
        A list of constraints that are to be applied. Can be computed using the
        find_constraints_to_apply function
    verbose: bool
        If True, report the actions.

    Returns
    -------
    dict
        The dictionary of sanitized final values.


Train the interpolator(s) on the PSyGrid used for construction.


Get the output vector approximation.

        Get the output vector approximation as well as all of the
        classifications given a Binary Star

        Parameters
        ----------
        binary : BinaryStar
            A class which is an input vector which are to be classified and for
            which an output vector will be approximated.

        Returns
        -------
        Output space approximation as a tuple containing two dictionary


Load a saved IFInterpolator from a .pkl file.

        Parameters
        ----------
        filename : string
            Path to the .pkl file


Save the interpolator to a .pkl file.

        Parameters
        ----------
        filename : string
            Path where .pkl file will be saved


Load interpolation model, which can only be used for predictions.

        Parameters
        ----------
        filename : str
            path/name of pickle file to be loaded.


Convert a PSyGrid to a numpy array.

        Parameters
        ----------
        grid : PSyGrid
            a loaded PSyGrid object

        Returns
        -------
        Two numpy arrays with the first being the input space and
        the second being the output space


Convert a binary instance to a numpy array.

        Parameters
        ----------
        binary : BinaryStar
            An initialized instance of the Binary star class

        Returns
        -------
        A binary as a numpy array


Set binary tracks as (in)valid depending on termination flags.


Train the interpolator.

        Parameters
        ----------
        ic : numpy array
            Contains the interpolation class for each track in the grid used
            for training the interpolator.


Train the classifiers.

        Paramaters
        ----------

        grid : PSyGrid
            The training grid
        method : string
            Specifies the classification method, default is kNN


Train a specific classifier.

        Paramaters
        ----------
        grid : PSyGrid
            The training grid
        method : string
            Specifies the classification method, default is kNN


Get the output vector approximation.

        Get the output vector approximation as well as all of the
        classifications given an input vector.

        Parameters
        ----------
        Xt : numpy array
            A list of input vectors which are to be classified and for which
            output vectors are to be approximated.

        Returns
        -------
        Output space approximations as numpy arrays


Get the output vector approximation.

        Get the output vector approximation as well as all of the
        classifications given a Binary Star.

        Parameters
        ----------
        binary : BinaryStar
            A class which is an input vector which are to be classified and for
            which an output vector will be approximated.

        Returns
        -------
        Output space approximation as a tuple containing two dictionary


Find if the (regular) grid was uniformly sampled in M_2 or q.

        Parameters
        ----------
        grid : posydon.grids.psygrid.PSyGrid
            Grid of binaries to convert to data matrix.

        Returns
        -------
        bool
            True if the grid was sampled in q.


Find the best scaling for the input space.


Find the best scaling for both input and output space.


Fill nan values i numerical magnitudes with 1NN.


Train the interpolator.

        Parameters
        ----------
        XT : numpy array
            List of input vectors
        YT : numpy array
            List of corresponding output vectors


Interpolate and approximate output vectors given input vectors.

        Parameters
        ----------
        XT : numpy array
            List of input vectors


Calculate approximation error given testing data.

        Parameters
        ----------
        XT : numpy array
            List of input vectors
        YT : numpy array
            List of corresponding output vectors


Interpolate and approximate output vectors given input vectors.

        Parameters
        ----------
        XT : numpy array
            List of input vectors
        scaler : #TODO
        klass : #TODO

        Returns
        -------
        Output space approximation as numpy array


Train the interpolator.

        Parameters
        ----------
        XT : numpy array
            List of input vectors
        YT : numpy array
            List of corresponding output vectors
        z : #TODO


Interpolate and approximate output vectors given input vectors.

        Parameters
        ----------
        XT : numpy array
            List of input vectors
        zpred : #TODO
        scaler : #TODO

        Returns
        -------
        Output space approximation as numpy array


Train the classifier.

        Parameters
        ----------
        XT : numpy array
            List of input vectors
        YT : numpy array
            List of corresponding classes


Classify and approximate classes given input vectors.

        Parameters
        ----------
        XT : numpy array
            List of input vectors

        Returns
        -------
        Output space approximation as numpy array


Classify and get probability of input vector belonging to any class.

        Parameters
        ----------
        XT : numpy array
            List of input vectors

        Returns
        -------
        Output space approximation as numpy array


Calculate approximation error given testing data.

        Parameters
        ----------
        XT : numpy array
            List of input vectors
        YT : numpy array
            List of corresponding classes


Train the classifier.

        Parameters
        ----------
        XT : numpy array
            List of input vectors
        YT : numpy array
            List of corresponding classes
        K : #TODO


Perform cross validation to find optimal k to use in classification.

        Parameters
        ----------
        XT : numpy array
            List of input vectors
        YT : numpy array
            List of corresponding classes


Scale input X.


Unscale input X.


Perform Monte Carlo Cross Validation; stratified if labels are provided.

    Parameters
    ----------
    N : int
        number of samples in the data set.
    percent_test : float
        Percentage of samples to be in the test sets. (0 < percent_test < 0.5)
    labels : #TODO

    Returns
    -------
    (np.ndarray, np.ndarray)
        1D int vectors containing the indices for train and test splits,
        respectively.


Train interpolators and classes and create assesment plots.

    Parameters
    ----------
    grid_train : string
        Path to training grid
    grid_test : string
        Path to testing grid
    ux2 : list of floats
        List containing the slices at which plots are to be generated. Slices
        are the 3rd variable in the input space, that is the mass of the second
        star for CO-HeMS and CO-HMS_RLO grids and the mass ratio for the
        HMS-HMS grid
    path : string
        The path where assesment plots will be saved
    classes : list of strings
        List containing the classes to be used in the MC-Interpolator


Assess models using a grid.

    Parameters
    ----------
    models : psi.Interpolator or list of psi.Interpolator
        Models to be evaluated.
    grid_T : psg.PSyGrid
        Train grid
    grid_t : psg.PSyGrid
        Test grid
    ux2 : #TODO
    path : #TODO


Find nans in input numerical variables.


Find None values in input categorical variables.


Plot confusion matrix as heatmap.


Plot confusion matrix for classification assessment.


Plot slices illustrating decision boundaries and classification prob.


Helper function for plot_mc_classifier.


Plot the interpolation errors by key.

    Parameters
    ----------
    m : IFInterpolator
        A trained instance of the IFInterpolator
    keys : List of strings
        Variables for which interpolation errors will be plotted
    v2 : #TODO
    ux2 : #TODO
    scales : #TODO
    path : #TODO


Make violin plots for the error distributions of each of the variables.

    Parameters
    ----------
    Ygt : numpy array
        Ground truth of the final values of testing tracks
    Ys : numpy array
        Model's approximation of the final values of testing tracks
    ind_MT : #TODO
    methods : List of strings
        List that indicates the interpolation methods
    keys : List of strings
        List indicating for which variables error distributions will be plotted
    path : #TODO


    NAME:
       vxta_deltav
    PURPOSE:
       construct the (v,x,t,apar) for the points at which to compute deltav for the GC stream
    INPUT:
       snap_gc - the snapshot of the GC stream
       apar - parallel angle along the stream
       acfs - the action-angle coordinates for the GC stream
    OUTPUT:
       (v,x,t,apar)
    HISTORY:
       2015-11-25 - Written - Bovy (UofT)


    NAME:
       impulse_deltav_plummerint
    PURPOSE:
       calculate the velocity kick using direct plummer integration, potentially for multiple particles
    INPUT:
       v - [nstar,3] velocity of the star to be kicked at the central time
       x - [nstar,3] position of the star to be kicked at the central time
       GM - mass of the Plummer sphere doing the kicking
       x0 - [nplum,3] position of the Plummer sphere doing the kicking *at the start*
       v0 - [nplum,3] velocity of the Plummer sphere doing the kicking *at the start*
       rs - scale radius of the Plummer sphere(s)
       tmax - time to integrate the interaction over
    OUTPUT:
       deltav [nstar,3]
    HISTORY:
       2015-11-23 - Written - Bovy (UofT)


    NAME:
       calc_impulse_curvedstream_deltav
    PURPOSE:
       Calculate the velocity kicks using the impulse approximation, but taking into account that stars move along the stream track
    INPUT:
       time - (string) time string identifying the DM simulation (0.125, 0.25, 0.375, or 0.50)
       savefilename - name of the file to save the deltav to
    OUTPUT:
       deltav [nstar,3]
    HISTORY:
       2015-11-24 - Written - Bovy (UofT)


    NAME:
       calc_fullplummer_deltav
    PURPOSE:
       Calculate the velocity kicks using full Plummer integration using a set of DM particles; each DM particle is considered separately
    INPUT:
       time - (string) time string identifying the DM simulation (0.125, 0.25, 0.375, or 0.50)
       savefilename - name of the file to save the deltav to
       ndm - number of DM particles to compute the kick for
       nfw= (False) if True, analyze the NFW simulations
    OUTPUT:
       deltav [nstar,3,ndm]
    HISTORY:
       2015-11-24 - Written - Bovy (UofT)
       2016-01-26 - Edited for NFW - Bovy (UofT)


Create an mp4 movie of a 3D array


Bins down high time resolution files to the resolution of a TPF.


Download and cache the quaternions


Download and cache the CBVs for a given sector, camera and CCD

    Note this function explicitly goes to the MAST archive and uses their file
    tree to find the best CBV. We go to the archive, and take the first file
    available in the FFI directory for a given sector. At time of writing, this is
    always the CBV, and let's us find new sector CBVs automatically.


Linearly solve an image stack...


 Iteratively finds the standard deviation of an array after sigma clipping

    Parameters
    ----------
    x : np.ndarray
        Array with average of zero
    mask : np.ndarray of bool
        Mask of same size as x, where True indicates a point to be masked.
    sigma : int or float
        The standard deviation at which to clip
    n_iters : int
        Number of iterations


Reparameterization trick by sampling from an isotropic unit Gaussian.

    # Arguments
        args (tensor): mean and log of variance of Q(z|X)

    # Returns
        z (tensor): sampled latent vector


 Change here from Cao paper, taking latents*log2pi outside
        the sum over latents


Boilerplate for pulling from the default dictionary if a desired key isn't present.


Boilerplate for checking units of a variable.


    Integral of blackbody surface flux at wavelengths from 0 to w.

    Parameters
    ----------
    w : astropy quantity, units of length
        wavelength to which to integrate
    T : astropy quantity, units of temperature
        temperature of blackbody

    Returns
    -------
    I : astropy quantity


    Quick computation of blackbody surface flux integrated within wbins.

    This is especially helpful if there are large wavelength bins where taking the value of the Planck function at the
    midpoint might give inaccurate results.

    Parameters
    ----------
    {wbins}
    T : astropy quantity, units of temperature
        temperature of blackbody
    bolometric : astropy quantity, units of energy time-1 length-2
        value of the bolometric blackbody flux by which to normalize the
        output.  A value of None gives the flux at the surface of the
        emitter.

    Returns
    -------
    flux_density : astropy quantity, units of energy time-1 length-3
        The flux spectral density of the blackbody in each wbin, generally in units of erg s-1 cm-2 AA-1.


    Compute the flux spectral density of the emission from a blackbody.

    Returns the value at each w, rather than the value averaged over wbins. For the latter, use blackbody_binned.

    Parameters
    ----------
    w : astropy quantity array, units of length
        Wavelengths at which to compute flux density.
    T : astropy quantity, units of temperature
        temperature of blackbody
    bolometric : astropy quantity, units of energy time-1 length-2
        value of the bolometric blackbody flux by which to normalize the
        output.  A value of None gives the flux at the surface of the
        emitter.

    Returns
    -------
    flux_density : astropy quantity, units of energy time-1 length-3
        The flux spectral density of the blackbody at each w, generally in units of erg s-1 cm-2 AA-1.


    Rebin some binned values.

    Parameters
    ----------
    bins_new : array
        New bin edges.
    bins_old : array
        Old bin edges.
    y : array
        Binned values (average of some function like a spectrum across
        each bin).

    Returns
    -------
    y_new : array
        Rebinned values.


    Random values drawn from a power-law distribution.

    Parameters
    ----------
    min : float
        Minimum value of the distribution.
    max : float
        Maximum value of the distribution.
    cumulative_index : float
        Index of the cumulative distribution.
    n : integer
        Number of values to draw.

    Returns
    -------
    values : array
        Array of random values.


    Generate random times of events that when binned into even intervals would yield counts that are Poisson distributed.

    Parameters
    ----------
    rate : float
        Average rate of events.
    time_span : float
        Length of time over which to generate events.

    Returns
    -------
    times : array
        Times at which random events occurr.


    Compute the lightcurve from one or more boxcar-decay functions.

    Parameters
    ----------
    tbins : array
        edges of the time bins used for the lightcurve
    t0 : float or array
        start times of the boxcar-decays
    area_box : float or array
        areas of the boxcar portion of the boxcar-decays
    height_box : float or array
        heights of the boxcar-decays
    area_decay : float or array
        areas of the decay portions of the boxcar-decays

    Returns
    -------
    y : array
        lightcurve values

    Notes
    -----
    This function is a bottleneck when creating a lightcurve from a long
    series of flares. If this code is to be adapted for quick simulation
    of years-long series of flares, this is where the speedup needs to
    happen.


    Convenience function for converting the energy in a photometric filter to the Si IV energy of a flare.

    Parameters
    ----------
    filter_wave : astropy quantity array, units of length
        Wavelengths of filter response curve.
    filter_response : array, unitless
        Filter response at filter_wave.
    energy : float or astropy quantity, units of energy
        Energy of the flare in the specified filter.
    {flare_params}

    Returns
    -------
    energy_SiIV : float or astropy quantity
        Energy of the flare in the Si IV 1393,1402 AA line.


    Return a lightcurve for a single flare normalized to quiescent flux.

    Parameters
    ----------
    {tbins}
    {t0}
    {eqd}
    {flare_params}

    Returns
    -------
    y : array
        Quiescent-normalized lightcurve of the flare.


    Rate of flares spanning the given energy range.

    Parameters
    ----------
    {flare_params}

    Returns
    -------
    rate : astropy quantity


    Start times and equivalent durations for a randomly generated series of flares.

    Parameters
    ----------
    time_span : astropy quantity, units of time
    {flare_params}

    Returns
    -------
    t_flare : astropy quantity array, units of time
        Start times of the random flares.
    eqd : astropy quantity array, units of time
        Equivalent durations of the random flares.


    Generate a series of random flares and return their lightcurve.

    Parameters
    ----------
    {tbins}
    return_flares : bool
        If True, return the start times and equivalent durations of
        the flares.
    {flare_params}

    Returns
    -------
    y : array
        Quiescent-normalized ightcurve values in each tbin.
    tflares : astropy quantity array, units of time, optional
        Start time of random flares.
    eqd : astropy quantity array, units of time, optional
        Equivalent durations of the random flares.


    Return the flare spectrum scaled to match the energy or equivalent duration specified by SiIV and binned according
    to wbins.

    Parameters
    ----------
    {wbins}
    SiIV : float or astropy quantity
        Equivalent duration or energy of the flare in the Si IV 1393,1402 AA
        line. This could also be peak flux or some other quantity, but note
        that you should probably specificy your own 'Edensity' column of  the
        SiIV_normed_flare_spec table to match if so.
    {flare_params}

    Returns
    -------
    spectrum : astropy quantity array, units variabile according to units of SiIV
        Energy spectral density or other spectral density of the flare spectrum
        in each wbin.


    Return a series of flare spectra averaged over each tbin for a flare starting at t0 with equivalent duration eqd
    in Si IV.

    Parameters
    ----------
    {wbins}
    {tbins}
    {t0}
    {eqd}
    {flare_params}

    Returns
    -------
    spectra : astropy quantity array, variable units
        Array of spectra in each tbin, where the array has dimensions
        (len(tbins)-1, len(wbins)-1). Units will match the product
        of the eqd and SiIV_quiescent units, divided by time and length.


    Generate time-evolving spectra from a random series of flares.

    Parameters
    ----------
    {wbins}
    {tbins}
    {flare_params}

    Returns
    -------
    spectra : astropy quantity array
        Array of spectra in each tbin, where the array has dimensions
        (len(tbins)-1, len(wbins)-1). Units will match the product of
        the eqd and SiIV_quiescent units, divided by time and length.


 The main attributes of the object are filled:

                "cols": {
                    "ALKALI": {
                        "external_name": ["alkali"],  # just one element in project settings
                        "attrs": ["param", "required", ],
                        "data_type": "float",
                        "unit": "UMOL/KG",
                        "precision": 3,
                        "export": True
                    },
                    "ALKALI_FLAG_W": {
                        "external_name": [],
                        "attrs": ["flag", ],
                        "data_type": "integer"
                        "unit": False,  # >> False
                        "precision": 0,
                        "export": True
                    }
                }


 Checks if the file has an unit row or not.
            The df should have all strings and nan values
                * if there is at least one nan in the row               > unit row
                * if all the cells are strings                          > unit row
                * if there is at least one number (stored as string)    > no unit row


 Returns True if the string is a number:
                    float or integer


 Assign 9 to the rows where the param has an NaN
            Also checks if there is any NaN or incorrect value in the flag columns


 Adds a column to the self.cols dictionary
            This dictionary is useful to select some columns by type
                * required      - required columns
                * param         - parameter columns
                * flag          - flag columns
                * non_qc        - parameters without flag columns associated
                * computed      - computed parameters
                * created       - if the column was created by the app

            TODO: add all arguments or add a param as a dictionary with all the attributes
                  this method also should work if something should be modified or removed?


Make sure there is a flag column for each param parameter