    It loads the payload information and returns a dictionary containing the payload,
    a dictionary with the channels already built,
    and a couple with minimum and maximum wavelength investigated by the payload

    Parameters
    ----------
    payload_file: str
        xml file with payload description
    output: str
        h5 output file

    Returns
    -------

    dict:
        payload dictionary
    dict:
        channels dictionary
    couple:
        minimum and maximum investigated wavelength

    Examples
    --------
    >>> preparePayload = PreparePayload()
    >>> payload, channels, (wl_min, wl_max) = PreparePayload(payload_file=payload, output=output)


    Merges the channels output tables

    Parameters
    ----------
    channels: dict

    Returns
    ---------
    Table


    Returns a list of the channels of the specific type that are contained in the instrument options file

    Parameters
    ----------
    options: object
        payload description
    channel_type: string
        type of channel to find

    Returns
    -------
    list:
        list of strings with channel names

    Examples
    --------
    >>> from exorad.tasks.loadOptions import LoadOptions
    >>> loadOptions = LoadOptions()
    >>> options = loadOptions(filename = 'path/to/file.xml')
    >>> getDetectorList = GetChannelList()
    >>> photometers_list = getDetectorList(options = options, channel_type = 'Photometer')
    >>> spectrometers_list = getDetectorList(options = options, channel_type = 'Spectrometer')


    Updates target with its source and return the source Sed

    Parameters
    ----------
    target: Target Class
        target class
    source: dict
        source spectrum description
    wl_range: couple
        wavelength range to investigate: (wl_min, wl_max)

    Returns
    -------
        Target:
            Target class with star.sed updated
        Sed:
            source Sed

    Examples
    --------
    >>> loadSource = LoadSource()
    >>> target, source = loadSource(target= target, source={'sourceSpectrum': {'value':'Planck'}})

    Raises
    ------
    AttributeError:
        if some target information are missing


    Loads target list from file

    Parameters
    ----------
    target_list: str
        target list file address. Supported formats are csv and xml

    Returns
    -------
    TargetList:
        return a list of Target class

    Examples
    --------
    >>> loadTargetList = LoadTargetList()
    >>> targets = loadTargetList(target_list='target_list/address')


    Prepares the target output table over the channels to populate with light propagation

    Parameters
    ----------
    target: Target
        target to prepare
    channels : dict
        channel dictionary

    Returns
    -------
    Target:
        same target with table attribute populated


    Updated the target output table over the channels to populate with light propagation

    Parameters
    ----------
    target: Target
        target to prepare
    table : QTable
        table to merge in the target table

    Returns
    -------
    Target:
        same target with table attribute updated


    Updated the target output table with maximum estimated signal in pix column

    Parameters
    ----------
    target: Target
        target to prepare

    Returns
    -------
    Target:
        same target with table attribute updated


    Standard pipeline for target observation. It includes:
    1. PrepareTarget,
    2. EstimateForegrounds,
    3. PropagateForegroundLight
    4. LoadSource
    5. PropagateTargetLight
    6. EstimateNoise

    Parameters
    ----------
    target: Target
        target to prepare
    payload : dict
        payload description
    channels : dict
        channel dictionary
    wl_range: (float, float)
        wavelength range to investigate. (wl_min, wl_max)

    Returns
    -------
    Target:
        same target with table attribute updated


    Standard pipeline to observe a full targetlist. It allows parallelization:

    Parameters
    ----------
    targets: Target
        targets to prepare
    payload : dict
        payload description
    channels : dict
        channel dictionary
    wl_range: (float, float)
        wavelength range to investigate. (wl_min, wl_max)
    plot: bool
        allow to save plots
    out_dir: str
        indicate the directory where to save plots
    n_thread: int
        number of threads
    debug: bool
        debug mode

    Returns
    -------
    dict:
        targets dict


    Instantiate a Stellar class using Phenix Stellar Models

    Attributes
    ----------
    lumiosity : 		float
                Stellar bolometric luminosity computed from Phenix stellar modle. Units [W]
    wl				array
                wavelength [micron]
    sed 			array
                Spectral energy density [W m**-2 micron**-1]
    ph_wl			array
                phoenix wavelength [micron]. Phenix native resolution
    ph_sed 			array
                phenix spectral energy density [W m**-2 micron**-1]. Phenix native resolution
    ph_filename 		phenix filename


It's a Signal class with data having units of [hr^1/2]


    Signal class is the main class for every wavelength and time dependent object.
    By default it assume wavelength in um, data dimensionless and time in hours.

    Parameters
    ----------
    wl_grid: quantity
        wavelength grid. Must have a single axes
    data: array
        data table. Can have 2 axes
    time_grid: quantity (optional)
        time grid. Must have a single axes

    Attributes
    ----------
    wl_grid: quantity(um)
        wavelength grid. Must have a single axes
    data: quantity(dimensionless)
        data table. Can have 2 axes
    time_grid: quantity(hr)
        time grid. Must have a single axes
    time_dependent: bool
        it tells if the signal is time dependent (True) or not (False)

    Examples
    ---------
    >>> import numpy as np
    >>> wl = np.linspace(0.1,1, 10)*u.um
    >>> data = np.random.random_sample((10,10))
    >>> time = np.linspace(1,5, 10)*u.hr
    >>> signal = Signal(wl_grid=wl, data=data, time_grid=time)


It's a Signal class with data having units custom units


It's a Signal class with data having units of [W m^-2 mu^-1]


It's a Signal class with data having units of [W m^-2 mu^-1 sr^-1]


It's a Signal class with data having units of [ct/s]


Target base class


Target list base class


It parses a .xlsx file into a :class:`BaseTargetList` class


It parses a csv file into a :class:`BaseTargetList` class


It parses an .xls file into a :class:`BaseTargetList` class


It parses an :class:`astropy.table.QTable` into a :class:`BaseTargetList` class


Photometer instrument class.


Spectrometer instrument class.


    Abstract Instrument class. Contains the basic function that every instrument needs.

    Parameters
    -----------
    name: str
        instrument name
    description: dict
        instrument description dictionary
    payload: dict
        main payload. Default is None

    Attributes
    ----------
    name: str
        instrument name
    description: dict
        instrument description dictionary
    payload: dict
        main payload. Default is None
    table: QTable
        contain the output grid for the instrument
    built_instr: dict
        contains the instrument parameters needed to propagate the signal

    Raises
    -------
    ValueError:
        if you try to build a loaded payload.


    Handler for sky filter

    Attributes
    ----------
    transmission: array
        contains the transmission information sampled at the radiance wl grid


    Produce the zodiacal radiance.

    Parameters
    ----------
    wl: array
        wavelength grid
    description: dict
        zodiacal foreground description
    coordinates: (float, float)
        pointing coordinates as (ra, dec)

    Attributes
    -----------
    wl: array
        wavelength grid
    description: dict
        zodiacal foreground description dict
    radiance: Radiance
        zodiacal radiance


    Handler for instrument radiance.

    Attributes
    ----------
    position : str
        Position of the optical element in the optical path.
        Default is 'path'.
    slit : None or bool
        Indicates if a slit is present in the optical path.


    Handler for instrument diffuse light.

    Parameters
    ----------
    description : dict
        Optic description.
    wl : array_like
        Wavelength grid as a quantity array.

    Attributes
    ----------
    optical_element_dict : dict
        Dictionary of `OpticalElement` instances.
    radiance_dict : dict
        Dictionary of `InstRadiance` instances.
    radiance_table : QTable
        Table of optical elements radiance.
    transmission_table : QTable
        Table of optical elements transmissions.
    signal_table : QTable
        Table of optical elements signals.
    max_signal_per_pixel : QTable
        Table of optical elements max signal per pixel.
    slit_width : Quantity or None
        Slit width measurement, if a slit is in the optical path. Default is None.

    Methods
    -------
    prepend_optical_elements(optical_element_dict)
        Updates the class `optical_element_dict` by putting the input dictionary
        at the top of the existing one.
    chain()
        Concatenates the optical elements, producing the `radiance_table` and `radiance_dict`.
    build_transmission_table()
        Produces the transmission table for the optical path.
    compute_signal(ch_table, ch_built_instr)
        Produces the telescope self-emission signal for the channel and returns
        the updated channel table.

    Examples
    --------
    >>> telescope = OpticalPath(wl=wl_grid, description=options)
    >>> spec = OpticalPath(wl=wl_grid, description=options['channel']['Spec'])
    >>> spec.prepend_optical_elements(telescope.optical_element_dict)
    >>> spec.build_transmission_table()
    >>> spec.chain()


    Handler for an optical element.

    This class represents an optical element within an optical path, managing its
    transmission, emissivity, temperature, and other relevant properties.

    Parameters
    ----------
    description : dict
        Dictionary containing the optical element's description from the payload
        configuration file.
    wl : `astropy.units.Quantity` or array_like
        Wavelength grid where the optical properties of the element are evaluated.
        Should have units of length (e.g., microns).

    Attributes
    ----------
    name : str
        Name of the optical element.
    description : dict
        Original description dictionary of the optical element.
    wl : `astropy.units.Quantity` or array_like
        Wavelength grid.
    transmission : `numpy.ndarray`
        Transmission of the optical element evaluated over the wavelength grid.
    emissivity : `numpy.ndarray`
        Emissivity of the optical element evaluated over the wavelength grid.
    temperature : `astropy.units.Quantity` or None
        Temperature of the optical element in Kelvin. `None` if not specified.
    type : str
        Type of the optical element (e.g., "detector box", "optics box", "surface").
    position : str
        Position of the optical element in the optical path (e.g., "detector",
        "optics box", "path").
    angle : `astropy.units.Quantity` or None
        Solid angle associated with the optical element in steradians. `None` if
        not specified.

    Methods
    -------
    _get_angle()
        Retrieves and processes the solid angle of the optical element.
    _get_position()
        Determines the position of the optical element in the optical path.
    _get_temperature()
        Retrieves and processes the temperature of the optical element.
    _get_transmission()
        Calculates the transmission of the optical element over the wavelength grid.
    _get_emissivity()
        Calculates the emissivity of the optical element over the wavelength grid.


    Plotter class. It offers a fast and easy way to produce diagnostic plots on the produced data.

    Parameters
    -----------
    input_table: Qtable
        table where to grab data and wl grid to plot.
    channels: dict
        dictionary describing the channels in the payload. Default is None


    The Singleton class can be implemented in different ways in Python. Some
    possible methods include: base class, decorator, metaclass. We will use the
    metaclass because it is best suited for this purpose.


Class used to propagate values through the code.


Standard logging using logger library


Structure containing data from a Mesa output file.
    Reads a profile or history output file from mesa. Assumes a file with
    the following structure:
    - line 1: header names
    - line 2: header data
    - line 3: blank
    - line 4: main data names
    - line 5: main data values
    This structure can be altered by using the class methods
    MesaData.set_header_rows and MesaData.set_data_rows.
    Parameters
    ----------
    file_name : str, optional
        File name to be read in. Default is 'LOGS/history.data', which works
        for scripts in a standard work directory with a standard logs directory
        for accessing the history data.
    Attributes
    ----------
    file_name : str
        Path to file from which the data is read.
    bulk_data : numpy.ndarray
        The main data (line 6 and below) in record array format. Primarily
        accessed via the `data` method.
    bulk_names : tuple of str
        Tuple of all available data column names that are valid inputs for
        `data`. Essentially the column names in line 4 of `file_name`.
    header_data : dict
        Header data (line 2 of `file_name`) in dict format
    header_names : list of str
        List of all available header column names that are valid inputs for
        `header`. Essentially the column names in line 1 of `file_name`.


Structure containing data from the profile index from MESA output.
    Reads in data from profile index file from MESA, allowing a mapping from
    profile number to model number and vice versa. Mostly accessed via the
    MesaLogDir class.
    Parameters
    ----------
    file_name : str, optional
        Path to the profile index file to be read in. Default is
        'LOGS/profiles.index', which should work when the working directory is
        a standard work directory and the logs directory is of the default
        name.
    Attributes
    ----------
    file_name : str
        path to the profile index file
    index_data : dict
        dictionary containing all index data in numpy arrays.
    model_number_string : str
        header name of the model number column in `file_name`
    profile_number_string : str
        header name of the profile number column in `file_name`
    profile_numbers : numpy.ndarray
        List of all available profile numbers in order of their corresponding
        model numbers (i.e. time-order).
    model_numbers : numpy.ndarray
        Sorted list of all available model numbers.


Structure providing access to both history and profile output from MESA
    Provides access for accessing the history and profile data of a MESA run
    by linking profiles to the history through model numbers.
    Parameters
    ----------
    log_path : str, optional
        Path to the logs directory, default is 'LOGS'
    profile_prefix : str, optional
        Prefix before profile number in profile file names, default is
        'profile'
    profile_suffix : str, optional
        Suffix after profile number and period for profile file names, default
        is 'data'
    history_file : str, optional
        Name of the history file in the logs directory, default is
        'history.data'
    index_file : str, optional
        Name of the profiles index file in the logs directory, default is
        'profiles.index'
    memoize_profiles : bool, optional
        Determines whether or not profiles will be "memo-ized", default is
        True. If memoized, once a profile is called into existence, it is saved
        so that it need not be read in again. Good for quick, clean, repeated
        access of a profile, but bad for reading in many profiles for one-time
        uses as it will hog memory.
    Attributes
    -----------
    log_path : str
        Path to the logs directory; used (re-)reading data in
    profile_prefix : str
        Prefix before profile number in profile file names
    profile_suffix : str
        Suffix after profile number and period for profile file names
    history_file : str
        Base name (not path) of the history file in the logs directory
    index_file : str
        Base name (not path) of the profiles index file in the logs directory
    memoize_profiles : bool
        Determines whether or not profiles will be "memo-ized". Setting this
        after initialization will not delete profiles from memory. It will
        simply start/stop memoizing them. To clear out memoized profiles,
        re-read the data with `self.read_logs()`
    history_path : str
        Path to the history data file
    index_path : str
        Path to the profile index file
    history : mesa_reader.MesaData
        MesaData object containing history information from `self.history_path`
    history_data : mesa_reader.MesaData
        Alias for `self.history`
    profiles : mesa_reader.MesaProfileIndex
        MesaProfileIndex from profiles in `self.index_path`
    profile_numbers : numpy.ndarray
        Result of calling `self.profiles.profile_numbers`. Just the profile
        numbers of the simulation in order of corresponding model numbers.
    model_numbers : numpy.ndarray
        Result of calling `self.profiles.model_numbers`. Just the model numbers
        of the simulations that have corresponding profiles in ascending order.
    profile_dict : dict
        Stores MesaData objects from profiles. Keys to this dictionary are
        profile numbers, so presumably `self.profile_dict(5)` would yield the
        MesaData object obtained from the file `profile5.data` (assuming
        reasonable defaults) if such a profile was ever accessed. Will remain
        empty if memoization is shut off.


an index that we want to set


a simple object to keep track of how many variables there are in a
    set


Use mcaf to create new SDM from bdf


Placeholder for description of SMP class


A general task template.


Timestream task template.


A task to process the raw timestream data along the axis of baseline.


Circular beam of a dish antenna.


Beam of a cylinder feed.


Representation of an individual dish antenna or cylinder feed.


Representation of an individual dish antenna.


Representation of an individual cylinder feed.


A celestial source.


A source at fixed RA,DEC.  Combines ephem.FixedBody with RadioBody.


Class to do the calibration.


The SumThreshold method.

    For more details, see Offringa et al., 2000, MNRAS, 405, 155,
    *Post-correlation radio frequency interference classification methods*.


Local average fit method.

    In this method, the background value is caculated by the local average of a
    sliding window of size :math:`N \\times M` around each data value.


Spline interpolation method.

    This is not really a surface fit method, but intended to fill masked
    (or invalid) values presented in the data by spline interpolation.


Local minimum fit method.

    In this method, the background value is caculated by the local minimum of a
    sliding window of size :math:`N \\times M` around each data value.


Gaussian filter method.

    In this method, the background is caculated by a Gaussian high pass
    filtering process.


Abstract base class for surface fitting methods.

    A surface fit to the correlated visibilities :math:`V(\\nu, t)` as a
    function of frequency :math:`\\nu` and time :math:`t` can produce a
    surface :math:`\\hat{V}(\\nu, t)` that represents the astronomical
    information in the signal. Requiring :math:`\\hat{V}(\\nu, t)` to be
    a smooth surface is a good assumption for most astronomical continuum
    sources, as their observed amplitude tend not to change rapidly with
    time and frequency, whereas specific types of RFI can create sharp edges
    in the time-frequency domain. The residuals between the fit and the data
    contain the system noise and the RFI, which can then be thresholded
    without the chance of flagging astronomical sources that have visibilities
    with high amplitude.

    .. note::
        Because of the smoothing in both time and frequency direction, this
        method is not directly usable when observing strong line sources or
        strong pulsars.


Abstract base class for combinatorial thresholding methods.

    The method will flag a combination of samples when a property of this
    combination exceeds some limit. The more connected samples are combined,
    the lower the sample threshold.

    For more details, see Offringa et al., 2000, MNRAS, 405, 155,
    *Post-correlation radio frequency interference classification methods*.

    For this implementation, the sequence of thresholds are determined by
    the following formula:

    .. math:: \\alpha \\times \\frac{\\rho^{i}}{w} \\times (\\sigma \\times \\beta) + \\eta

    in which :math:`\\alpha` is the first threshold set to 6.0,
    :math:`\\rho = 1.5`, :math:`i` is the current iteration, :math:`w` the
    current window size, :math:`\\sigma` the standard deviation of the values,
    :math:`\\beta` the base sensitivity, set to 1.0, and :math:`\\eta` the
    median.


The VarThreshold method.

    For more details, see Offringa et al., 2000, MNRAS, 405, 155,
    *Post-correlation radio frequency interference classification methods*.


Local median fit method.

    In this method, the background value is caculated by the local median of a
    sliding window of size :math:`N \\times M` around each data value.


Abstract base class for local fit method.


Class to do the map-making.


A class for applying attribute values from a supplied dictionary.

    DEPRECATED!! Use routines from drift.util.config instead.


A Telescope describing an interferometric array of dishes.

    Attributes
    ----------
    gridu, gridv : integer
        Number of dishes in u and v directions.
    dish_width : scalar
        Width of the dish in metres.


A base for a polarised telescope.

    Again, an abstract class, but the only things that require implementing are
    the `feedpositions`, `_get_unique` and the beam functions `beamx` and `beamy`.

    Abstract Methods
    ----------------
    beamx, beamy : methods
        Routines giving the field pattern for the x and y feeds.


A abstract base class describing the Tianlai dishe array for inheriting by sub-classes.

    Attributes
    ----------
    ants : list
        List of antennas to use, number starts from 1.
    zenith : [lat, lon]
        Geometric position of the array.
    pointing: [az, alt, twist]
        Antenna beam to point at (az, alt) with specified right-hand twist to polarizations.
        Polarization y is assumed to be +pi/2 azimuth from pol x.
    freq_lower, freq_higher : scalar
        The lower / upper bound of the lowest / highest frequency bands.
    num_freq : scalar
        The number of frequency bands (only use for setting up the frequency
        binning). Generally using `nfreq` is preferred.
    tsys_flat : scalar
        The system temperature (in K). Override `tsys` for anything more
        sophisticated.
    dish_width : scalar
        Width of the dish in metres.
    center_dish : integer
        The reference dish.
    freq_inds: list
        Choose frequency channels to include.


A Telescope describing the Tianlai non-polarized dishe array.

    See Also
    --------
    This class also inherits some useful properties, such as `zenith` for
    giving the telescope location and `tsys_flat` for giving the system
    temperature.


Common functionality for all Cylinder Telescopes.

    Attributes
    ----------
    num_cylinders : integer
        The number of cylinders.
    num_feeds : integer
        Number of regularly spaced feeds along each cylinder.
    cylinder_width : scalar
        Width in metres.
    feed_spacing : scalar
        Gap between feeds in metres.
    in_cylinder : boolean
        Include in cylinder correlations?
    touching : boolean
        Are the cylinders touching (no spacing between them)?
    cylspacing : scalar
        If not `touching` this is the spacing in metres.


A complete class for an Unpolarised Cylinder telescope.


A telescope describing the Tianlai non-polarized cylinder array.


Modified KL technique that performs a first transformation to remove
    foreground modes, and a subsequent transformation to diagonalise the full
    noise (remaining foregrounds+instrumental space).

    Attributes
    ----------
    foreground_threshold : scalar
        Ratio of S/F power below which we throw away modes as being foreground
        contaminated.


Perform KL transform.

    Attributes
    ----------
    subset : boolean
        If True, throw away modes below a S/N `threshold`.
    threshold : scalar
        S/N threshold to cut modes at.
    inverse : boolean
        If True construct and cache inverse transformation.
    use_thermal, use_foregrounds : boolean
        Whether to use instrumental noise/foregrounds (default: both True)
    _foreground_regulariser : scalar
        The regularisation constant for the foregrounds. Adds in a diagonal of
        size reg * cf.max(). Default is 2e-15


An extension of the PSEstimation class to support estimation of the
    Fisher matrix via Monte-Carlo simulations.

    This uses the fact that the covariance of the q-estimator is the Fisher
    matrix to Monte-Carlo the Fisher matrix and the bias. See Padmanabhan and
    Pen (2003), and Dillon et al. (2012).

    Attributes
    ----------
    nsamples : integer
        The number of samples to draw from each band.


An extension of the PSEstimation class to support estimation of the
    Fisher matrix via Monte-Carlo simulations.

    This uses a stochastic estimation of the trace which allows us to compute
    a reduced set of products between the four covariance matrices.

    Attributes
    ----------
    nswitch : integer
        The threshold number of eigenmodes above which we switch to Monte-Carlo
        estimation.
    nsamples : integer
        The number of samples to draw from each band.


Scale up point source amplitude to a higher S_{cut} = 0.1 Jy


Base class for simulating any transit interferometer.

    This is an abstract class, and several methods must be implemented before it
    is usable. These are:

    * `feedpositions` - a property which contains the positions of all the feeds
    * `_get_unique` -  calculates which baselines are identical
    * `_transfer_single` - calculate the beam transfer for a single baseline+freq
    * `_make_matrix_array` - makes an array of the right size to hold the
      transfer functions
    * `_copy_transfer_into_single` - copy a single transfer matrix into a
      collection.

    The last two are required for supporting polarised beam functions.

    Properties
    ----------
    zenith : [theta, phi]
        The position of the zenith spherical polars (in radians). Read only.
    freq_lower, freq_higher : scalar
        The center of the lowest and highest frequency bands.
    num_freq : scalar
        The number of frequency bands (only use for setting up the frequency
        binning). Generally using `nfreq` is preferred.
    tsys_flat : scalar
        The system temperature (in K). Override `tsys` for anything more
        sophisticated.
    positive_m_only: boolean
        Whether to only deal with half the `m` range. In many cases we are
        much less sensitive to negative-m (depending on the hemisphere, and
        baseline alignment). This does not affect the beams calculated, only
        how they're used in further calculation. Default: False
    minlength, maxlength : scalar
        Minimum and maximum baseline lengths to include (in metres).
    local_origin : bool
        If set the observers location is the terrestrial origin, and so the
        rotation angle corresponds to the right ascension that is overhead
        (Local Stellar Angle in `caput.time`). If not the origin is Greenwich,
        so the rotation angle is what is overhead at Greenwich (Earth Rotation
        Angle).


A base for an unpolarised telescope.

    Again, an abstract class, but the only things that require implementing are
    the `feedpositions`, `_get_unique` and the `beam` function.


A base for a unpolarised telescope.

    Again, an abstract class, but the only things that require implementing are
    the `feedpositions`, `_get_unique` and the beam functions `beamx` and `beamy`.

    Abstract Methods
    ----------------
    beam : method
        Routines giving the field pattern for the feeds.


A class for reading and writing Beam Transfer matrices from disk.

    In addition this provides methods for projecting vectors and matrices
    between the sky and the telescope basis.

    Parameters
    ----------
    directory : string
        Path of directory to read and write Beam Transfers from.
    telescope : drift.core.telescope.TransitTelescope, optional
        Telescope object to use for calculation. If `None` (default), try to
        load a cached version from the given directory.

    Attributes
    ----------
    svcut
    polsvcut
    ntel
    nsky
    nfreq
    svd_len
    ndofmax

    Methods
    -------
    ndof
    beam_m
    invbeam_m
    beam_svd
    beam_ut
    invbeam_svd
    beam_singularvalues
    generate
    project_vector_sky_to_telescope
    project_vector_telescope_to_sky
    project_vector_sky_to_svd
    project_vector_svd_to_sky
    project_vector_telescope_to_svd
    project_matrix_sky_to_telescope
    project_matrix_sky_to_svd


BeamTransfer class that performs the old temperature only SVD.


Base class for quadratic powerspectrum estimation.

    See Tegmark 1997 for details.

    Attributes
    ----------
    bandtype : {'polar', 'cartesian'}
        Which types of bands to use (default: polar).

    k_bands : np.ndarray
        Array of band boundaries. e.g. np.array([0.0, 0.5, ]), polar only
    num_theta: integer
        Number of theta bands to use (polar only)

    kpar_bands : np.ndarray
        Array of band boundaries. e.g. np.array([0.0, 0.5, ]), cartesian only
    kperp_bands : np.ndarray
        Array of band boundaries. e.g. np.array([0.0, 0.5, ]), cartesian only

    threshold : scalar
        Threshold for including eigenmodes (default is 0.0, i.e. all modes)

    unit_bands : boolean
        If True, bands are sections of the exact powerspectrum (such that the
        fiducial bin amplitude is 1).

    zero_mean : boolean
        If True (default), then the fiducial parameters have zero mean.


PS Estimation class with exact calculation of the Fisher matrix.


Waterfall plot for Timestream.

    This task plots the waterfall (i.e., visibility as a function of time
    and frequency) of the visibility
    for each baseline (and also each polarization if the input data is a
    :class:`~tlpipe.container.timestream.Timestream` instead of a
    :class:`~tlpipe.container.raw_timestream.RawTimestream`).


Plot phase of a time-frequency slice.

    This task plots the phase of a time-frequency visibility slice
    for each baseline (and also each polarization if the input data is a
    :class:`~tlpipe.container.timestream.Timestream` instead of a
    :class:`~tlpipe.container.raw_timestream.RawTimestream`).


Plot time or frequency slices.

    This task plots a given number of time (or frequency) slice of the visibility
    for each baseline (and also each polarization if the input data is a
    :class:`~tlpipe.container.timestream.Timestream` instead of a
    :class:`~tlpipe.container.raw_timestream.RawTimestream`).


Plot time or frequency integral.

    This tasks plots the real, imagery part and the absolute value of the
    time or frequency integrated visibility for each baseline (and also each
    polarization if the input data is a
    :class:`~tlpipe.container.timestream.Timestream` instead of a
    :class:`~tlpipe.container.raw_timestream.RawTimestream`).


Module to estimate the power spectrum.


Class to subtract the foreground.


This stops the iteration of `next()` in pipeline tasks.

    Pipeline tasks should raise this exception in the `next()` method to stop
    the iteration of the task and to proceed to `finish()`.

    Note that if `next()` receives input data as an argument, it is not
    required to ever raise this exception.  The pipeline will proceed to
    `finish()` once the input data has run out.


Pipeline manager for setting up and running pipeline tasks.

    The manager is in charge of initializing all pipeline tasks, setting them
    up by providing the appropriate parameters, then executing the methods of
    each task in the appropriate order. It also handles intermediate data
    products and ensuring that the correct products are passed between tasks.


Base class for all pipeline tasks.

    All pipeline tasks should inherit from this class, with functionality and
    analysis added by over-riding `__init__`, `setup`, `next` and/or
    `finish`.

    In addition, input parameters may be specified by adding adding entries
    (key and default value) in the class attribute `params`, which will then
    be updated by the corresponding parameters setttin in the input pipeline file.


Do nothing.

    This task will actually do nothing and its :meth:`next` is never called,
    since the pipeline never generates its input, 'non_existent_input'.
    As this task method is missing its input, as specified by the 'requires'
    or 'in' keys, the pipeline will restart at the beginning of the `tasks`
    list once it get to this task. Once everything before :class:`DoNothing`
    has been executed, the pipeline notices that there is no opertunity for
    'non_existent_input' to be generated and forces `DoNothing` to proceed to
    :meth:`finish`. This then unblocks its following tasks, allowing them to
    proceed normally.

    This may be useful when devise non-trivial pipeline flow.


Base class for tasks that have (at most) one input and one output.

    The input for the task will be preferably get from the `in` key, if no input
    product is specified by the `in` key, then input will be get from the files
    specified by the value of :attr:params[`input_files`] if it is anything other
    None, otherwise an error will be raised upon initialization.

    If the value of :attr:params[`output_files`] is anything other than None
    then the output will be written (using :meth:`write_output`) to the specified
    output files.


Base class for iterating tasks over input files.

    Tasks inheriting from this class should override :meth:`process` and
    optionally :meth:`setup`, :meth:`finish`, :meth:`read_input`,
    :meth:`write_output` and :meth:`cast_input`. They should not override
    :meth:`next`.


RFI flagging.

    RFI flagging by using the SumThreshold method.


Exceptional values flagging along the time axis.

    This flags the data along the time axis by comparing the data with its
    smoothing, its difference that exceed the given threshold will be masked.


Delay transform.

    Doing delay transform of the visibility, i.e., Fourier transform along
    the frequency axes.


Average the accumulated data by dividing its weight.

    This task works for the accumulated data returned by task
    :class:`~tlpipe.timestream.accumulate.Accum`.


Calibration by strong point source fitting.

    This works by minimize

    .. math:: \\chi^2 = \| V_{ij}^{\\text{obs}}(t + \\Delta t) - G_{ij} V_{ij}^{\\text{sim}}(t) \|^2

    Its solution is

    .. math:: G_{ij} = \\frac{V_{ij}^{\\text{sim} \\dagger} V_{ij}^{\\text{obs}}}{V_{ij}^{\\text{sim} \\dagger} V_{ij}^{\\text{sim}}}


Phase the zenith-phased visibility data to a source.

    The phasing is done by divide the visibility by the reference phase of
    the given *source*, as

    .. math:: V_{ij}^{\\text{phs}} = V_{ij} \\, / \\, e^{2 \\pi i \\, \\boldsymbol{s}_0 \\cdot \\boldsymbol{u}_{ij}}

    This will make the visibility has a phase reference center at the location
    of the given *source*.


Re-order data to have longitude from 0 to 2pi.

    By doing this, data of different days can be accumulated and averaged.


RFI flagging by using Local Outlier Factor (LOF).

    LOF is an unsupervised outlier detection algorithm.

    The anomaly score of each sample is called Local Outlier Factor. It
    measures the local deviation of density of a given sample with respect
    to its neighbors. It is local in that the anomaly score depends on how
    isolated the object is with respect to the surrounding neighborhood.
    More precisely, locality is given by k-nearest neighbors, whose distance
    is used to estimate the local density. By comparing the local density of
    a sample to the local densities of its neighbors, one can identify
    samples that have a substantially lower density than their neighbors.
    These are considered outliers.

    We use the algorithm implemented in sklearn.neighbors.LocalOutlierFactor.


RFI statistics.

    Analysis of RFI distributions along time and frequency.


Combine RFI masks of all four polarizations.

    If a sample in one polarization is flagged, the sample will be flagged
    in all polarizations. This is done by stacking the masks of the XX, YY,
    XY and YX polarizations.


Mask the given time sections.


Initialize telescope array, average the timestream and do the map-making.

    This task calls the submodule :mod:`~tlpipe.map.drift` which uses the m-mode
    formalism method to do the map-making.


Exceptional values flagging along the frequency axis.

    This task does a very simple flagging by masking data points whose
    absolute value exceed a given threshold (in unit of std of the data)
    along the frequency axis.


Normalize the m-mode generated by DFT of the timestream data.


Relative phase calibration using the noise source signal.

    The noise source can be viewed as a near-field source, its visibility
    can be expressed as

    .. math:: V_{ij}^{\\text{ns}} = C \\cdot e^{i k (r_{i} - r_{j})}

    where :math:`C` is a real constant.

    .. math::

        V_{ij}^{\\text{on}} &= G_{ij} (V_{ij}^{\\text{sky}} + V_{ij}^{\\text{ns}} + n_{ij}) \\\\
        V_{ij}^{\\text{off}} &= G_{ij} (V_{ij}^{\\text{sky}} + n_{ij})

    where :math:`G_{ij}` is the gain of baseline :math:`i,j`.

    .. math::

        V_{ij}^{\\text{on}} - V_{ij}^{\\text{off}} &= G_{ij} V_{ij}^{\\text{ns}} \\\\
                                       &=|G_{ij}| e^{i k \\Delta L} C \\cdot e^{i k (r_{i} - r_{j})} \\\\
                                       & = C |G_{ij}| e^{i k (\\Delta L + (r_{i} - r_{j}))}

    where :math:`\\Delta L` is the equivalent cable length.

    .. math:: \\text{Arg}(V_{ij}^{\\text{on}} - V_{ij}^{\\text{off}}) = k (\\Delta L + (r_{i} - r_{j})) = k \\Delta L + const.

    To compensate for the relative phase change (due to :math:`\\Delta L`) of the
    visibility, we can do

    .. math:: V_{ij}^{\\text{rel-cal}} = e^{-i \\; \\text{Arg}(V_{ij}^{\\text{on}} - V_{ij}^{\\text{off}})} \\, V_{ij}

    .. note::
        Note there is still an unknown (constant) phase factor to be determined in
        :math:`V_{ij}^{\\text{rel-cal}}`, which may be done by absolute calibration.


Generate beam transfer matrices.

    Beam transfer matrices can be pre-generated for accelerate map-making.


Mask the data involving the specified channels.


Accumulate data.

    This task accumulates data abserved in different (sidereal) days
    and records the weight (i.e., the number of valid or un-masked data)
    of each data point.

    .. note::
        This should be done after the data has been calibrated and re-ordered
        to a same LST (or RA).


Phase the source-phased visibility data to the zenith

    The phasing is done by multiply the visibility by the reference phase of
    the given *source*, as

    .. math:: V_{ij}^{\\text{phs}} = V_{ij} \\cdot e^{2 \\pi i \\, \\boldsymbol{s}_0 \\cdot \\boldsymbol{u}_{ij}}

    This is just the inverse operation of task
    :class:`~tlpipe.timestream.phs2src.Phs2src`.


Convert visibility from intensity unit to temperature unit in K.

    .. math:: T = \\frac{\\lambda^2}{2 k_b} I


Subtract simulated strong point sources signal from the visibilities.

    .. note::

        This must be done after the data has been calibrated.


Daytime data mask.


Task that provides raw timestream or timestream IO and data selection operations.

    Provides the methods `read_input`, `read_output` and `write_output` for
    raw timestream or timestream data.

    This is usually used as a direct base class as those tasks that operates on
    timestream data (can be data held in both
    :class:`~tlpipe.container.raw_timestream.RawTimestream` and
    :class:`~tlpipe.container.timestream.Timestream`), which can determine which
    data container the data is being held from the *input* or from data stored in
    the input data files.


Generate m-mode by DFT of the timestream data.

    The generated m-mode can be used for map-making.


Calibrate the visibility by divide the gain.

    .. math:: V_{ij}^{\\text{cal}} = V_{ij} / (g_i g_j^*).


Map-making.

    This task calls the submodule :mod:`~tlpipe.map.drift` which uses the m-mode
    formalism method to do the map-making.


Calibration using a strong point source.

    The observed visibility of a strong point source with flux :math:`S_c` is

    .. math:: V_{ij} &= g_i g_j^* A_i(\\hat{\\boldsymbol{n}}_0) A_j^*(\\hat{\\boldsymbol{n}}_0) S_c e^{2 \\pi i \\hat{\\boldsymbol{n}}_0 \\cdot (\\vec{\\boldsymbol{u}}_i - \\vec{\\boldsymbol{u}}_j)} \\\\
                     &= S_c \\cdot g_i A_i(\\hat{\\boldsymbol{n}}_0) e^{2 \\pi i \\hat{\\boldsymbol{n}}_0 \\cdot \\vec{\\boldsymbol{u}}_i} \\cdot (g_j A_j(\\hat{\\boldsymbol{n}}_0) e^{2 \\pi i \\hat{\\boldsymbol{n}}_0 \\cdot \\vec{\\boldsymbol{u}}_j})^* \\\\
                     &= S_c \\cdot G_i G_j^*,

    where :math:`G_i = g_i A_i(\\hat{\\boldsymbol{n}}_0) e^{2 \\pi i \\hat{\\boldsymbol{n}}_0 \\cdot \\vec{\\boldsymbol{u}}_i}`.

    In the presence of outliers and noise, we have

    .. math:: \\frac{V_{ij}}{S_c} = G_i G_j^* + S_{ij} + n_{ij}.

    Written in matrix form, it is

    .. math:: \\frac{\\boldsymbol{\\mathbf{V}}}{S_c} = \\boldsymbol{\\mathbf{V}}_0 + \\boldsymbol{\\mathbf{S}} + \\boldsymbol{\\mathbf{N}},

    where :math:`\\boldsymbol{\\mathbf{V}}_0 = \\boldsymbol{\\mathbf{G}} \\boldsymbol{\\mathbf{G}}^H`
    is a rank 1 matrix represents the visibilities of the strong point source,
    :math:`\\boldsymbol{\\mathbf{S}}` is a sparse matrix whose elements are outliers
    or misssing values, and :math:`\\boldsymbol{\\mathbf{N}}` is a matrix with dense
    small elements represents the noise.

    By solve the optimization problem

    .. math:: \\min_{V_0, S} \\frac{1}{2} \| V_0 + S - V \|_F^2 + \\lambda \| S \|_0

    we can get :math:`V_0`, :math:`S` and :math:`N` and solve the gain.


Mask the data when signal of the Sun is strong.


Detect noise source signal by using an appropriate threshold.

    This task automatically finds out the time points that the noise source
    is **on**, and creates a new bool dataset "ns_on" with elements *True*
    corresponding to time points when the noise source is **on**.


Line RFI flagging.

    This task flags the line RFI along time (then frequency) by first integrate
    data along frequency (and correspondingly time) axis, and mask values that
    exceeds the given threshold.


Dispatch data.

    This task will (maybe iteratively) load data from the input data files
    according to the required data selection (time, frequency, baseline
    selection). If work iteratively, data will be iteratively loaded according
    to the time unit set in the input pipe file, and the loaded data (contained
    in a data container which is a
    :class:`~tlpipe.container.raw_timestream.RawTimestream` object) will be
    dispatched to other tasks to be further processed.

    .. note::
        This usually should be the first task in the input pipe file to select
        and load the data from input data files for other tasks.

    .. note::
        Current this task only works for a continuously observed data sets.
        Works need to do to make it work also for data observed in dis-continuous
        time periods.


Mask the data involving the specified feeds.


Barrier the iterative pipeline flow before executing its following tasks.

    This inherits from :class:`~tlpipe.pipeline.pipeline.DoNothing` just for
    convenient use.


Rebin the frequency channels.

    This task rebins the data along the frequency by merging (and average)
    the adjacent frequency channels.


Convert RawTimestream to Timestream.

    This converts the current data which is held in a
    :class:`~tlpipe.container.raw_timestream.RawTimestream` container
    to data held in a
    :class:`~tlpipe.container.timestream.Timestream` container.

    By doing so, the original mixed *polarization* and *baseline* will be
    separated, which will be more convenient for the following processing.


Bad/Exceptional visibility values detect.

    This task does a simple bad/exceptional values detection by mask those
    values that are not finite, and those have non-zero imaginary part of an
    auto-correlation.


RFI flagging by using Local Outlier Probabilities (LoOP).

    LoOP is a local density based outlier detection method which provides
    outlier scores in the range of [0, 1] that are directly interpretable
    as the probability of a sample being an outlier.


RFI flagging by applying the SIR (Scale-Invariant Rank) operator.

    The scale-invariant rank (SIR) operator is a one-dimensional mathematical
    morphology technique that can be used to find adjacent intervals in the
    time or frequency domain that are likely to be affected by RFI.


Check the phase closure relation.

    The closure phase of the visibility for feeds :math:`i,j,k` is
    :math:`\\text{Arg}(V_{ij} V_{jk} V_{ki})`. We see for a strong point source,
    the closure phase should be nearly *zero*.


Detect noise source signal.

    This task automatically finds out the time points that the noise source
    is **on**, and creates a new bool dataset "ns_on" with elements *True*
    corresponding to time points when the noise source is **on**.


Noise source calibration by using eigen-decomposition method.

    The observed visibility of a strong point source with flux :math:`S_c` is

    .. math:: V_{ij} &= g_i g_j^* A_i(\\hat{\\boldsymbol{n}}_0) A_j^*(\\hat{\\boldsymbol{n}}_0) S_c e^{2 \\pi i \\hat{\\boldsymbol{n}}_0 \\cdot (\\vec{\\boldsymbol{u}}_i - \\vec{\\boldsymbol{u}}_j)} \\\\
                     &= S_c \\cdot g_i A_i(\\hat{\\boldsymbol{n}}_0) e^{2 \\pi i \\hat{\\boldsymbol{n}}_0 \\cdot \\vec{\\boldsymbol{u}}_i} \\cdot (g_j A_j(\\hat{\\boldsymbol{n}}_0) e^{2 \\pi i \\hat{\\boldsymbol{n}}_0 \\cdot \\vec{\\boldsymbol{u}}_j})^* \\\\
                     &= S_c \\cdot G_i G_j^*,

    where :math:`G_i = g_i A_i(\\hat{\\boldsymbol{n}}_0) e^{2 \\pi i \\hat{\\boldsymbol{n}}_0 \\cdot \\vec{\\boldsymbol{u}}_i}`.

    In the presence of outliers and noise, we have

    .. math:: \\frac{V_{ij}}{S_c} = G_i G_j^* + S_{ij} + n_{ij}.

    Written in matrix form, it is

    .. math:: \\frac{\\boldsymbol{\\mathbf{V}}}{S_c} = \\boldsymbol{\\mathbf{V}}_0 + \\boldsymbol{\\mathbf{S}} + \\boldsymbol{\\mathbf{N}},

    where :math:`\\boldsymbol{\\mathbf{V}}_0 = \\boldsymbol{\\mathbf{G}} \\boldsymbol{\\mathbf{G}}^H`
    is a rank 1 matrix represents the visibilities of the strong point source,
    :math:`\\boldsymbol{\\mathbf{S}}` is a sparse matrix whose elements are outliers
    or misssing values, and :math:`\\boldsymbol{\\mathbf{N}}` is a matrix with dense
    small elements represents the noise.

    By solve the optimization problem

    .. math:: \\min_{V_0, S} \\frac{1}{2} \| V_0 + S - V \|_F^2 + \\lambda \| S \|_0

    we can get :math:`V_0`, :math:`S` and :math:`N` and solve the gain.


Unit tests for mkdir_p.


Container class for the timestream data.

    This timestream data container is to hold time stream data that has polarization
    and baseline separated from the channel pairs in the raw timestream.

    Parameters
    ----------
    Same as :class:`container.BasicTod`.


Container class for the raw timestream data.

    The raw timestream data are raw visibilities (the main data) and other data
    and meta data saved in HDF5 files which are recorded from the correlator.

    Parameters
    ----------
    Same as :class:`container.BasicTod`.


Basic time ordered data container.

    Inherits from :class:`caput.memh5.MemDiskGroup`.

    Basic one-level time ordered data container that allows any number of
    datasets in the root group but no nesting.

    This container is intended to be an base class for other concrete data
    classes, so only basic input/output and a limited operations are provided.
    Usually you should not use this class directly, use a concrete sub-class
    instead.

    Parameters
    ----------
    files : None, string or list of strings
        File name or a list of file names that data will be loaded from. No files
        if None. Default None.
    mode : string, optional
        In which mode to open the input files. Default 'r' to open files read only.
    start : integer, optional
        Starting time point to load. Non-negative integer is relative to the first
        time point of the first file, negative integer is relative to the last time
        point of the last file. Default 0 is from the start of the first file.
    stop : None or integer, optional
        Stopping time point to load. Non-negative integer is relative to the first
        time point of the first file, negative integer is relative to the last time
        point of the last file. Default None is to the end of the last file.
    dist_axis : string or integer, optional
        Axis along which the main data is distributed.
    use_hints : bool, optional
        If True, will try to use the hints in the first file of `files` to
        construct this class. Default True.
    comm : None or MPI.Comm, optional
        MPI Communicator to distributed over. Default None to use mpiutil._comm.


Common things for the raw timestream data and timestream data.

    This class hold the common data an operations for :class:`RawTimestream` and
    :class:`Timestream`. Usally you should not directly use this class, use
    :class:`RawTimestream` or :class:`Timestream` instead.

    Parameters
    ----------
    Same as :class:`container.BasicTod`.


This will be a subclass of ether :class:`caput.memh5.MemDatasetCommon`
            or :class:`caput.memh5.MemDatasetDistributed` depending on the type
            of `outer_self.vis.__class__`.


Exception class for failure on scraping repository link


Exception class for failure on scraping download links of bands


Exception class for the failure of downloading bz2 arhive


Exception class for the failure of extraction of bz2 archive


    Contains FITS image data of an SDSS galaxy
    and associated data extracted out of this image
    to detect whether it is a double nuclei galaxy or not


    Class that loads the FITS data corresponding to a .csv file of SDSS objIDs
    and performs DAGN classification on them


    Enum for the final verdict of a galaxy
        INVALID_OBJID       - Self explanatory
        DOWN_FAIL           - Failed to download
        FILTERED            - Rejected by filtration condition
        NO_PEAK             - shc did not return any peaks
        SINGLE              - Single nuclei galaxy
        DOUBLE              - Double nuclei galaxy


    Stores data and methods to compute the intensity optima in a region of
    an image along with procedures to filter them to infer the true peaks


    Stores a grayscale pixel distribution and contains methods to infer
    the noise/signal level from it depending on a particular fitting curve
        1. Parameters of the fit
        2. Noise level
        3. Signal level


    Parameters and method to infer noise/signal
    for a Gaussian intensity profile


    Parameters and method to infer noise/signal for a Sersic intensity profile.
    Galaxy light curves are usually fit with a Sersic profile with an index ranging
    between 0.5 and 10. For this Class, the limits are present in the Class values
    llim = 0.25, and rlim = 15. If the fit sersic index does not fall within this
    range, it is recommended to use a Gaussian profile


Support setup.py upload.


Provides easy read/write of structured data to/from a dictionary.


Base class for snapshot formats.


Unformatted f77 binary snapshot class.


Gadget2 Type 1 Snapshot


Gadget2 header structure.


Buildgal TREEBI snapshot.


BGC2 Halo Catalogue


BGC2 header structure


BGC2 group structure


BGC2 particle structure


Tipsy header structure


Tipsy gas particle structure


Tipsy dark matter particle structure


Tipsy star particle structure


A class used for enabling importance sampling of an MCMC chain.

    Note: the 'scale' parameter is not used if you use the `lnlikes_binning`
    method of choosing training points.

    Args:
        chain: an MCMC chain that we want to draw samples from
        lnlikes: the log-likelihoods of the samples in the MCMC chain
        scale: 'spread' of the training points. Default is 6.


This aspect finds all aws_iam.Role objects in a node (ie. CDK stack) and sets permission boundary to the given ARN.


    Provides transiting candidate vetting information like centroids and spaceship motion, momentum dumps, neighbours
    curves inspection and more to give a deeper insight on the quality of the candidate signal.


Used to run a single scenario validation with TRICERATOPS


Wrapper class for input arguments of TriceratopsThreadValidator.


Base class to prepare the DVR url for a given mission id


Prepares the DVR url for a given Kepler mission id


Prepares the DVR urls for a given Kepler mission id


Class offering official data validation report download


Compute a fake CE event.
    Requires the input star to be an H-rich and evolved star.
    Otherwise, it will fail.


Class describing a single star.


Class describing the properties of a population synthesis simulation.


Base class for hooking into binary evolution.


Add history column 'step_times' (time taken by step) to each binary.

    Example
    -------
    >>> pop.to_df(extra_columns={'step_times': float})


Add history column 'step_name' to each binary.

    Name of evolutionary step as defined in SimulationProperties.

    >>> pop.to_df(extra_columns={'step_names': str})


Simple example for adding extra print info.


Default end step.


A class containing the state and history of a stellar binary.


Evolve an isolated star (a single star, a merger product, a runaway star, etc.)

    The star will be matched in the beginning of the step and will be evolved
    until core-collapse or maximum simulation time,
    based on a grid of single star HDF5 grid.


Prepare a runaway star to do an an isolated_step)


Evolve a detached binary.

    The binary will be evolved until Roche-lobe overflow, core-collapse or
    maximum simulation time, using the standard equations that govern the
    orbital evolution.

    Parameters
    ----------
    path : str
        Path to the directory that contains a HDF5 grid.
    dt : float
        The timestep size, in years, to be appended to the history of the
        binary. None means only the final step.
        Note: do not select very small timesteps cause it may mess with the
        solving of the ODE.
    n_o_steps_history: int
        Alternatively, we can define the number of timesteps to be appended to
        the history of the binary. None means only the final step. If both `dt`
        and `n_o_steps_history` are different than None, `dt` has priority.
    matching_method: str
        Method to find the best match between a star from a previous step and a
        point in a single MIST-like stellar track. Options "root" (which tries
        to find a root of two matching quantities, and it is possible to not
        achieve it) or "minimize" (minimizes the sum of squares of differences
        of various quantities between the previous step and the track).
    verbose : Boolean
        True if we want to print stuff.
    do_wind_loss: Boolean
        If True, take into account change of separation due to mass loss from
        the star.
    do_tides: Booleans
        If True, take into account change of separation, eccentricity and star
        spin due to tidal forces.
    do_gravitational_radiation: Boolean
        If True, take into account change of separation and eccentricity due to
        gravitational wave radiation.
    do_magnetic_braking: Boolean
        If True, take into account change of star spin due to magnetic braking.
    magnetic_braking_mode: String
        A string corresponding to the desired magnetic braking prescription.
            -- RVJ83: Rappaport, Verbunt, & Joss 1983
            -- M15: Matt et al. 2015
            -- G18: Garraffo et al. 2018
            -- CARB: Van & Ivanova 2019
    do_stellar_evolution_and_spin_from_winds: Boolean
        If True, take into account change of star spin due to change of its
        moment of inertia during its evolution and due to spin angular momentum
        loss due to winds.

    Attributes
    ----------
    KEYS : list of str
           Contains valid keywords which is used
           to extract quantities from the grid.
    grid : GRIDInterpolator
           Object to interpolate between the time-series in
           the h5 grid.
    initial_mass : list of float
            Contains the initial masses of the stars in the grid.

    Note
    ----
    A matching between the properties of the star, and the h5 tracks are
    required. In the "root" solver matching_method, if the root solver fails
    then the evolution will immediately end, and the binary state will be
    tagged with "Root solver failed". In the "minimize" matching_method, we
    minimize the sum of squares of differences of various quantities between
    the previous step and the h5 track.

    Warns
    -----
    UserWarning
        If the call cannot determine the primary or secondary in the binary.

    Raises
    ------
    Exception
        If the ode-solver fails to solve the differential equation
        that governs the orbital evolution.


The double compact-object step class.


Prepare a merging star to do an an IsolatedStep


Compute supernova final remnant mass, fallback fraction and CO type.

    This considers the He core mass of the nearest neighbor of the star
    prior to the collapse. Using a set of data for the He core
    mass of the compact object progenitors prior the collapse, the final
    remnant mass and stellar state of the compact object are known.

    Parameters
    ----------
    engine : string
        Engine for the supernova explosion, from the one where used in [1]_.

    path_engine_dataset : string
        Path to the location of the data on initial and final states
        for each engine described in [1]_

    Returns
    -------
    m_rem : double
        Remnant mass of the compact object in M_sun.
    f_fb : double
        Fallback mass of the compact object in M_sun.
    state : string
        Finall state of the stellar remnant after the supernova.

    References
    ----------
    .. [1] Sukhbold, T., Ertl, T., Woosley, S. E., Brown, J. M., & Janka, H. T.
        (2016). Core-collapse supernovae from 9 to 120 solar masses based on
        neutrino-powered explosions. The Astrophysical Journal, 821(1), 38.


Superclass for steps using the POSYDON grids.


Class for performing the MESA step for a MS-MS binary.


Class for performing the MESA step for a CO-HMS_RLO binary.


Class for performing the MESA step for a CO-HeMS_RLO binary.


Class for performing the MESA step for a CO-HeMS binary.


Class for performing the MESA step for a HMS-HMS RLO binary.
    For binaries with an initial eccentricity at ZAMS,
    we evolve them first with step detached and map to the HMS-HMS RLO grid
    using `initial_eccentricity_flow_chart`.


Compute supernova final remnant mass, fallback fraction & stellar state.

    This consider the nearest neighboor of the He core mass of the star,
    previous to the collapse. Considering a set of data for which the He core
    mass of the compact object projenitos previous the collapse, the final
    remnant mass and final stellar state of the compact object is known.

    Parameters
    ----------
    verbose : bool
        If True, the messages will be prited in the console.

    Keyword Arguments
    -----------------
    prescription : str
        Prescription to use for computing the prediction of common enevelope
        evolution. Available options are:

        * 'alpha-lambda' : Considers the the alpha-lambda prescription
          described in [1]_ and [2]_ to predict the outcome of the common
          envelope evolution. If the profile of the donor star is available
          then it is used to compute the value of lambda.

    References
    ----------
    .. [1] Webbink, R. F. (1984). Double white dwarfs as progenitors of R
        Coronae Borealis stars and Type I supernovae. The Astrophysical
        Journal, 277, 355-360.

    .. [2] De Kool, M. (1990). Common envelope evolution and double cores of
        planetary nebulae. The Astrophysical Journal, 358, 189-195.


Test Regressor class on the 3d synthetic data set.


Test Classifier class on the 3d synthetic data set.


Test TableData class on the 3d synthetic data set.


Test Sampler class on the 3d synthetic data set.


Test methods in utils.


    def test_matching2_root(self):
        method = "root"
        matching = HMS_detached_step(PATH_TO_EEPS, matching_method=method, verbose=True)
        get_mist0 = HMS_detached_step.get_mist0
        get_track_val = HMS_detached_step.get_track_val
        PROPERTIES_STAR = {
            "mass": 20.0,
            "log_R": 2.5,
            "mdot": -(10.0 ** (-5)),
            "state": "PostMS",
            "center_he4": 0.8,
            "center_h1": 0.0,
            "total_moment_of_inertia": 10.0 ** 57,
            "log_total_angular_momentum": 52,
            "he_core_mass": 7.0,
            "surface_he4": 0.2,
            "surface_h1": 0.7,
        }
        m0, t = get_mist0(matching, SingleStar(**PROPERTIES_STAR))

        self.assertAlmostEqual(
            m0,
            23.092430444226363,
            places=5,
            msg="Initial mass in MIST matching not exactly what expected. Should be 23.092430444226363",
        )
        self.assertAlmostEqual(
            get_track_val(matching, "mass", m0, t),
            20.000000000003112,
            places=5,
            msg="Current mass in matching not exactly what expected. Should be 20.000000000003112",
        )
        self.assertAlmostEqual(
            get_track_val(matching, "log_R", m0, t),
            3.006026700371161,
            places=5,
            msg="Current log_R in matching not exactly what expected. Should be 3.006026700371161",
        )
        self.assertAlmostEqual(
            get_track_val(matching, "center_he4", m0, t),
            0.6426242107646186,
            places=5,
            msg="Current center_he4 in matching not exactly what expected. Should be 0.6426242107646186",
        )
        self.assertAlmostEqual(
            get_track_val(matching, "he_core_mass", m0, t),
            6.99999999999913,
            places=5,
            msg="Current mass he_core_mass matching not exactly what expected. Should be 6.99999999999913",
        )

    def test_matching2_minimize(self):
        method = "minimize"
        matching = HMS_detached_step(PATH_TO_EEPS, matching_method=method, verbose=True)
        get_mist0 = HMS_detached_step.get_mist0
        get_track_val = HMS_detached_step.get_track_val
        PROPERTIES_STAR = {
            "mass": 20.0,
            "log_R": 2.5,
            "mdot": -(10.0 ** (-5)),
            "state": "PostMS",
            "center_he4": 0.8,
            "center_h1": 0.0,
            "total_moment_of_inertia": 10.0 ** 57,
            "log_total_angular_momentum": 52,
            "he_core_mass": 7.0,
            "surface_he4": 0.2,
            "surface_h1": 0.7,
        }
        m0, t = get_mist0(matching, SingleStar(**PROPERTIES_STAR))

        self.assertAlmostEqual(
            m0,
            23.441360274390483,
            places=5,
            msg="Initial mass in MIST matching not exactly what expected. Should be 23.441360274390483",
        )
        self.assertAlmostEqual(
            get_track_val(matching, "mass", m0, t),
            21.931950016322705,
            places=5,
            msg="Current mass in matching not exactly what expected. Should be 21.931950016322705",
        )
        self.assertAlmostEqual(
            get_track_val(matching, "log_R", m0, t),
            2.5019520817980974,
            places=5,
            msg="Current log_R in matching not exactly what expected. Should be 2.5019520817980974",
        )
        self.assertAlmostEqual(
            get_track_val(matching, "center_he4", m0, t),
            0.9095107795447867,
            places=5,
            msg="Current center_he4 in matching not exactly what expected. Should be 0.9095107795447867",
        )
        self.assertAlmostEqual(
            get_track_val(matching, "he_core_mass", m0, t),
            6.86182071726521,
            places=5,
            msg="Current mass he_core_mass matching not exactly what expected. Should be 6.86182071726521",
        )


Perform regression/interpolation with different regression algorithms.

    Regression algorithms are trained by class and by output column in the data
    set and stored as instance variables in nested dictionaries.

    This class inlcudes a 'cross validation' method that trains with the
    holdout method but calculates differences instead of a single accuracy.


Classifier class.

    Perform one against all classification with a variety of different
    classification algorithms (interpolators). Different classifcation
    algorithms are trainined and stored for recall as instance variables
    inside nested dictionaries.
    This class also supports model validation through cross validation
    using the holdout method.


Class implementing PTMCMC and MCMC for PSY-CRIS algorith.

    Modular implementation of PTMCMC and MCMC designed to
    implement the PSY-CRIS algorithm of sampling points
    in a target distribution constructed with a Classifier
    and Regressor. After a posterior is generated, methods
    in this class are also used to downsample.


    For managing data sets used for classification and regression.

        Reads tables of simulation data where a single row represents one
        simulation. Each column in a row represents different inputs
        (initial conditions) and outputs (result, continuous variables).
        If using multiple files, each file is assumed to have the same columns.
        You may also directly load a pandas DataFrame instead of reading in
        files.

        Example data structure expected in files or pandas DataFrame:

        0  input_1  input_2  outcome  output_1   output_2  output_3 ...
        1    1.5      2.6      "A"       100       0.19       -     ...
        2    1.5      3.0      "B"        -          -        -     ...
        3    2.0      2.6      "C"        -          -        6     ...
        ...

        The above table has dashes '-' in output columns to indicate NaN
        values. You may have a similar structure if different classes have
        fundamentally different outputs.


General POSYDON warning class.


Warning that something unexpeted occurred during the binary evolution, but
    the evolution is able to continue (binary did not fail).


Class which stores caught warnings.


Context manager class to catch POSYDON warnings.


General POSYDON exception class.


Class for handling ignore reasons when creating new grids.


Interpolation class for one dimensional interpolation.


Class handling input, process and output of configurations.


A dictionary key which is a variable.

    @ivar item: The variable AST object.


A class to handle the evolution of binary populations.

    Attributes
    ----------
    pop_params : dict
        The parameters of the population population.
    solar_metallicities : list of float
        The metallicities of the populations in solar units.
    binary_populations : list of BinaryPopulation
        The binary populations.
    verbose : bool
        If `True`, print additional information.


A class to handle the interface between the population file and the History and Oneline classes.


A class to handle the history dataframe of a population file.

    This class provides methods to handle the history dataframe of a population file.
    It allows accessing and manipulating the history table based on various keys and conditions.

    Attributes
    ----------
    filename : str
        The path to the population file.
    verbose : bool
        If `True`, print additional information.
    chunksize : int
        The chunksize to use when reading the history file.
    lengths : pd.DataFrame
        The number of rows of each binary in the history dataframe.
    number_of_systems : int
        The number of systems in the history dataframe.
    columns : list of str
        The columns of the history dataframe.
    indices : np.ndarray
        The binary indices of the history dataframe.


A class to handle the oneline dataframe of a population file.

    The `Oneline` class provides methods to manipulate and retrieve data from the oneline dataframe of a population file.

    Attributes
    ----------
    filename : str
        The path to the population file.
    verbose : bool
        If `True`, print additional information.
    chunksize : int
        The chunksize to use when reading the oneline file.
    number_of_systems : int
        The number of systems in the oneline dataframe.
    indices : np.ndarray
        The binary indices of the oneline dataframe.
    columns : list of str


A class to handle the input/output of population files.

    This class provides methods to load and save population files in HDF5 format.
    It also includes methods to load and save metadata and ini parameters.

    Attributes
    ----------
    mass_per_metallicity : pandas.DataFrame
        A DataFrame containing mass per metallicity data.
    ini_params : dict
        A dictionary containing some ini parameters, described in parameter_array.


A class to handle population files.

    This class provides methods to handle population files. It includes methods to read and write population files,
    as well as methods to access and manipulate the history and oneline dataframes.

    Attributes
    ----------
    history : History
        The history dataframe of the population.
    oneline : Oneline
        The oneline dataframe of the population.
    formation_channels : pd.DataFrame
        The formation channels dataframe of the population.
    ini_params : dict
        The parameters from the ini file used to create the population.
    mass_per_metallicity : pd.DataFrame
        The mass per metallicity dataframe of the population.
    solar_metallicities : np.ndarray
        The solar metallicities of the population.
    metallicities : np.ndarray
        The metallicities of the population.
    indices : np.ndarray
        The indices of the binaries in the population.
    verbose : bool
        If `True`, print additional information.
    chunksize : int
        The chunksize to use when reading the population file.
    filename : str
        The path to the population file.
    number_of_systems : int
        The number of systems in the population.
    history_lengths : pd.DataFrame
        The number of rows of each binary in the history dataframe. The index is the binary index.


A class representing a population of transient events.

    This class allows you to calculate additional properties of the population,
    such as the efficiency of events per Msun for each solar metallicity, and to
    calculate the cosmic weights of the transient population.

    Attributes
    ----------
    population : pandas.DataFrame
        DataFrame containing the whole transient population.
    transient_name : str
        Name of the transient population.
    efficiency : pandas.DataFrame
        DataFrame containing the efficiency of events per Msun for each solar metallicity.
    columns : list
        List of columns in the transient population.


Class representing rates of a transient population.

    Attributes
    ----------
    SFH_identifier : str
        The identifier for the star formation history.
    base_path : str
        The base path for accessing the rates data.
    MODEL : dict
        The model data for the star formation history.
    weights : pandas.DataFrame
        The weights of the transient population.
    z_birth : pandas.DataFrame
        The redshift of the birth bins.
    z_events : pandas.DataFrame
        The redshift of the events.
    intrinsic_rate_density : pandas.DataFrame
        The intrinsic rate density of the transient population.
    observable_population_names : list
        The names of the observable populations.
    edges_metallicity_bins : np.ndarray
        The edges of the metallicity bins of the star formation history.
    centers_metallicity_bins : np.ndarray
        The centers of the metallicity bins of the star formation history.
    edges_redshift_bins : np.ndarray
        The edges of the redshift bins of the star formation history.
    centers_redshift_bins : np.ndarray
        The centers of the redshift bins of the star formation history.


Abstract class for star formation history models


    Base class for Madau-style star-formation history implementations.
    This class implements common methods for CSFRD, mean metallicity,
    and fractional SFR based on the chosen Madau parameterisation.
    The specific parameters for CSFRD must be provided by subclasses.


Madau & Dickinson (2014) [1]_ star formation history model using the
    mean metallicity evolution of Madau & Fragos (2017) [2]_.

    References
    ----------
    .. [1] Madau, P., & Dickinson, M. (2014). ARA&A, 52, 415-486.
        https://ui.adsabs.harvard.edu/abs/2014ARA%26A..52..415M
    .. [2] Madau, P., & Fragos, T. (2017). ApJ, 840(1), 39.
        https://ui.adsabs.harvard.edu/abs/2017ApJ...840...39M


The Madau & Fragos (2017) star formation history model with the
    metallicity evolution of Madau & Fragos (2017) [1]_.

    References
    ----------
    .. [1] Madau, P., & Fragos, T. (2017). ApJ, 840(1), 39.
        https://ui.adsabs.harvard.edu/abs/2017ApJ...840...39M/abstract


The Neijssel et al. (2019) [1]_ star formation history model, which fits
    the Madau & Dickinson (2014) [2]_ cosmic star formation rate density formula
    with the BBH merger rate and uses a truncated log-normal distribution for
    the mean metallicity distribution.
    The mean metallicity evolution follows the Langer and Normal parameterisation
    also fitted to the BBH merger rate.

    References
    ----------
    .. [1] Neijssel, C. J., et al. (2019). MNRAS, 490, 3740.
        https://ui.adsabs.harvard.edu/abs/2019MNRAS.490.3740N
    .. [2] Madau, P., & Fragos, T. (2017). ApJ, 840(1), 39.
        https://ui.adsabs.harvard.edu/abs/2017ApJ...840...39M/


The IllustrisTNG star formation history model.

    Uses the TNG100-1 model from the IllustrisTNG simulation.

    https://www.tng-project.org/


The Fujimoto et al. (2024) star formation history model.
    mean metallicity evolution of Madau & Fragos (2017).

    Fujimoto et al. (2024), ApJ SS, 275, 2, 36, 59
    https://ui.adsabs.harvard.edu/abs/2024ApJS..275...36F/abstract


The Zavala et al. (2021) star formation history model [1]_.

    The "min" and "max" models are based on the obscured and unobscured
    star formation rate density models, respectively.

    References
    ----------
    .. [1] Zavala, J., et al. (2021). ApJ, 909(2), 165.
        https://ui.adsabs.harvard.edu/abs/2021ApJ...909..165Z/


Handle a binary star population.


Manage a population of binaries.


Generate binaries to be included in a BinaryPopulation.


    K-nearest neighbor model that instantiates based on detection probability grid

    When instantiating, must supply path to the grid, and key that represents
    GW network and sensitivity.


Test class for MadauBase


Concrete subclass of MadauBase for testing


Tests for the IllustrisTNG SFH model with mocked data loading.


Tests for the MadauDickinson14 SFH model


Tests for the MadauFragos17 SFH model


Tests for the Neijssel19 SFH model


Tests for the Fujimoto24 SFH model


Tests for the Chruslinska21 SFH model with mocked data loading.


Tests for the Zavala21 SFH model with mocked data loading.


Tests for the get_SFH_model function.


Tests for SFR_per_met_at_z function.


Class for reading MESA output files of an individual run.


Class for quick reading of MESA grid files.


Class handling a grid of MESA runs encoded in HDF5 format.


Class for iterating runs (i.e., PSyRunView instances) in a PSyGrid.


Access runs in HDF5 grid without opening all data.

    Example
    -------
    mygrid = PSyGrid("thegrid.h5")  # opens a stored grid
    myrun = mygrid[0]               # get a "view" of the first run in the grid
    print(mygrid[1].history1.star_age)

    t1 = myrun["binary_history"]["age"]
    t2 = myrun["binary_history"].age
    t3 = myrun.binary_history["age"]
    t4 = myrun.binary_history.age

    print(mygrid[1].history1.star_age)


Class performing downsampling of multi-dimensional paths.


Plotting class for 2D (MESA) grids.


The different view for the Presenter.


Handle a VH diagram.


Plotting class for 1D (MESA) grids.


Class that is helpful for evaluating interpolation performance


Simple class to store an before/after info and simplfy dataframe.

    Parameters
    ----------
    state_before : any value
        Value for the older state.
    state_after : any value
        Value for the younger state.

    Attributes
    ----------
    state_before
    state_after


Charged to setup window and format data before calling display funcs.


Window to display available options, emit signal for selected option.


Enumeration of different type of infos.


Mother-class with common informations uselful for all widget.


Informations to create a case widget.


Informations to create a widget with a point drew.


Define the mother-class for widget in GraphVisualizer.

    Attributes
    ----------
    connected : bool
        Indicate if this widget need to be connected with the previous one in
        the same column.


Case widget in GraphVisualizer.

    Provides the ability to display 5 texts: 2 on the top 2 on the bottom,
    and 1 in center. Can have a border.


Define an empty widget with a point drew.


Widget containing GraphVisualizerPointDraw.

    Provides the ability to display 2 texts, one at each side.


Information to create a widget with a line of diagram inside.


Widget containing drawings.

    Provides the ability to display 4 texts on top & bottom.


Enumeration of different column type.


Represent a visual link between 2 widgets.


Mother-class of visual column in GraphVisualizer.

    Manage one visual column in the QGridLayout
    (can take several logical columns).


Simple visual column with arrow between connected widget.


Draw a visual column, compressed by another other column.


Widget used to display the different columns and add widget in them.


Model containing the dataset of simulations.


Custom label to display LaTeX formula.


Handle a multiple or hierarchical VH diagram plot.


Handle multiple Diagram view


Handles drawing binaries as hierarchical trees


Handle for all callback triggered by user.


Custom window to display the application.


Handle the binary parsing


Convert a MESA history file to Equivalent Evolutionary Phase track.


Data Normalization class.

    This class provides normalizing tools for float 1D arrays. Features can be
    standarized or scaled to a range depending on the method chosen when
    calling the fit ot fit_and_transform functions.


Perform track interpolation for POSYDON.


Class to interpolate between single star MESA tracks.

    Attributes
    ----------
    path : str
        The path to the directory that contains the h5 grid.

    keys : tuple of str
        Contains valid keys for accessing the data.


Class handling initial-final interpolation.

    Class handling initial-final interpolation with support to interpolate
    certain keys by differing classes.


Class handling the initial-final interpolation for POSYDON.


Class used as a shell parent class for all Interpolators.


Class implementing Nearest Neighbor interpolation.


Class implementing Linear Interpolation.


Class implementing class-wise interpolation.


Class used as a shell parent class for all classifiers.


Class implementing K - Nearest Neighbors classifier.


Class used to scale input and output space.


Convenient tool for constructing linear chains of blocks and views

    Examples::

        bc = bf.BlockChainer()
        bc.blocks.read_sigproc("foo.fil", gulp_nframe=1)
        bc.blocks.copy('cuda')
        bc.views.split_axis('freq', 2, 'fine_freq')
        bc.views.merge_axes('freq', 'fine_freq')
        bc.blocks.copy('cuda_host')
        bc.custom(my_block)(arg1, arg2, ...)
        bc.blocks.write_sigproc()
        print(bc.last_block) # The last added block (this can also be set)


Context manager to use a stream created outside Bifrost


Class which connects blocks linearly, with
        one ring between each block. Does this by creating
        one ring for each input/output 'port' of each block,
        and running data through the rings.


Defines the structure for a transform block


Defines the structure for a source block


Defines the structure for a sink block


Defines functions and attributes for a block with multi input/output


Block which splits up a ring into two


Block which adds two input rings


Block for debugging purposes.
    Allows you to pass arbitrary N-dimensional arrays in initialization,
    which will be outputted into a ring buffer


Prints the header of a ring to a file


Performs complex to complex 1D FFT on input ring data


Performs complex to complex 1D IFFT on input ring data


Copies input ring's data into ascii format
        in a text file.


Copies input ring's data to the output ring


This block reads in a sigproc filterbank
    (.fil) file into a ring buffer


This block performs spectral kurtosis and cleaning
        on sigproc-formatted data in rings


This block calculates the dedispersion of
        sigproc-formatted data in a ring, and tags
        it in the headers


This block folds a signal into a histogram


This block creates a waterfall block
        based on the data in a ring, and stores it
        in the headers


Perform an arbitrary N ndarray -> M ndarray numpy function
        Inside of a pipeline. This block will calculate all of the
        necessary information for Bifrost based on the passed function.


Simulate an incoming stream of data on a ring using an arbitrary generator.
        This block will calculate all of the
        necessary information for Bifrost based on the passed function.


Python object for a ring's sequence (data unit)


defines, reads, writes sigproc settings


Reads from or writes to a sigproc filterbank file


This class is used as a Py3 StopIterator

    In Python >3.7, reaching a StopIterator in a generator will
    raise a RuntimeError  (so you can't do 'except StopIteration' to catch it!)
    See PEP479 https://www.python.org/dev/peps/pep-0479/


Base class for simple objects with create/destroy functions


Bifrost telemetry client to help understand usage of the Bifrost Python interface.


    Dada file reader for raw LEDA correlator data.

    Reads the header of a dada file

    Parameters
    ----------
    filename: str
        name of dada file to open
    n_int: int
        number of integrations to read. If None, will only read header
    inspectOnly: bool
        If inspectOnly, will only read header and will not unpack data.


    Handle the generation of true times and RA/DEC for the observation in the DADA file.
    Use pyephem for the tricky stuff. Includes the new calculation of RA/DEC in terms
    of long/lat rather than just using long/lat.


Test the ability of the Dada block to read
        in data that is compatible with other blocks.


 Simple file-like reading object for pipeline testing

    Args:
        filename (str): Name of file to open
        dtype (np.dtype or str): datatype of data, e.g. float32. This should be a *numpy* dtype,
                                 not a bifrost.ndarray dtype (eg. float32, not f32)
        gulp_size (int): How much data to read per gulp, (i.e. sub-array size)


Copies input ring's data into ascii format in a text file,
        after resizing late (after opening sequence).


Test late resizing of a ring in a pipeline


Create a gulp size larger than ring size


Testing-only block which calls user-defined
        functions on sequence and on data


Test all aspects of the print header block


Test the iterate_ring_write function of SourceBlocks/TransformBlocks


Test the TestingBlock for basic functionality


Performs tests of the Copy Block.


This tests functionality of the FoldBlock.


This tests functionality of the KurtosisBlock.


This test assures basic functionality of fft block


This test assures basic functionality of the ifft block.
    Requires the FFT block for testing.


Test rigidity and features of the pipeline


Test call syntax and function of a multi transform block


Test a block which splits up incoming data into two rings


Tests for a block which can call arbitrary functions that work on numpy arrays.
        This should include the many numpy, scipy and astropy functions.
        Furthermore, this block should automatically move GPU data to CPU,
        call the numpy function, and then put out data on a CPU ring.
        The purpose of this ring is mainly for tests or filling in missing
        functionality.


Test simple IO for the UDP-based TBN packet reader and writing


Test simple IO for the UDP-based DRX packet reader and writing


Test simple IO for the UDP-based PBeam packet reader and writing


Test simple IO for the UDP-based Simple packet reader and writing


Test simple IO for the disk-based TBN packet reader and writing


Test simple IO for the disk-based DRX packet reader and writing


Test simple IO for the disk-based PBeam packet reader and writing


Test simple IO for the disk-based Simple packet reader and writing


Create a bunch of headers which should pass the test,
        and check that they do in fact pass


Create a bunch of headers which should not pass the
        test, and check that they do not.


Test simple IO for the binary read/write blocks


Test-only block which converts the input data to cf32 data.


Test the sigproc read function


Time total clock and individual parts of blocks in a pipeline


 This class is used to shared all the vbles across the application.
        This are visible on the python classes of the folders.
            * bokeh_models through the class Environment
            * data_models through the class SharedCruiseData

        This class is created to avoid sending shared variables to
        the other classes constructors. Like this the variables are
        always updated. This should be done in the rest of classes:

            from ocean_data_qc.env import Environment

            [...]

                self.env = Environment

        NOTE: Here I cannot instantiate the other objects as children >> recursive inheritance


 This class is gathering all the common methods needed to manage
        the aqc, csv and whp files (instantiated with the children classes)


This class is used to exchange messages from bokeh server and Electron


 Mainly this manages all the JSON files.
        TODO: Move all the asyncronous tasks on Electron with files to this file if possible
        TODO: the config file could be here as well


 This class is gathering all the common methods needed to export and save
        the aqc, csv and whp files


 This class use to manage the plain AQC files. This file can be come from
        csv file or whp csv file.


This class is used to manage the plain CSV files (non-WHP format)


 This class is used for:
            * check octave path
            * set octave path manually
            * equations that can be used by octave

        NOTE: If one new method is added to this class, its string name should be
              added to the ComputedParameter class as well. This is to prevent from adding
              it to the local context (local_dict)


This class use to manage the plain CSV files (with WHP format)


 This class creates objects used to update data.csv
        with new columns, values or rows. Before that we should process
        the new original.csv and if there is any error, all the actions are resetted


Class to manage Flag Controls and its Events


Export plots in PNG, SVG. All files will be gathered in a ZIP file or PDF


Show the stations on a tile map server


 Controls and events. The widgets and buttons are created here
        Also some other events and triggers such as update points selections


 This class is used for:
            * load the bokeh form for the first time
            * reload the bokeh form
            * reload parts of the bokeh form


 The purpose of this class is to instantiate all the bokeh
        plot objects and make some operations to handle them

        The common attributes for all the plots should be instantiated here,
        or at least assign the values to the bokeh_shared_data


DataTable Controls and events


Creates a DS9 window (named 'VIP_ds9') using pyDS9 functionality.

    The methods of this class allow interacting with the DS9 window. It uses
    XPA under the hood, which mean that using the ``set`` and ``get`` methods
    one can have fine control of the DS9 window. More info here:
    http://ds9.si.edu/doc/ref/xpa.html.


    Define the various modes to use with SVD in PCA as constant strings.

    Modes
    -----
    * ``LAPACK``: uses the LAPACK linear algebra library through Numpy
    and it is the most conventional way of computing the SVD
    (deterministic result computed on CPU).

    * ``ARPACK``: uses the ARPACK Fortran libraries accessible through
    Scipy (computation on CPU).

    * ``EIGEN``: computes the singular vectors through the
    eigendecomposition of the covariance M.M' (computation on CPU).

    * ``RANDSVD``: uses the randomized_svd algorithm implemented in
    Sklearn (computation on CPU), proposed in [HAL09]_.

    * ``CUPY``: uses the Cupy library for GPU computation of the SVD as in
    the LAPACK version. `

    * ``EIGENCUPY``: offers the same method as with the ``eigen`` option
    but on GPU (through Cupy).

    * ``RANDCUPY``: is an adaptation of the randomized_svd algorithm,
    where all the computations are done on a GPU (through Cupy). `

    * ``PYTORCH``: uses the Pytorch library for GPU computation of the SVD.

    * ``EIGENPYTORCH``: offers the same method as with the ``eigen``
    option but on GPU (through Pytorch).

    * ``RANDPYTORCH``: is an adaptation of the randomized_svd algorithm,
    where all the linear algebra computations are done on a GPU
    (through Pytorch).


    Define modes for the pixel-wise scaling.

    Modes
    -----
    * ``TEMPMEAN``: temporal px-wise mean is subtracted.

    * ``SPATMEAN``: spatial mean is subtracted.

    * ``TEMPSTANDARD``: temporal mean centering plus scaling pixel values
    to unit variance. HIGHLY RECOMMENDED FOR ASDI AND RDI CASES!

    * ``SPATSTANDARD``: spatial mean centering plus scaling pixel values
    to unit variance.


    Define modes for processing ADI+mSDI cubes through PCA.

    Modes
    -----
    * ``SINGLE``: PCA only. The multi-spectral frames are rescaled wrt the largest
    wavelength to align the speckles and all the frames (n_channels *
    n_adiframes) are processed with a single PCA low-rank approximation.

    * ``DOUBLE``: PCA and LOCI. A first stage is run on the rescaled spectral frames,
    and a second frame is run on the residuals in an ADI fashion.

    * ``SKIPADI``: LOCI only. The multi-spectral frames are rescaled wrt the largest
    wavelength to align the speckles and the least-squares model is
    subtracted on each spectral cube separately.


List of all possible modes of classic PCA.


Define all metrics possible for various post-processing functions.


Define the values for the low rank mode for LLSG.


Define the values for the auto rank mode for LLSG.


Define the values for thresholding modes for LLSG.


    Define the solver for the least squares problem in LLSG.

    Modes
    -----
    * ``LSTSQ`` : uses the standard scipy least squares solver.

    * ``NNLS`` : uses the scipy non-negative least-squares solver.


    Define the mode for the PostProc PCA object.

    Modes
    -----
    * ``CLASSIC`` : base PCA function, with multiple usages depending on the
    parameters given.

    * ``ANNULAR`` : annular PCA function.

    * ``GRID`` : grid PCA function (can be used implicitely from "classic").

    * ``ANNULUS`` : annulus PCA function.


    Define modes for handling negative values in NMF full-frame.

    Modes
    -----
    * ``SUBTR_MIN`` : subtract the minimum value in the arrays.

    * ``MASK`` : mask negative values.

    * ``NULL`` : set negative values to zero.


    Define modes for initializing SVD for NMF full-frame.

    Modes
    -----
    * ``NNDSVD``: non-negative double SVD recommended for sparseness.

    * ``NNDSVDA`` : NNDSVD where zeros are filled with the average of cube;
        recommended when sparsity is not desired.

    * ``RANDOM`` : random initial non-negative matrix.


    Defines the method of balancing for the flux difference for ANDROMEDA.

    Modes
    -----

    * ``NO``

    * ``TOTAL``

    * ``LSQ``

    * ``ROBUST``


    Define modes to use for the residual noise variance estimation in FMMF.

    Modes
    -----

    * ``FR``: consider the pixels in the selected annulus with a width equal
    to asize but separately for every frame.

    * ``FM``: consider the pixels in the selected annulus with a width
    equal to asize but separately for every frame. Apply a mask one FWHM
    on the selected pixel and its surrounding.

    * ``TE``:rely on the method developped in PACO to estimate the
    residual noise variance (take the pixels in a region of one FWHM
    arround the selected pixel, considering every frame in the
    derotated cube of residuals except for the selected frame).


    Empty object. Used by ``Saveable`` to restore the state of an object without
    calling __init__. Similar to what pickle/copy do.


Show progress bars. Supports multiple backends.

    Examples
    --------
    .. code:: python

        from vip_hci.var import Progressbar
        Progressbar.backend = "tqdm"

        from time import sleep

        for i in Progressbar(range(50)):
            sleep(0.02)

        # or:

        bar = Progressbar(total=50):
        for i in range(50):
            sleep(0.02)
            bar.update()

        # Progressbar can be disabled globally using
        Progressbar.backend = "hide"

        # or locally using the ``verbose`` keyword:
        Progressbar(iterable, verbose=False)


Wraps an ``iterable`` to behave like ``Progressbar``, but without
    producing output.


Context manager for redirecting stdout/err to files


    Dataclass for post-processing information storage.

    Each session of post-processing with one of the PostProc objects has a defined set
    of parameters, a frame obtained with those parameters and a S/N map generated with
    that frame. The Session class holds them in case you need to access them later or
    compare with another session.


    Container for results of post-processing algorithms.

    For each given set of data and parameters, a frame is computed by the PostProc
    algorithms, as well as a S/N map associated. To keep track of each of them, this
    object remembers each set of parameters, frame and S/N map as a session. Sessions
    are numbered in order of creation from 0 to X, and they are displayed to the user
    as going from 1 to X+1.


    Base post-processing algorithm class.

    Does not need an ``__init__`` because as a parent class for every algorithm object,
    there is no reason to create a PostProc object. Inherited classes benefit from the
    ``dataclass_builder`` support for their initialization and no further methods are
    needed to create those.

    The PostProc is still very useful as it provides crucial utility common to all the
    inherited objects, such as :
        - establishing a list of attributes which need to be calculated
        - updating the dataset used for the algorithm if needed
        - calculating the signal-to-noise ratio map after a corrected frame has been
        generated
        - setting up parameters for the algorithm.


    Post-processing frame differencing algorithm.

    Parameters
    ----------
    _algo_name: str, optional
        Name of the algorithm wrapped by the object.


    Object used as a wrapper for the ``vip_hci.psfsub.median_sub``.

    Gets its parameters from the MedsubParams dataclass.

    Parameters
    ----------
    full_output: bool, optional
        Whether to return the final median combined image only or with other
        intermediate arrays.
    _algo_name: str, optional
        Name of the algorithm wrapped by the object.


Post-processing ANDROMEDA algorithm.