Computes and applies a constrained matched multifilter to a set of multi-frequency
       map. The filter is build from provided spatial and spectral source templates and
       the cross spectrum of a set of maps at different frequencies.

	Parameters
	----------
	images: 3D float array
		Data cube containing the input images that are provided at n_f frequencies.
		The dimensions are supposed to be n_f * n_x * n_y, where n_x and n_y are
		the number of pixels along the * and y axis of the images.
	sources: 3D or 4D float array
		Source templates of the n_c components. Can either be a n_c * n_x * n_y
		data cube or alternatively a hypercube of dimensions n_c * n_f * n_x * n_y
		if each image comes at a different spatial resolution.
	spec: 2D float array
		SEDs of the sources. Needs to be provided at the same n_f frequencies as the
		input images. Dimensions are n_c * n_f.
	response: float array
		Array containing the desired response of the filter to each provided source
		template.
	noise_maps: 3D float array, optional
		Data cube containing provided noise maps that will be used to compute noise
		power spectrum matrix. Otherwise the noise power spectrum matrix is directly
		computed from the images. noise_maps need to have the same dimensions as images.
		Default: None
	sigma_noise: float array, optional
		Array containing the standard deviation of the noise for the n_f maps. Does
		allow the analytic computation of the noise power spectrum. Useful for tests
		with white noise. Default: None
	no_cross: bool, optional
		If True the frequency-to-frequency covariance of the n_f maps will be ignored,
		i.e. non-diagonal elements of the noise power spectrum matrix are set to zero.
		Default: False
	global_cross: bool, optional
		If set to True, the cross power of the maps is computed globally
		(i.e. averaged over the full maps / all scales). If False, the
		cross power is computed at each spatial frequency. Default: False

	Returns
	-------
	filtered_image: 2D float array
		Linear combination of the images convolved with the computed constrained matched
		multifilter.
	filter_ft: 3D float array
		Data cube containing the 2D window functions of the constrained matched multifilter.
	noise: float
		Noise level of the filtered map.


        Check if early stopping condition is met.

        Args:
            validation_loss (float): Loss value on the validation set.

        Returns
        -------
            bool: True if early stopping condition is met, False otherwise.


Normalize the input variable(s) using mean and standard deviation.

    Args:
        var (numpy.ndarray): Input variable(s) to be normalized.
        varm (numpy.ndarray): Mean of the variable(s).
        varstd (numpy.ndarray): Standard deviation of the variable(s).

    Returns
    -------
        numpy.ndarray: Normalized variable(s).


    Load and preprocess input data for neural network training.

    Args:
        U (numpy.ndarray): Zonal wind component.
        V (numpy.ndarray): Meridional wind component.
        T (numpy.ndarray): Temperature.
        DSE (numpy.ndarray): Dry static energy.
        NM (numpy.ndarray): Northward mass flux.
        NETDT (numpy.ndarray): Net downward total radiation flux.
        Z3 (numpy.ndarray): Geopotential height.
        RHOI (numpy.ndarray): Air density.
        PS (numpy.ndarray): Surface pressure.
        lat (numpy.ndarray): Latitude.
        lon (numpy.ndarray): Longitude.
        UTGWSPEC (numpy.ndarray): Target zonal wind spectral component.
        VTGWSPEC (numpy.ndarray): Target meridional wind spectral component.

    Returns
    -------
        tuple: A tuple containing the input data and target data arrays.


        Forward pass through the network.

        Args:
            X (torch.Tensor): Input tensor.

        Returns
        -------
            torch.Tensor: Output tensor.


    Training loop.

    Args:
        dataloader (DataLoader): DataLoader for training data.
        model (nn.Module): Neural network model.
        loss_fn (torch.nn.Module): Loss function.
        optimizer (torch.optim.Optimizer): Optimizer.

    Returns
    -------
        float: Average training loss.


    Run the validation loop.

    Args:
        dataloader (DataLoader): DataLoader for validation data.
        model (nn.Module): Neural network model.
        loss_fn (torch.nn.Module): Loss function.

    Returns
    -------
        float: Average validation loss.


Inpainting  the map with Nearest-Neighbours .


MinMax rescale to the map to the physical units


Inpainting with GAN


Set of instructions to inpaint with :class:`DeepPrior`


        Set of instructions to inpaint with
        :class:`ContextualAttention`


Set of instructions to inpaint with :class:`NearestNeighbours`


Define conv for generator.

    Args:
        x: Input.
        cnum: Channel number.
        ksize: Kernel size.
        Stride: Convolution stride.
        Rate: Rate for or dilated conv.
        name: Name of layers.
        padding: Default to SYMMETRIC.
        activation: Activation function after convolution.
        training: If current graph is for training or inference, used for bn.

    Returns:
        tf.Tensor: output


Define deconv for generator.
    The deconv is defined to be a x2 resize_nearest_neighbor operation with
    additional gen_conv operation.

    Args:
        x: Input.
        cnum: Channel number.
        name: Name of layers.
        training: If current graph is for training or inference, used for bn.

    Returns:
        tf.Tensor: output


Define conv for discriminator.
    Activation is set to leaky_relu.

    Args:
        x: Input.
        cnum: Channel number.
        ksize: Kernel size.
        Stride: Convolution stride.
        name: Name of layers.
        training: If current graph is for training or inference, used for bn.

    Returns:
        tf.Tensor: output


Generate a random tlhw with configuration.

    Args:
        config: Config should have configuration including IMG_SHAPES,
            VERTICAL_MARGIN, HEIGHT, HORIZONTAL_MARGIN, WIDTH.

    Returns:
        tuple: (top, left, height, width)


Generate mask tensor from bbox.

    Args:
        bbox: configuration tuple, (top, left, height, width)
        config: Config should have configuration including IMG_SHAPES,
            MAX_DELTA_HEIGHT, MAX_DELTA_WIDTH.

    Returns:
        tf.Tensor: output with shape [1, H, W, 1]


Crop local patch according to bbox.

    Args:
        x: input
        bbox: (top, left, height, width)

    Returns:
        tf.Tensor: local patch


Resize mask like shape of x.

    Args:
        mask: Original mask.
        x: To shape of x.

    Returns:
        tf.Tensor: resized mask


Generate spatial discounting mask constant.

    Spatial discounting mask is first introduced in publication:
        Generative Image Inpainting with Contextual Attention, Yu et al.

    Args:
        config: Config should have configuration including HEIGHT, WIDTH,
            DISCOUNTED_MASK.

    Returns:
        tf.Tensor: spatial discounting mask


 Contextual attention layer implementation.

    Contextual attention is first introduced in publication:
        Generative Image Inpainting with Contextual Attention, Yu et al.

    Args:
        x: Input feature to match (foreground).
        t: Input feature for match (background).
        mask: Input mask for t, indicating patches not available.
        ksize: Kernel size for contextual attention.
        stride: Stride for extracting patches from t.
        rate: Dilation for matching.
        softmax_scale: Scaled softmax for attention.
        training: Indicating if current graph is training or inference.

    Returns:
        tf.Tensor: output


Transfer flow map to image.
    Part of code forked from flownet.


Tensorflow ops for computing flow to image.


Convert flow into middlebury color code image.


Tensorflow ops for highlight flow.


Convert image to edges.


        Implementation of the up-sampling  block

        **Parameters**

        - ``X``:
            input tensor of shape ``(m, n_H_prev, n_W_prev, n_C_prev)``

        - ``f``: {int}
            specifying the shape of the middle CONV's window for the main path
        - ``filters`` :{int}
            defining the number of filters in the CONV layers of the main path
        - ``stage`` :{int}
            used to name the layers, depending on their position in the network
        - ``block``: {string}
            used to name the layers, depending on their position in the network

        **Returns**

        - ``X``:
            output of the convolutional block, tensor of shape ``(n_H, n_W, n_C)``


        Implementation of a down-sampling block

        **Parameters**

        - ``X``:
            input tensor of shape ``(m, n_H_prev, n_W_prev, n_C_prev)``

        - ``f``: {int}
            specifying the shape of the middle CONV's window for the main path
        - ``filters`` :{int}
            defining the number of filters in the CONV layers of the main path
        - ``stage`` :{int}
            used to name the layers, depending on their position in the network
        - ``block``: {string}
            used to name the layers, depending on their position in the network

        **Returns**

        - ``X``:
            output of the convolutional block, tensor of shape ``(n_H, n_W, n_C)``


Loss function evaluated outside the masked region and normalized by  the ground-truth norm.


Accuracy defined as the ratio between  the 2-norms of the prediction and of the ground-truth.


Returns the model summary


Compile the architecture


Iterate over the epochs


Inpainting with Deep -Prior


rescale inpainted map to physical units .


    Estimate Minkowski functionals (:math:`V_0, V_1, V_2`) at a given
    threshold on an image with the technique of  `Marching Squares`, described in Mantz et al 2008.

    **Parameters**

    - ``data`` : {array}
        2D image (rescaled to :math:`[-1,1]`` )
    - ``threshold``: {float}
        threshold value to estimate Minkowski functionals

    **Returns**

    - ``f``: {float}
        the value of :math:`V_0`
    - ``u``:{float}
        the value of :math:`V_1`
    - ``chi``:{float}
        the value of :math:`V_2`


    Returns a target square submap from a projected  HEALPIX map, given a WCS header,
    using :py:mod:`reproject` package

    **Parameters**

    - ``hmap`` : {array}
        healpix map
    - ``target_header``:
        header defined from :func:`set_header`


    Returns a  HEALPIX map projected  and the footprint of a flat one , given a WCS header,
    using :py:mod:`reproject` package

    **Parameters**

    - ``flat`` : {2D array}
        flat  map
    - ``target_header``:
        header defined from :func:`set_header`
    - ``nside``:{int}
        nside of output healpix map


Convert ``ra,dec -> theta,phi``


Convert ``theta,phi -> ra,dec``


Performs  a MinMax Rescaling on an array `x` to a generic range :math:`[a,b]`.


Standardizes  an array `x` to have average ``0``, and std. deviation ``1`` .


Estimate the intersection between two histograms.


Visualize the contextual attention from the Generative inpainting .


Create legend for scaled scatterplot markers


    #Plot flux divergence values for each bin
    if gf.vm is not None and gf.H is not None:
        divQ_bin_mean = np.gradient(H_bin_mean * vm_bin_med * v_col_f)
        axa[1].plot(divQ_bin_mean, z_bin_centers, color='green')


Create scatter plot with scaled circles


    Iteratively numerically estimate eccentric anomaly from mean anomaly
    M (radians) and eccentricity e. 100 iterations is way more than we need,
    but it's not a bottleneck so we are not worried about it.
    Credits: Kellen Lawson


    Defines a set of nord points, distributed according to a cropped Gaussian defined
    by (mu, sigma) and bound between two boundaries specified by the list "limits".
    Unlike mirroring (e.g., np.abs()) or flooring (np.crop()) function, this function
    retains the Gaussianity of the returned array.
    Credits: Vito Squicciarini


Populate input queue with images from input_dir. This will go on forever.


Read the data from the shared memory to the destination tensors.


Immediately put item in the queue. Should raise an exception if the queue is full.
        IPC is not available on Jetson so we need to make sure that the tensor is on CPU before pickling.
        WARNING: pickling is slow and should be avoided if possible.


IPC is not available on Jetson so we need to make sure that the tensor is on CPU before pickling.
        WARNING: pickling is slow and should be avoided if possible.


Calculate the time difference between two log messages.


Read the data at the given index, process safe


Write the data at the given index, process safe


Replaces the oldest element in the buffer with the given tensor


Send the handles of the shared memory slots over a local connection to all child processes.
        This method should be called only from the original process.


Receive the handles of the shared memory slots over a local connection.
        This method should be called only from the child process.
        It needs to be called after the object is unpickled.
        Otherwise the child process will not have access to the shared memory.


initialize persistent memory where the of the buffer will be written


Send the handles of the shared memory slots over a local connection.
        This method should be called only from the original process.


Receive the handles of the shared memory slots over a local connection.
        This method should be called only from the child process.
        It needs to be called after the object is unpickled.
        Otherwise the child process will not have access to the shared memory


Put item in the queue immediately. Should raise an exception if the queue is full.


This method is responsible for communication with outer world, administration and launches the inference procedure whenever needed.


Stop the model process. Should only be called from the parent process. Made to be idempotent.


Change the frequency of the model process. Returns (True, None) if successful, (False, error_message) otherwise


    Loads and resizes images from a list of directories, mimicking the procedure
    in vp_engine/example_input.py.


Runs the benchmark using the visual perception engine.


Runs the benchmark for the specified baseline framework.


Load the model cards of the foundation model and the model heads.


Change the inference rate of the given model. Returns True if successful, False otherwise.


Initialize the model class and return it


Check if the model can be compiled using torch.compile


Export default models such that they can be used in the engine.
        This function takes `registry_path` as an argument, which is the relative path to the registry file.


Create an empty registry file


Load the model dict into a model card
        Args:
            model_dict (dict): dictionary with the model card properties
        Returns:
            ModelCard: model card instance
        Throws:
            AttributeError: if the model type is not recognized


Load the registry file


Register a model in specified jsonl file


Load a model available in the registry


Prediction each pixel.


State dict from the original implementation has different naming convention, hence we need to modify it.


Forward pass of the model with annotated inputs and outputs.


Visualize the output of the model as an image.
        NOTE: this method is optional and should be implemented only if it makes sense to represent model output as an image


ViT weight initialization, original timm impl (for reproducibility)


Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64


x_list contains a list of tensors to nest together and run


Forward pass.

        Args:
            x (tensor): input

        Returns:
            tensor: output


Forward pass.

        Returns:
            tensor: output


Create a logger for the current process.

    :param log_file: Optional, the path to the log file.
    :param log_to_console: Optional, whether to log to stdout.

    :return: The logger object.


Check if the two shapes are compatible, i.e. shape1 can fit into shape2. None values are treated as wildcards.


Check if the signature1 can be used as an input for signature2.


Decorator that asserts that the input and output shapes of the function are correct.
    Can be applied to models implementing ModelInterfaceBase or transforms implementing AbstractTransform.


Decorator that asserts that the input and output types of the function are correct.
    Can be applied to transforms implementing AbstractTransform.


Rezise the sample to ensure the given size. Keeps aspect ratio.

    Args:
        sample (dict): sample
        size (tuple): image size

    Returns:
        tuple: new size


Extracts frames from an OGV video and saves them as images.


    Context manager to run jtop in a separate process to monitor system resources.

    :param output_file: File path to store monitoring data.
    :param duration: Duration in seconds to run the monitoring.


    A really silly linear limb darkening law with a linear
    wavelength dependence.


    The default worker function. Should be replaced
    with the desired mapping function on the first
    call.


    We ignore SIGINT. It's up to our parent to kill us in the typical
    condition of this arising from `^C` on a terminal. If someone is
    manually killing us with that signal, well... nothing will happen.


If this isn't the master process, wait for instructions.


        Like the built-in :py:func:`map` function, apply a function to all
        of the values in a list and return the list of results.

        :param function:
            The function to apply to the list.

        :param tasks:
            The list of elements.


Equivalent to mpi4py :func:`bcast` collective operation.


        Just send a message off to all the pool members which contains
        the special :class:`_close_pool_message` sentinel.


        Equivalent of `map()` built-in, without swallowing
        `KeyboardInterrupt`.

        :param func:
            The function to apply to the items.

        :param iterable:
            An iterable of items that will have `func` applied to them.


    Chooses between the different pools.
    If ``pool == 'AnyPool'``, chooses based on availability.


    Checks for updates to the code on `github` and prints a message
    to the screen if there's a new version available.


    Function to read-in MIRI photometic filters

    :param str f: File location/name of JWST/MIRI photometric filter file. \
                  Default is relative to file.

    :returns: array_like wl_filt: Wavelength grid for filter throughputs \
              [:math:`\mu \mathrm{m}`]
    :returns: array_like dwl_filt: Wavelength bin widths for filter \
              throughputs [:math:`\mu \mathrm{m}`]
    :returns: array_like tputs: Filter throughputs
    :returns: list tputs: List of MIRI filter names


        Plots the filter throughput curve.

        :param ax: An axis instance
        :type ax: :py:obj:`axis`


        Compute the photon count rate registered by the detector.

        :param array_like lam: High-res wavelengths [:math:`\mu \mathrm{m}`]
        :param array_like flux: Spectral flux density \
               [:math:`\mathrm{W/m}^2 / \mu \mathrm{m}`]
        :param float atel: Telescope collecting area [:math:`\mathrm{m}^2`]. \
               Default is `25`
        :param array_like dlam: Delta-wavelength grid. Default is \
               :py:obj:`None` and is calculated

        :returns array_like cphot: Photon count rate [:math:`\mathrm{s}^{-1}`]


        Convolve flux with normalized filter throughput.

        :param array_like lam: High-res wavelength grid [:math:`\mu \mathrm{m}`]
        :param array_like flux:  High-res flux grid \
               [:math:`\mathrm{W/m}^2 / \mu \mathrm{m}`]

        :returns array_like F: Flux convolved with normalized throughput


        Computes an observed lightcurve in the :py:func:`Filter`.

        :param array_like time: Time grid [days]
        :param array_like flux: Observed flux grid (`time` by `lam`) \
               [:math:`\mathrm{W/m}^2 / \mu \mathrm{m}`]
        :param array_like continuum: Observed *continuum* flux grid (no \
               occultations, shape `time` by `lam`) \
               [:math:`\mathrm{W/m}^2 / \mu \mathrm{m}`]
        :param array_like lam: Wavelength [:math:`\mu \mathrm{m}`]
        :param int stack: Number of exposures to stack. Default `1`
        :param float atel: Telescope collecting area [:math:`\mathrm{m}^2`]. \
               Default `25`
        :param bool thermal: Compute thermal noise. Default :py:obj:`True`
        :param array_like time_hr: High-res time grid [Days]. \
               Default :py:obj:`None`
        :param array_like flux_hr: High-res flux grid. Default :py:obj:`None`


        Plots the synthetic lightcurve.

        :param ax0: User provided plot :py:obj:`axis`. Default :py:obj:`None`
        :type ax0: :py:obj:`axis`
        :param str title: Plot title. Defult ""


    Planck blackbody function.

    :param float or array_like temp: Temperature [K]
    :param float or array_like wav: Wavelength [:math:`\mu \mathrm{m}`]

    :returns array_like B_lambda: Planck function \
             [:math:`\mathrm{W/m}^2 / \mu \mathrm{m}`]


    Plot JWST/MIRI photometric filter bands.

    :param :py:obj:`Axis` ax: Matplotlib Axis
    :param array_like wl: Wavelengths
    :param array_like filters: Filter throughput curves
    :param list names: Names of filters
    :param tuple ylim: y-axis limits. Default `(0.0, 1.0)`
    :param bool leg: Add a legend to the plot. Default :py:obj:`True`


    Calculates the JWST thermal background from (Glasse et al. 2015)

    :param array_like wl: Wavelength grid [:math:`\mu \mathrm{m}`]

    :returns array_like Fback: Spectral flux density \
             [:math:`\mathrm{W/m}^2 / \mu \mathrm{m}`]


    Estimate the signal-to-noise on the detection of secondary eclipses in
    JWST/MIRI photometric filters.

    :param float tint: Exposure time [s]. Default `36.4*60.`
    :param float nout: Out-of-transit time observed [transit durations]. \
           Default `4`
    :param float lammin: Wavelength minimum [:math:`\mu \mathrm{m}`]. \
           Default `1.0`
    :param float lammax: Wavelength maximum [:math:`\mu \mathrm{m}`]. \
           Default `30.0`
    :param int Nlam: Number of wavelengths. Default `10000`
    :param float Tstar: Stellar effective temperature [K]. Default `2560`
    :param float Tplan: Planet equilibrium temperature [K]. Default `400`
    :param float Rs: Stellar radius [solar radii]. Default `0.12`
    :param float Rp: Planet radius [Earth radii]. Default `1.086`
    :param float d: System distance [pc]. Default `12.2`
    :param float atel: Telescope collecting area [:math:`\mathrm{m}^2`]. \
           Default `25`
    :param verbose: Print things. Default `True`
    :param plot: Make a plot. Detault `True`
    :param thermal: Include thermal noise. Default `True`
    :param filters: User provided filter names or list of filters. Default \
            `MIRI`
    :type filters: str or list of :py:func:`Filter` objects


    Returns a function of time for testing.

    :param array_like t: Time grid
    :param float factor: Relative variability factor

    :returns array_like f: A function of time


    Creates a fake flux dataset as a function of wavelength and
    time for testing.

    :param int Nlam: Number of wavelengths. Default `4000`
    :param int Ntime: Number of times. Default `4000`
    :param float lammin: Wavelength min [:math:`\mu \mathrm{m}`]. Defult `1.0`
    :param float lammax: Wavelength max [:math:`\mu \mathrm{m}`]. Defult `30.0`
    :param float tmin: Time min [days]. Default `0.0`
    :param float tmax: Time max [days]. Default `4.0`
    :param float Tstar: Stellar effective temperature [K]. Defult `2560`
    :param float Tplan: Planet equilibrium temperature [K]. Defult `400`
    :param float Rs: Stellar radius [solar radii]. Default `0.12`
    :param float Rp: Planet radius [Earth radii]. Default `1.086`
    :param float d: System distance [pc]. Default `12.2`
    :param float tfact: Relative variability factor. Default `0.01`

    :returns tuple ttup: (`time`, `delta_time`)
    :returns tuple ltup: (`lam`, `delta_lam`)
    :returns tuple data: Flux as a function of time and wavelength


    Generate a low-resolution grid and bin widths

    :param float lomin: Min value
    :param float lomax: Max value
    :param int Nlow: Number of final points

    :returns array_like lr: New evenly-spaced grid
    :returns array_like dlr: New bin widths


    Re-bin series to lower resolution using `sp.binned_statistic`

    :param array_like yhr: Series to be degraded
    :param array_like xhr: High-res x grid
    :param array_like xlr: Low-res x grid
    :param array_like dxlr: Low-res x width grid. Default :py:obj:`None`

    :returns: array_like ylr: Low-res series


    Draw fake data points from model `val` with errors `sig`

    :param float or array_like val: Mean of Gaussian to sample from
    :param float or array_like sig: Standard dev. of Gaussian to sample from

    :returns float or array_like: Randomly sampled fake data points


    Create a tophat :py:func:`Filter`

    :param float lammin: Wavelength minimum [:math:`\mu \mathrm{m}`]
    :param float lammax: Wavelength maximum [:math:`\mu \mathrm{m}`]
    :param float dlam: Wavelength resolution [:math:`\mu \mathrm{m}`]. \
           Default `0.1`
    :param float Tput: Filter throughput. Default `0.3`
    :param str name: Name of filter. Default "custom"

    :returns filt: New custom tophat :py:func:`Filter` object
    :type filt: :py:func:`Filter`


    The Rodrigues rotation formula in 3D, given a vector `v`, a unit vector `k`
    normal to the plane of rotation, and the angle of rotation `theta`
    in radians.


The cross product of vectors `u` and `v`, normalized to unity.


    Computes the eyeball angles :math:`\\theta` and :math:`\gamma` given the
    Cartesian orbital elements and the hotspot offset angles :math:`\Lambda`
    and :math:`\Phi`.

    :param float x: The **x** component of the planet's position vector
    :param float y: The **y** component of the planet's position vector
    :param float z: The **z** component of the planet's position vector
    :param float vx: The **x** component of the planet's velocity vector
    :param float vy: The **y** component of the planet's velocity vector
    :param float vz: The **z** component of the planet's velocity vector
    :param float Lambda: The longitudinal hotspot offset in radians. \
           Default `0`
    :param float Phi: The latitudinal hotspot offset in radians. Default `0`
    :returns: :math:`\\theta` and :math:`\gamma`, the eyeball phase angles, \
              in radians


    Creates a floating axis and draws an "eyeball" planet at given
    phase and rotation angles.

    .. plot::
         :align: center

         from planetplanet import DrawEyeball
         from planetplanet.photo.maps import RadiativeEquilibriumMap
         import matplotlib.pyplot as pl
         fig = pl.figure(figsize = (3,3))
         DrawEyeball(radiancemap = RadiativeEquilibriumMap(), fig = fig)
         pl.show()

    :param float x0: The `x` position of the center of the planet in \
           figure coordinates
    :param float y0: The `y` position of the center of the planet in \
           figure coordinates
    :param float r: The radius of the planet in figure coordinates
    :param float theta: The phase angle of the eyeball in radians. \
           Default :math:`\pi/3`
    :param float gamma: The rotation angle of the eyeball in radians. \
           Default `0`
    :param int nz: The number of zenith angle wedges. Default `11`
    :param array_like occultors: A list of :py:obj:`dict` instances with \
           information on each of the occultors to draw. \
    Each dictionary must have keywords `x`, `y`, and `r`, corresponding to \
           the xy position and radius of the \
    occultor, respectively. These are defined relative to the center of the \
           planet and scaled so that the \
    radius of the planet is unity. Optional keywords are `zorder`, `color`, \
           and `alpha`. Default :py:obj:`[]`
    :param str cmap: The name of the :py:class:`matplotlib` colormap. \
           Default `inferno`
    :param fig: The figure object in which to create the axis. \
           Default :py:obj:`None`
    :type fig: :py:class:`matplotlib.Figure`
    :param bool draw_terminator: Draw the terminator ellipse outline? \
           Default :py:obj:`False`
    :param bool draw_ellipses: Draw the zenith angle ellipse outlines? \
           Default :py:obj:`False`
    :param bool rasterize: Rasterize the image? Default :py:obj:`False`
    :param str color: Occulted body outline color. Default :py:obj:`None`

    :return: **fig**, **ax**, **occ**, **xy**. These are the figure and \
             floating axis instances, a lits of :py:obj:`Circle` \
             instances corresponding to each of the occultors, and a function \
             **xy** that performs the rotation \
             transformation into the axis-symmetric eyeball frame


    Draw an "eyeball" planet's orbit on the sky, illustrating the changing
    phases over the course of the orbit.

    .. plot::
         :align: center

         from planetplanet import DrawOrbit
         import matplotlib.pyplot as pl
         DrawOrbit(Omega = 45., size = 2, figsize = (6, 6))
         pl.show()

    :param float inc: The orbital inclination in degrees. Default `70.`
    :param float Omega: The longitude of ascending node in degrees. \
           Default `0.`
    :param float ecc: The orbital eccentricity. Default `0.`
    :param float w: The longitude of pericenter in degrees. Default `0.`
    :param float Phi: The latitudinal hot spot offset in degrees. Default `0.`
    :param float Lambda: The longitudinal hot spot offset in degrees. \
           Default `0.`
    :param int nphases: The number of planets to draw at different phases. \
           Default `20`
    :param float size: The size of the planets in arbitrary units. Default `1.`
    :param bool draw_orbit: Draw the orbit outline? Default :py:obj:`True`
    :param bool draw_orbital_vectors: Draw the orbital radial vectors? \
           Default :py:obj:`True`
    :param bool plot_phasecurve: Compute and plot the phase curve for one \
           orbit? Default :py:obj:`False`
    :param bool label_phases: Label each of the phases? Default :py:obj:`False`
    :param tuple figsize: The size of the figure in inches. \
           Default :py:obj:`(8, 8)`
    :param dict kwargs: Any other :py:obj:`kwargs` to be passed to \
           :py:func:`DrawEyeball`

    :returns: `fig`, `axes`, and optionally `figphase`, `axphase`; these are \
              all the figure and axes objects generated by the function


    Plots the curve `y(x)` with linearly increasing alpha.
    Adapted from `http://nbviewer.jupyter.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb`_.


        Pause/play the animation. Unfortunately I haven't been able to
        figure out how to freeze the animation so that it resumes at the
        same frame it was paused on...


Play frame `j` of the animation.


        Applies all settings, makes bodies accessible as properties, resets
        flags, and computes some preliminary orbital information for the
        system.


Allocate memory for all the C arrays.


        Run telescope observability calculations for a system that has had its
        lightcurve computed. Calculates a synthetic noised lightcurve in the
        user specified filter.

        :param bool save: Save a text file and a plot. Default :py:obj:`None`
        :param filter: Filter name or :py:func:`Filter` object. \
               Default `'f1500w'`
        :type filter: str or :py:func:`Filter`
        :param int stack: Number of exposures to stack. Default `1`
        :param str instrument: Telescope instrument to use. Default `'jwst'`


        Plots an image of the `occulted` body and its occultor(s) at a
        given index of the `time_hr` array `t`.

        .. plot::
             :align: center

             from planetplanet.photo.eyeball import DrawEyeball
             import matplotlib.pyplot as pl
             DrawEyeball(0.535, 0.5, 0.25, theta = 1., gamma = 1.,
                         occultors = [{'x': 0.2, 'y': 0.4, 'r': 0.5}],
                         cmap = 'inferno')
             pl.show()

        :param int t: The index of the occultation in the high resolution \
               time array `time_hr`
        :param occulted: The occulted body instance
        :type occultor: :py:class:`BODY` or :py:obj:`list`
        :param occultor: The occultor(s). Default :py:obj:`None`
        :type occultor: :py:class:`BODY` or :py:obj:`list`
        :param float wavelength: The wavelength in microns at which to plot \
               the light curve. Must be within the wavelength grid. \
               Default `15`
        :param fig: The figure on which to plot the image
        :type fig: :py:class:`matplotlib.Figure`
        :param float figx: The x coordinate of the image in figure units. \
               Default `0.535`
        :param float figy: The y coordinate of the image in figure units. \
               Default `0.5`
        :param float figr: The radius of the image in figure units.
               Default `0.05`


        Plot the light curve of the system after running :py:func:`compute`.

        .. plot::
             :align: center

             from scripts import lightcurve
             import matplotlib.pyplot as pl
             lightcurve.plot()
             pl.show()

        :param float wavelength: The wavelength in microns at which to plot \
               the light curve. Must be within the wavelength grid. \
               Default `15`
        :param bool interactive: Interactive (clickable) plot? Default \
               :py:obj:`True`. If :py:obj:`False`, returns a :py:obj:`fig` \
               and an :py:obj:`axis` instance.
        :returns: :py:obj:`(fig, ax)` if \
                  :py:obj:`interactive` = :py:obj:`False`


        Plot the orbits of a given set of bodies over `nper` periods.

        .. plot::
             :align: center

             import matplotlib.pyplot as pl
             import numpy as np
             import planetplanet as pp
             T1 = pp.Trappist1()
             T1.compute_orbits(np.linspace(0,10,10000))
             fig, ax = T1.plot_orbits()
             pl.show()

        :param planets: The planet(s) to plot. Can be a list of strings \
               corresponding to their names or a list of \
               :py:obj:`Planet <planetplanet.photo.structs.Planet>` instances.\
               Default is to plot all planets in the system
        :param float trail_dur: The duration of the orbital trails in days. \
               Default `1`
        :returns: A figure and an axis instance


Picker event for interactive light curves


The total flux of the system computed on a grid of time and wavelength.


        The total *continuum* flux of the system computed on a
        grid of time and wavelength. This is the same as :py:attr:`flux`,
        but without any occultations/transits.


        The total flux of the system computed on a grid of high
        resolution time and wavelength.


Wavelength array in microns.


    Returns an instance of :py:obj:`planetplanet.photo.System` for the full
    TRAPPIST-1 system. Star and planet parameters are drawn from their
    respective prior distributions, which are based on the observed values
    from Gillon et al. (2017), Luger et al. (2017), and
    Burgasser & Mamajek (2017). Longitudes of ascending node are
    drawn from the :math:`\\theta` distribution derived in the paper.

    :param bool sample: Draw a random sample from the full prior? \
           If :py:obj:`False`,returns the mean values for all parameters. \
           Default :py:obj:`True`
    :param float distance: Distance to the system in parsecs. \
           Default :py:obj:`12`
    :param int seed: Random number generator seed. Default :py:obj:`None`
    :param kwargs: Any other :py:obj:`kwargs` to be passed to \
           :py:func:`planetplanet.Star`, \
           :py:func:`planetplanet.Planet`, and :py:func:`planetplanet.System`.

    .. plot::
         :align: center

         from planetplanet.photo.trappist1 import Trappist1
         from planetplanet.constants import MINUTE
         import matplotlib.pyplot as pl
         import numpy as np
         system = Trappist1()
         system.compute(np.arange(0, 10, 1 * MINUTE))
         system.plot_lightcurve()
         pl.show()


        We need to update the time of pericenter passage whenever the
        eccentricty, longitude of pericenter, period, or time of transit
        changes. See the appendix in Shields et al. (2016).


The mean anomaly at a time `t`.


        Draws the orbit of the body on the sky. Accepts the keyword
        arguments taken by :py:func:`planetplanet.photo.eyeball.DrawOrbit`.


Can't set this property for the star.


    Returns the value of the cumulative distribution function (CDF) of the
    polar angle of the angular momentum vector, :math:`\\theta`.

    .. plot::
         :align: center

         from planetplanet.photo import theta
         import matplotlib.pyplot as pl
         x = np.linspace(0, 1, 1000)
         y = [theta.CDF(xi) for xi in x]
         pl.plot(x, y)
         pl.xlabel(r'$\\theta$ [deg]', fontweight = 'bold')
         pl.ylabel('Cumulative Probability', fontweight = 'bold')
         pl.show()


    Draw a sample from the distribution of polar angle of the angular
    momentum vector, :math:`\\theta`, computed using the Monte Carlo
    technique discussed in the paper.

    .. plot::
         :align: center

         from planetplanet.photo import theta
         import matplotlib.pyplot as pl
         x = [theta.sample() for i in range(10000)]
         pl.hist(x, bins = 50)
         pl.xlabel(r'$\\theta$ [deg]', fontweight = 'bold')
         pl.ylabel('Probability', fontweight = 'bold')
         pl.show()


    The default limb-darkened map. This is really a dummy function, since
    this is already hard-coded in the C engine.


    The default eyeball map. This is really a dummy function, since this is
    already hard-coded in the C engine.


    A uniform surface radiance map.

    :param float albedo: The body's albedo. Default `0.3`
    :param float irrad: The body's irradiation. Default is the Solar \
           constant, :py:obj:`SEARTH`


    A quirky periodic surface map that simulates banded clouds on a gas giant.
    Not terribly realistic, but showcases what the code can do.

    :param float albedo: The body's albedo. Default `0.3`
    :param float irrad: The body's irradiation. Default is the Solar \
           constant, :py:obj:`SEARTH`
    :param int bands: The number of bands. Default `5`


    This is a function generator that returns a surface map.
    It can have an arbitrary number of args/kwargs, but for
    simplicity we allow the user to tune two parameters: the FWHM of the
    hotspot in degrees, which for this map we'll assume is a Gaussian in
    zenith angle, and the temperature of the hotspot in K.


        The actual function that returns the radiance at a given wavelength
        and zenith angle.


    View an image of the planet w/ the custom map at a given phase angle.
    Note that I tuned `theta` and `gamma` to match the hotspot offset specified
    in the `secondary_eclipse` function below.


Compute and plot the planet's secondary eclipse light curve.


    Computes and plots the scatter plot for the TRAPPIST-1
    system seen with JWST MIRI at 15 microns over the
    course of 3 years.

    :param bool eyeball: Assume the radiative equilibrium surface map? \
           Default :py:obj:`True`. If :py:obj:`False`, uses the limb-darkened
           surface map.


     `N` stacked exposures of `b` occulting `c` observed in
     both Warm Spitzer filters


    Make a *sick* corner plot showing the projections of a data set in a
    multi-dimensional space. kwargs are passed to hist2d() or used for
    `matplotlib` styling.

    Parameters
    ----------
    xs : array_like (nsamples, ndim)
        The samples. This should be a 1- or 2-dimensional array. For a 1-D
        array this results in a simple histogram. For a 2-D array, the zeroth
        axis is the list of samples and the next axis are the dimensions of
        the space.

    weights : array_like (nsamples,)
        The weight of each sample. If `None` (default), samples are given
        equal weight.

    labels : iterable (ndim,) (optional)
        A list of names for the dimensions. If a ``xs`` is a
        ``pandas.DataFrame``, labels will default to column names.

    show_titles : bool (optional)
        Displays a title above each 1-D histogram showing the 0.5 quantile
        with the upper and lower errors supplied by the quantiles argument.

    title_fmt : string (optional)
        The format string for the quantiles given in titles.
        (default: `.2f`)

    title_args : dict (optional)
        Any extra keyword arguments to send to the `add_title` command.

    range : iterable (ndim,) (optional)
        A list where each element is either a length 2 tuple containing
        lower and upper bounds or a float in range (0., 1.)
        giving the fraction of samples to include in bounds, e.g.,
        [(0.,10.), (1.,5), 0.999, etc.].
        If a fraction, the bounds are chosen to be equal-tailed.

    truths : iterable (ndim,) (optional)
        A list of reference values to indicate on the plots.  Individual
        values can be omitted by using ``None``.

    truth_color : str (optional)
        A ``matplotlib`` style color for the ``truths`` makers.

    scale_hist : bool (optional)
        Should the 1-D histograms be scaled in such a way that the zero line
        is visible?

    quantiles : iterable (optional)
        A list of fractional quantiles to show on the 1-D histograms as
        vertical dashed lines.

    verbose : bool (optional)
        If true, print the values of the computed quantiles.

    plot_contours : bool (optional)
        Draw contours for dense regions of the plot.

    use_math_text : bool (optional)
        If true then axis tick labels for very large or small exponents will be
        displayed as powers of 10 rather than using `e`.

    no_fill_contours : bool (optional)
        Add no filling at all to the contours (unlike setting
        ``fill_contours=False``, which still adds a white fill at the densest
        points).

    plot_datapoints : bool (optional)
        Draw the individual data points.

    max_n_ticks: int (optional)
        maximum number of ticks to try to use

    fig : matplotlib.Figure (optional)
        Overplot onto the provided figure object.


    Like numpy.percentile, but:

    * Values of q are quantiles [0., 1.] rather than percentiles [0., 100.]
    * scalar q not supported (q must be iterable)
    * optional weights on x


Plot a 2-D histogram of samples.


    Simulate an observation of a secondary eclipse of each of
    the TRAPPIST-1 planets with JWST MIRI at 15 microns and
    compute the SNR.


    Compute the SNR analytically with back-of-the envelope
    calculations. This is a sanity check on the values we get
    with planetplanet.


    Submits a PBS cluster job to run :py:func:`Compute` in parallel.

    :param str queue: The name of the queue to submit to. \
           Default :py:obj:`None`
    :param str email: The email to send job status notifications to. \
           Default :py:obj:`None`
    :param int walltime: The number of hours to request. Default `8`
    :param int nodes: The number of nodes to request. Default `5`
    :param int ppn: The number of processors per node to request. Default `12`
    :param int nsamp: The number of prior samples to draw. Default `50,000`
    :param bool eyeball: Use the radiative equilibrium surface map? \
           Default :py:obj:`True`
    :param int batch_size: Size of each batch used in the parallelization. \
           Default `100`
    :param int mpn: Memory per node in gb to request. Default no setting.
    :param int nproc: Number of processes to spawn. Default is the number of \
           core.


Runs the actual parallelized computations. Used internally.


    Compute occultation histograms by drawing `nsamp` draws from the
    system prior. Saves the results to `data/histXXX.npz`.

    :param int nsamp: The number of prior samples to draw. Default `300`
    :param float minsnr: The minimum SNR to include in the tally. Default `1.`
    :param bool nbody: Use the N-Body solver? Default :py:obj:`True`
    :param bool progress_bar: Display a progress bar? Default :py:obj:`True`
    :param bool eyeball: Assume eyeball planets? Default :py:obj:`True`. If
           :py:obj:`False`, uses the limb darkened surface map.


Merge all the `npz` savesets into a single one for faster plotting.


Plots the results of a `Compute()` run and returns several figures.


Plots all histogram figures for the paper.


Compute the zenith angle.


    Simulate an observation of a triple occultation of TRAPPIST-1 `c` by `b`
    with OST.

        .. plot::
         :align: center

         from scripts import ost_example
         import matplotlib.pyplot as pl
         ost_example.Triple_bc()
         pl.show()


    Simulate `N` stacked exposures of `b` occulting `c`.

        .. plot::
         :align: center

         from scripts import ost_example
         import matplotlib.pyplot as pl
         ost_example.Stacked_bc()
         pl.show()


        Signal-to-noise ratio of an occultation of TRAPPIST-1c by TRAPPIST-1b
        as a function of wavelength for OST, assuming 5 micron-wide
        filters.

        .. plot::
             :align: center

             from scripts import ost_example
             import matplotlib.pyplot as pl
             ost_example.SNR_v_wavelength()
             pl.show()


    A really silly linear limb darkening law with a linear
    wavelength dependence.


    Submits a PBS cluster job to run :py:func:`Compute` in parallel.

    :param str queue: The name of the queue to submit to. \
           Default :py:obj:`None`
    :param str email: The email to send job status notifications to. \
           Default :py:obj:`None`
    :param int walltime: The number of hours to request. Default `8`
    :param int nodes: The number of nodes to request. Default `5`
    :param int ppn: The number of processors per node to request. Default `12`
    :param int nsamp: The number of prior samples to draw. Default `50,000`
    :param int batch_size: Size of each batch used in the parallelization. \
           Default `100`
    :param int mpn: Memory per node in gb to request. Default no setting.
    :param int nproc: Number of processes to spawn. Default is the number of \
           core.


    Runs the simulations.

    :param int nsamp: The number of prior samples to draw. Default `300`
    :param bool nbody: Use the N-Body solver? Default :py:obj:`True`
    :param bool progress_bar: Display a progress bar? Default :py:obj:`True`


  A really silly linear limb darkening law with a linear
  wavelength dependence.


    Simulate an observation of a triple occultation of TRAPPIST-1 `c` by `b`
    with JWST MIRI at 15 microns.

    .. plot::
         :align: center

         from scripts import jwst_example
         import matplotlib.pyplot as pl
         jwst_example.Triple_bc()
         pl.show()


    Simulate `N` stacked exposures of `b` occulting `c` in the
    MIRI F1500W filter.

    .. plot::
         :align: center

         from scripts import jwst_example
         import matplotlib.pyplot as pl
         jwst_example.Stacked_bc()
         pl.show()


     Simulate N stacked exposures of `b` occulting `c`
     observed in all MIRI filters.

     .. plot::
         :align: center

         from scripts import jwst_example
         import matplotlib.pyplot as pl
         figs = jwst_example.Stacked_bc_all_filters()
         for fig in figs[:-1]:
             pl.close(fig)
         pl.show()


    Compute the radiance at a point on the planet's surface
    at a given wavelength.


Get decorator to mark a method as the handler for a particular VCS.


Store f in HANDLERS[vcs][method].


Call the given command(s).


Extract version information from the given file.


Get version information from git keywords.


Get version from 'git describe' in the root of the source tree.

    This only gets called if the git-archive 'subst' keywords were *not*
    expanded, and _version.py hasn't already been rewritten with a short
    version string, meaning we're inside a checked out source tree.


Git-specific installation logic for Versioneer.

    For Git, this means creating/changing .gitattributes to mark _version.py
    for export-subst keyword substitution.


Try to determine the version from the parent directory name.

    Source tarballs conventionally unpack into a directory that includes both
    the project name and a version string. We will also support searching up
    two directory levels for an appropriately named parent directory


Try to determine the version from _version.py if present.


Write the given version number to the given _version.py file.


Return a + if we don't already have one, else return a .


Build up version string, with post-release "local version identifier".

    Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
    get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty

    Exceptions:
    1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]


TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE


TAG[.postDISTANCE[.dev0]+gHEX] .

    The ".dev0" means dirty. Note that .dev0 sorts backwards
    (a dirty tree will appear "older" than the corresponding clean one),
    but you shouldn't be releasing software with -dirty anyways.

    Exceptions:
    1: no tags. 0.postDISTANCE[.dev0]


TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]


TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


Render the given version pieces into the requested style.


Perform VCS-independent setup function for installing Versioneer.


Validate the contents of setup.py against Versioneer's expectations.


Group the tags by major and minor version
    Parameters
    ----------
    tags : list of str
        A list of tags to group

    Returns
    -------
    dict
        A dictionary with the major and minor version as keys and a list of tags as values


Get the 'PATH_*' variable set in the environment

    Parameters
    ----------
    name : str
        Name of the environment variable.

    Returns
    -------
    str
        Defined path or raises an error if the variable is not defined and
        pointing to a valid path.


Restore the SingleStar() object to its i-th state, keeping the star history before the i-th state.

        Parameters
        ----------
        i : int
            Index of the star object history to reset the star to. By default
            i == 0, i.e. the star will be restored to its initial state.
        hooks : list
            List of extra hooks associated with the SimulationProperties() of the BinaryStar()
            object containing this SingleStar(), if applicable. This parameter is
            automatically set when restoring a BinaryStar() object.


Return history parameters from the star in a DataFrame.

        By default all parameters in STARPROPERTIES are included.

        Parameters
        ----------
        extra_columns : dict( 'name':dtype, .... )
            Extra star history parameters to return in DataFrame that are not
            included in STARPROPERTIES. All columns must have an
            associated pandas data type.
            Can be used in combination with `only_select_columns`.
            Assumes names have no suffix.
        ignore_columns : list
            Names of STARPROPERTIES parameters to ignore.
            Assumes names have `_history` suffix.
        only_select_columns : list
            Names of the only columns to include.
            Can be used in combination with `extra_columns`.
            Assumes names have `_history` suffix.
        include_profile : bool
            Include the star's profile in the dataframe (NOT RECOMMENDED)
        null_value : float, optional
            Replace all None values with something else (for saving).
            Default is np.nan.
        prefix : str, optional
            Prefix to all column names. (e.g. 'star_1', 'S1')
            Default has no prefix.

        Returns
        -------
        pandas DataFrame


Convert SingleStar into a single row DataFrame.

        By default, initial final values of history are used with the `to_df`
        method. Any scalar values can also be added.

        Parameters
        ----------
        scalar_names : list of str
            Names of any values to be added to the oneline DataFrame.
        history : bool
            Include the history initial-final values from to_df method.
        prefix : str
            Any prefix to go at the beginning of all columns names.
        **kwargs
            All options for the to_df method.

        Returns
        -------
        oneline_df


Create a SingleStar object from a single-star grid run.


Instantiate step classes and set as instance attributes.

        Parameters
        ----------
        verbose: bool
            Print extra information.

        Returns
        -------
        None


Close hdf5 files before exiting.


Functions called before a binary evolves.

        Uses all extra hooks classes or extra functions.

        Parameters
        ----------
        binary : instance of <class, BinaryStar>
            The binary before evolution starts.

        Returns
        -------
        binary : instance of <class, BinaryStar>


Prepare for step.

        The method is called before every evolution step; uses all extra hooks
        classes or extra functions (except for undefined next step errors).

        Parameters
        ----------
        binary : instance of <class, BinaryStar>
            The binary before evolution starts.
        step_name : str
            The name of the step about to be called (as defined in the flow).

        Returns
        -------
        binary : instance of <class, BinaryStar>


Finalize step.

        The method is called after every evolution step; uses all extra hooks
        classes or extra functions (except for undefined next step errors).

        Parameters
        ----------
        binary : instance of <class, BinaryStar>
            The binary before evolution starts.
        step_name : str
            The name of the step about to be called (as defined in the flow).

        Returns
        -------
        binary : instance of <class, BinaryStar>


Finalize the evolution of the binary.

        The method is called after a binary exits the evolution loop.
        Uses all extra hooks classes or extra functions.

        Parameters
        ----------
        binary : instance of <class, BinaryStar>
            The binary after evolution is ended.

        Returns
        -------
        binary : instance of <class, BinaryStar>


Initialize the step time to match history.


Record the duration of the step.


Add None's to step_times to match history rows.


Initialize the step name to match history.


Record the step name.


Ensure None's are append to step_names to match rows in history.


Generate the flow chart.

    Default step nomenclature:
    - step_SN :  StepSN in posydon/bianry_evol/SN/step_SN.py
    - step_HMS_HMS : MS_MS_step in posydon/binary_evol/mesa_step.py
    - step_CO_HMS_RLO : CO_HMS_RLO_step in posydon/binary_evol/mesa_step.py
    - step_CO_HeMS : CO_HeMS_step in posydon/binary_evol/mesa_step.py
    - step_detached : detached_step in posydon/binary_evol/detached_step.py
    - step_CE : StepCEE in posydon/binary_evol/CE/step_CEE.py
    - step_dco : DoubleCO in posydon/binary_evol/double_CO.py
    - step_end

    Parameters
    ----------
    FLOW_CHART : dict
        Flow chart that maps the tuple (star_1_state, star_1_state,
        binary_state, binary_event) to a step.
    CHANGE_FLOW_CHART : dict
        Flow chart to change the default FLOW_CHART. E.g.
        CHANGE_FLOW_CHART = {('NS', 'NS', 'detached', None) : 'step_end',
                             ('NS', 'HeMS', 'RLO1', 'pRLO1') : 'step_my_RLO1'}

    Returns
    -------
    dict
        Flow chart.


Modify POSYDON's default flow to:
        ZAMS binaries -> detached
        oRLO1/oRLO2 -> HMS-HMS RLO grid

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

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


Evolve a binary from start to finish.


Evolve the binary through one evolutionary step.


Update the history of the binaries' properties.


Restore the BinaryStar() object to its i-th state, keeping the binary history before the i-th state.

        Parameters
        ----------
        i : int
            The index of the binary object history to reset the binary to.
            By default 0, i.e. the star will be restored to its initial state.


Reset the binary to its ZAMS state.

        Parameters
        ----------
        properties : SimulationProperties
            Instance of the SimulationProperties class (default: None)


Update the states of the two stars in the binary.


Return history parameters from the binary in a DataFrame.

        Includes star 1 and 2 (S1, S2) data and an extra column 'binary_index'.

        Parameters
        ----------
        extra_columns : dict( 'name':dtype, .... )
            Extra binary parameters to return in DataFrame that are not
            included in BINARYPROPERTIES. All columns must have an
            associated pandas data type.
            Can be used in combination with `only_select_columns`.
            Assumes names have no suffix.
        ignore_columns : list
            Names of binary parameters to ignore.
            Assumes names have `_history` suffix.
        only_select_columns : list
            Names of the only columns to include.
            Assumes names have `_history` suffix.
            Can be used in combination with `extra_columns`.
        null_value : float
            Replace all None values with something else (for saving).
            Default is np.nan.
        include_S1, include_S2 : bool
            Choose to include star 1 or 2 data to the DataFrame.
            The default is to include both.
        S1_kwargs, S2_kwargs : dict
            kwargs to pass to each star's 'to_df' method (extra/ignore columns)

        Returns
        -------
        pandas DataFrame


Convert a binary from a pandas DataFrame to BinaryStar instance.

        Parameters
        ----------
        dataframe : Pandas DataFrame
            data to turn into a BinaryStar instance.
        index : int, optional
            Sets the binary index.
        extra_columns : dict, optional
            Column names to be added directly to binary
            not in BINARYPROPERTIES.

        Returns
        -------
            New instance of BinaryStar


Convert binary into a single row DataFrame.


Convert a oneline DataFrame into a BinaryStar.

        The oneline DataFrame is expected to have initial-final
        values from history and any individual values that don't have
        histories.

        Parameters
        ----------
        oneline_df : DataFrame
            A oneline DataFrame describing a binary.
        index : int, None
            Binary index
        extra_columns : dict
            Names of any extra history columns not inlcuded
            in BINARYPROPERTIES

        Returns
        -------
            A new BinaryStar instance.


Return nan if `value` is neither int nor float.


Create a BinaryStar object from a PSyGrid run.


Generate a message with the initial conditions.

        Parameters
        ----------

        ini_params : None or iterable of str
            If None take the initial conditions from the binary, otherwise add
            each item of it to the message.

        Returns
        -------
        string
            The message with the binary initial conditions.


Compute the square distance used for scaling.


Nomarlize quantities in the single star grids to (0,1).

        Parameters
        ----------
        key : str
            Keyword of the required quantity.
        method : str
            Scalling method in the data normalization class

        Returns
        -------
        class
            Data normalization class


Get the track in the grid that matches the time and mass of a star.

        For "root" matching_method, the properties that are matched is always
        the mass of the secondary star.
        If the secondary has the state `MS` then
        the center hydrogen abundance will also be matched
        otherwise the mass of helium-core will be matched.

        Parameters
        ----------
        star : SingleStar
            The star which properties are required
            to be matched with the single MIST-like grid.

        Returns
        -------
        list of 2 float values
            Contains the associated (in solar units) and the time (in years)
            such that the time-series in the grid matches
            the properties of the secondary.


Difference between radius and Roche lobe at a given time.

            Used to check if there is RLOF mass transfer during the detached
            binary evolution interpolation.

            Parameters
            ----------
            t : float
                Time of the evolution, in years.
            y : tuple of floats
                [separation, eccentricity] at that time. Separation should be
                in solar radii.

            Returns
            -------
            float
                Difference between stellar radius and Roche lobe radius in
                solar radii.


Difference between radius and Roche lobe at a given time.

            Used to check if there is RLOF mass transfer during the detached
            binary evolution interpolation.

            Parameters
            ----------
            t : float
                Time of the evolution, in years
            y : tuple of floats
                [separation, eccentricity] at that time. Separation should be
                in solar radii.

            Returns
            -------
            float
                Difference between stellar radius and Roche lobe radius in
                solar radii.


Relative difference between radius and Roche lobe.

            Used to check if there is RLOF mass transfer during the detached
            binary evolution interpolation.

            Parameters
            ----------
            t : float
                Time of the evolution, in years.
            y : tuple of floats
                [separation, eccentricity] at that time. Separation should be
                in solar radii.

            Returns
            -------
            float
                Relative difference between stellar radius and Roche lobe
                radius.


Return a helper function to set attributes for solve_ivp events.


Diff. equation describing the orbital evolution of a detached binary.

    The equation handles wind mass-loss [1]_, tidal [2]_, gravational [3]_
    effects and magnetic braking [4]_, [5]_, [6]_, [7]_, [8]_. It also handles
    the change of the secondary's stellar spin due to its change of moment of
    intertia and due to mass-loss from its spinning surface. It is assumed that
    the mass loss is fully non-conservative. Magnetic braking is fully applied
    to secondary stars with mass less than 1.3 Msun and fully off for stars
    with mass larger then 1.5 Msun. The effect of magnetic braking falls
    linearly for stars with mass between 1.3 Msun and 1.5 Msun.

    TODO: exaplin new features (e.g., double COs)

    Parameters
    ----------
    t : float
        The age of the system in years
    y : list of float
        Contains the separation, eccentricity and angular velocity, in Rsolar,
        dimensionless and rad/year units, respectively.
    M_pri : float
        Mass of the primary in Msolar units.
    M_sec : float
        Mass of the secondary in Msolar units.
    Mdot : float
        Rate of change of mass of the star in Msolar/year units.
        (Negative for wind mass loss.)
    R : float
        Radius of the star in Rsolar units.
    I : float
        Moment of inertia of the star in Msolar*Rsolar^2.
    tau_conv: float
        Convective turnover time of the star, calculated @
        0.5*pressure_scale_height above the bottom of the outer convection
        zone in yr.
    L : float
        Luminosity of the star in solar units.
    #mass_conv_core : float
    #    Convective core mass of the secondary in Msolar units.
    conv_mx1_top_r : float
        Coordinate of top convective mixing zone coordinate in Rsolar.
    conv_mx1_bot_r : float
        Coordinate of bottom convective mixing zone coordinate in Rsolar.
    surface_h1 : float
        surface mass Hydrogen abundance
    center_h1 : float
        center mass Hydrogen abundance
    M_env : float
        mass of the dominant convective region for tides above the core,
        in Msolar.
    DR_env : float
        thickness of the dominant convective region for tides above the core,
        in Rsolar.
    Renv_middle : float
        position of the dominant convective region for tides above the core,
        in Rsolar.
    Idot : float
        Rate of change of the moment of inertia of the star in
        Msolar*Rsolar^2 per year.
    do_wind_loss: Boolean
        If True, take into account change of separation due to mass loss from
        the secondary. Default: True.
    do_tides: Booleans
       If True, take into account change of separation, eccentricity and
       secondary spin due to tidal forces. Default: True.
    do_gravitational_radiation: Boolean
       If True, take into account change of separation and eccentricity due to
       gravitational wave radiation. Default: True
    do_magnetic_braking: Boolean
        If True, take into account change of star spin due to magnetic braking.
        Default: True.
    magnetic_braking_mode: String
        A string corresponding to the desired magnetic braking prescription.
            - RVJ83 : Rappaport, Verbunt, & Joss 1983 [4]_
            - M15 : Matt et al. 2015 [5]_
            - G18 : Garraffo et al. 2018 [6]_
            - CARB : Van & Ivanova 2019 [7]_
    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. Default: True.
    verbose : Boolean
        If we want to print stuff. Default: False.

    Returns
    -------
    list of float
        Contains the change of
        the separation, eccentricity and angular velocity, in Rsolar,
        dimensionless and rad/year units, respectively.

    References
    ----------
    .. [1] Tauris, T. M., & van den Heuvel, E. 2006,
           Compact stellar X-ray sources, 1, 623
    .. [2] Hut, P. 1981, A&A, 99, 126
    .. [3] Junker, W., & Schafer, G. 1992, MNRAS, 254, 146
    .. [4] Rappaport, S., Joss, P. C., & Verbunt, F. 1983, ApJ, 275, 713
    .. [5] Matt et al. 2015, ApJ, 799, L23
    .. [6] Garraffo et al. 2018, ApJ, 862, 90
    .. [7] Van & Ivanova 2019, ApJ, 886, L31
    .. [8] Gossage et al. 2021, ApJ, 912, 65


TODO: add description and reference for the equations.


Return a helper function to set attributes for `solve_ivp` events.


        Make assumptions about the core/total mass, and abundances of the star of a merged product.

        Similar to the table of merging in BSE

        star_base: Single Star
            is our base star that engulfs its companion. The merged star will have this star as a base
        comp: Single Star
            is the star that is engulfed


Format the Patton&Sukhbold,20 dataset for interpolation.

                    Parameters
                    ----------
                    file_name : str
                        Name of the dataset file.

                    Returns
                    -------
                    CO_core_params : arr
                        Array containing the carbon-oxygen core parameters
                        in a grid of abundance and mass as columns.
                    target_parameter : arr
                        Array with the corresponding value of the target
                        parameter giving the selected dataset.


Collapse the star object into a compact object.

        This routine supports three options:
        1. use_interp_values : True
           The outcome of core collpase was interpolated from a post processed
           MESA grid and stored in the star object in the mesa_step or
           detached_step (default). This option supports only default
           assumptions for all core collase mechanism.
        2. use_profiles : False
           Perfrome the core collpase given a MESA profile. To use this option
           a MESA profile must be stored in the star object which is provided
           by nearest neighbor interpolation in the mesa_step or (TODO)
           interpolated in the detached_step.
        3. use_core_masses : False
           This option uses the core masses at carbon depletion to determine
           the core collapse outcoume (classical population sythesis
           threatment).
        4. allow_spin_None : False
           This option does not determine the spin during core collapse while
           setting other values like in use_core_masses. (used to avoid jumps
           in the spin for interpolator training because of missing profiles)

        Parameters
        ----------
        star : object
            Star object containing the star properties.

        Returns
        -------
        m_rem : double
            Remnant mass of the compact object in M_sun. This quantity accounts
            for the mass loss thorugh neutrino.

        state : string
            New state of the star object.


Compute baryonic remnant mass for the PPISN and PISN prescription.

        Parameters
        ----------
        star : object
            Star object containing the star properties.

        Returns
        -------
        m_PISN : double
            Maximum stellar mass in M_sun after the PPISN/PISN prescription.


Get the remnant mass, fallback frac., state & SN type of the SN.


Compute supernova remnant barionic mass.

        We follow the selected electron-capture and core-collapse mechanisms
        to get the remnant baryonic mass.

        Parameters
        ----------
        star : object
            Star object containing the star properties.

        m_PISN : double
            Maximum stellar mass in M_sun after the PPISN/PISN prescription.

        Returns
        -------
        m_rembar : double
            Barioninc mass of the remnant after the supernova in M_sun. This
            quantity does NOT take into account any neutrino lost, this will be
            taken into account in collapse_star().
        f_fb : double
            Mass fraction falling back onto the compact object created in the
            supernova. The maximum value is 1 and means that all the barionic
            mass is collapsing to form the compact object.
        state : string
            Finall state of the stellar remnant after the supernova.


Do the orbital kick.

        This function computes the supernova step of the binary object [1]_,
        [2]_. It checks which binary_state reached the core collapse flag,
        either CC1 or CC2, and runs the step accordingly updating the binary
        object.

        Geometry:
        We work in a right-handed coordinate system. The collapsing helium star,
        here M_he_star, lies on the origin. The companion, here M_companion,
        lies on the negative X axis at rest. The relative velocity of the M_he_star
        with respect to M_companion lies in the X-Y plane, with vY>0.
        The orbital angular momentum vector is in Z direction, which completes the
        right-handed coordinate system.

        psi:
            The angle in the orbital plane between the X axis and the pre-core
            collapse relative velocity. (psi = pi/2 points in Y direction)

        theta :
            The polar angle between the kick velocity and the pre-core collapse
            relative velocity of the M_he_star with respect to M_companion.

        phi :
            The corresponding azimuthal angle such that phi=0 is on the Z axis.

        tilt :
            The angle between pre- and post- supernova orbital angular momentum vectors

        Parameters
        ----------
        binary : object
            Binary object containing the binary properties and the two star
            objects.

        References
        ----------
        .. [1] Kalogera, V. 1996, ApJ, 471, 352

        .. [2] Wong, T.-W., Valsecchi, F., Fragos, T., & Kalogera, V. 2012, ApJ, 747, 111


Check that the binary is not disrupted [1]_, [2]_.

                Parameters
                ----------
                M_he_star : double
                    Helium star mass before the SN in g.
                M_companion : double
                    Companion star mass in g.
                M_compact_object : double
                    Compact object mass left  by the SN in g.
                rpre : double
                    Oribtal separation at the time of the exlosion in cm. If the
                    eccentricity pre SN is 0 this correpond to Apre.
                Apost : double
                    Orbital separtion after the SN in cm.
                epost : double
                    Eccentricity after the SN.
                Vr : double
                    Velocity of pre-SN He core relative to M_companion, directed
                    along the positive y axis in cm/s.
                Vkick : double
                    Kick velocity in cm/s.
                cos_theta : double
                    The cosine of the angle between pre- & post-SN orbital planes.

                Returns
                -------
                flag_binary : bool
                    flag_binary is True if the binary is not disrupted.

                References
                ----------
                .. [1] Willems, B., Henninger, M., Levin, T., et al. 2005, ApJ, 625, 324
                .. [2] Kalogera, V. & Lorimer, D.R. 2000, ApJ, 530, 890


Draw a kick from a Maxwellian distribution.

        We follow Hobbs G., Lorimer D. R., Lyne A. G., Kramer M., 2005, MNRAS, 360, 974
        and choose sigma = 265 km/s

        We rescale the kicks by 1 - f_fb as in Eq. 21 of Fryer, C. L., Belczynski, K., Wiktorowicz,
        G., Dominik, M., Kalogera, V., & Holz, D. E. (2012), ApJ, 749(1), 91.

        Parameters
        ----------
        star : object
            Star object containing the star properties.

        Returns
        -------
        Vkick : double
            Natal orbital kick in km/s.


Compute supernova final remnant mass and fallback fraction.

        It uses the results from [1]_. The prediction for the core-collapse
        outcome is performed using the C core mass and its C abundance.
        The criterion by [2]_ is used to determine the final outcome.

        Parameters
        ----------
            star : obj
                Star object of a collapsing star containing the MESA profile.

        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.

        References
        ----------
        .. [1] Patton, R. A., & Sukhbold, T. (2020). MNRAS, 499(2), 2803-2816.

        .. [2] Ertl, T., Janka, H. T., Woosley, S. E., Sukhbold, T., & Ugliano,
            M. (2016). ApJ, 818(2), 124.


Check if the SN type matches the stellar state of the given star.

    Parameters
    ----------
    SN_type : str
        SN type of the star.
    state : str
        Stellar state of the star.

    Returns
    -------
    correct_SN_type : bool
        True if the SN type matches the stellar state of the star.


Compute the BH innermost stable circular orbit (ISCO) parameters.

    Parameters
    ----------
    a : float
        Dimnesionless BH spin.
    m_BH : float
        Mass of the BH in g.

    Returns
    -------
    r_isco : float
        Radius of the ISCO in CGS units (cm).
    j_isco : float
        Specific angular momentum at ISCO in CGS units (cm^2/s).
    efficiency : float
        Orbital energy efficiency at ISCO.


Do the core collapse of a star object with MESA profile provided.

    Parameters
    ----------
    star : object
        Star object of a collapsing star containing the MESA profile.
    mass_collapsing : float
        Remnant barionic mass in M_sun collapsing to form the BH. This is the
        mass left to collapse after applying a supernova prescriptions,
        see e.g. rapid and delayed mechanisms of Fryer et al. (2012).
    mass_central_BH : float
        Mass of the central stellar layers (in M_sun) collasping directly to
        form a proto BH.
    neutrino_mass_loss : float
        Mass (in M_sun) lost thorugh neutrinos in the formation of the central
        BH.
    max_neutrino_mass_loss : float
        Maximum mass (in M_sun) lost thorugh neutrinos.
    verbose : bool
        If `True`, it prints some informations.

    Returns
    -------
    core_collapse_results : dict
        A dictionary containing the following keys:
        'M_BH_total' : float
            The mass of the final BH in M_sun.
        'a_BH_total' : float
            The dimensionless spin of the final BH.
        'm_disk_accreted' : float
            The mass of the disk accreted by the BH in M_sun.
        'm_disk_radiated' : float
            The mass of the disk radiated away in M_sun.
        'BZ_jet_power_total' : float
            The total Blandford-Znajek jet power in erg/s.

        # Additional keys that are not used in the current implementation:
        # 'BZ_jet_power_array' : np.array(BZ_jet_power_array),
        #       Blandford-Znajek jet power at each shell collapse in erg/s
        # 'M_BH_array' : np.array(M_BH_array)
        #       BH mass evolution in g
        # 'a_BH_array': np.array(a_BH_array)
        #       Dimensionless spin evolution
        # 'J_accreted_array': np.array(J_accreted_array)
        #       Angular momentum accreted from a given shell by the BH in CGS units.
        # 'J_total_array': np.array(J_total_array)
        #       Total angular momentum in accreted shells + BH's initial J
        # 'J_disk_shell_array': np.array(J_disk_shell_array)
        #       Angular momentum accreted from the shell's part collapsing to form a
        #       disk in CGS units.
        # 'radiation_eff_array': np.array(radiation_eff_array)
        #       Fraction of accretion disk radiated away, this is one minus accretion
        #       efficiency.
        # 'r_isco_array': np.array(r_isco_array)
        #       Radius of the innermost stable circular orbit in cm.
        # 'j_isco_array': np.array(j_isco_array)
        #       Specific angular momentum at ISCO (prograde orbits) in CGS.
        # 'M_direct_collapse_array': np.array(M_direct_collapse_array)
        #       Cumulative mass accreted through direct collapse in g.
        # 'M_disk_array': np.array(M_disk_array)
        #       Cumulative mass accreted through the disk in g.
        # 'dm_direct_array': np.array(dm_direct_array)
        #       Mass in shell with j < j_isco (direct collapse) in g
        # 'dm_disk_array': np.array(dm_disk_array)
        #       Mass in shell with j > j_isco (forms a disk) in g
        # 'j_shell_array': np.array(j_shell_array)
        #       Shell's specific angular momentum in CGS
        # 'M_total_array': np.array(M_total_array)
        #       Integrated mass (shells + initial BH) in g
        # 'a_star_array': np.array(a_star_array)
        #       Star's spin parameter
        # 'max_he_mass_ejected': max_he_mass_ejected
        #       Max He mass that can be ejected during the disk formation


Compute the Blandford-Znajek jet power.

    This function computes the Blandford-Znajek jet power given the mass
    accretion, the efficiency factor for the magnetic flux, and the
    efficiency factor for the BH spin.
    This is based on the decomposition of the jet power in terms of the
    magnetic flux and the BH spin, see Gottlieb et al. (2023, 2024).
    We do not assume any disk state in this calculation, i.e.
    magnetically arrested disk (MAD), Neutrino dominated accretion flow (NDAF),
    or advection dominated accretion flow (ADAF).
    However, the functions for eta_phi and eta_a can be dependent on the disk
    type. Moreover, the efficiency factors are not constant and
    can change with the magnetic field and BH spin.

    Parameters
    ----------
    M_dot : float
        Mass accretion rate in g.
    eta_phi : float
        Efficiency factor for the magnetic flux.
    eta_a : float
        Efficiency factor for the BH spin.

    Returns
    -------
    P_jet : float
        Blandford-Znajek jet power in erg.


Infer the grid boundaries (min/max of masses and orbital period).


Load the interpolator that has been trained on the grid.


Take the step by calling the appropriate interpolator.


Check if the type of the star is supported.


Update properites according to nearest neighbour interpolation.

        Parameters
        ----------
        star_1_CO : bool
            `True` if star_1 is a compact object.
        star_2_CO : bool
            `True` if star_2 is a compact object.
        track_interpolation : bool
            If True, uses track interpolation over initial-final interpolation


Update the binary through initial-final interpolation.


Update the binary event if max time has been exceeded.


Linear interpolation in time between two points.

        Parameters
        ----------
        t : type
            Description of parameter `t`.
        t_before : type
            Description of parameter `t_before`.
        t_after : type
            Description of parameter `t_after`.
        v_before : type
            Description of parameter `v_before`.
        v_after : type
            Description of parameter `v_after`.

        Returns
        -------
        type
            Description of returned object.


Calculate lambda_CE from an assumed constant value or from profile.

        If lambda_CE is calculated from donor's profile, we also pass a more
        accurate calculation of the donor core mass for the purposes of CEE.

        Parameters
        ----------
        donor : instance of SingleStar
            The donor star to calculate pre-CE quantities.
        verbose : bool
            In case we want information about the CEE  (the default is False).

        Returns
        -------
        lambda_CE: float
            lambda_CE calculated either as an assumed constant value or
            calculated from profile
        mc1_i: float
            If lambda_CE is calculated from donor's profile, we also pass a
            more accurate calculation of the donor core mass for the purposes
            of CEE.
        rc1_i: float
            The radius of the donor's core


Calculate the post-common-envelope core masses and radii.

        It determines the post-CE parameters based on the core properties.
        Note that these parameters may be updated in a subsequent step
        depending on assumptions about whether and how the final layers
        of the CE are removed from the cores.

        Parameters
        ----------
        donor : SingleStar object
            The donor star
        mc1_i : float
            Core mass of the donor after the fast CE phase (in Msun)
        rc1_i : float
            Core radius of the donor after the fast CE phase (in Rsun)
        donor_type : string
            String dictating whether the donor has a 'He_core' or 'CO_core'
        comp_star : SingleStar object
            The companion star
        mc2_i : float
            Core mass of the companion after the fast CE phase (in Msun)
        rc2_i : float
            Core radius of the companion after the fast CE phase (in Rsun)
        comp_type : string
            String dictating whether the companion has a 'He_core', 'CO_core',
            or 'not_giant_companion' (e.g. a compact object or MS star).
        double_CE : bool
            In case we have a double CE situation.
        verbose : bool
            In case we want information about the CEE.

        Returns
        -------
        m1c_f: float
            Donor mass after the complete CE (in Msun)
        r1c_f: float
            Donor radius after the complete CE (in Rsun)
        m2c_f: float
            Companion mass after the complete CE (in Msun)
        r2c_f: float
            Companion radius after the complete CE (in Rsun)


Calculate the post-common-envelope parameters upon exiting a CEE.

        This prescription assumes the he_core_mass/radius (or
        co_core_mass/radius for CEE of stripped_He*) are not further stripped
        beyond the core defined given by the core_definition_H/He_fraction.
        Hence, there are no changes on the orbit after successful ejection.
        Instead it is assumed that the defined core will become the remaining
        stripped object with core abundances at its surface.

        Parameters
        ----------
        donor : SingleStar object
            The donor star
        mc1_i : float
            Core mass of the donor after the fast CE phase (in Msun)
        rc1_i : float
            Core radius of the donor after the fast CE phase (in Rsun)
        comp_star : SingleStar object
            The companion star
        mc2_i : float
            Core mass of the companion after the fast CE phase (in Msun)
        rc2_i : float
            Core radius of the companion after the fast CE phase (in Rsun)
        separation_postCEE : float
            Binary's separation after the fast CE phase (in cm)
        verbose : bool
            In case we want information about the CEE.

        Returns
        -------
        m1c_f: float
            Donor mass after the complete CE (in Msun)
        r1c_f: float
            Donor radius after the complete CE (in Rsun)
        m2c_f: float
            Companion mass after the complete CE (in Msun)
        r2c_f: float
            Companion radius after the complete CE (in Rsun)
        separation_f : float
            Binary's final separation upon exiting the CE (in Rsun)
        orbital_period_f : float
            Binary's final orbital period upon exiting the CE (in days)
        merger : bool
            Whether the binary merged in the CE


Calculate the post-common-envelope parameters upon exiting a CEE.

        This prescription assumes the he_core_mass/radius (or
        co_core_mass/radius for CEE of stripped_He*) becomes the value
        determined by MESA pre CEE. It stripes the envelope between the core
        defined by the core_definition_H/He_fraction and the MESA core by
        assuming an instantaneous stable MT phase (non-conservative, with mass
        lost from the accretor) after the successful ejection of the outer
        envelope part lost during the fast CE phase.

        Parameters
        ----------
        donor : SingleStar object
            The donor star
        mc1_i : float
            Core mass of the donor after the fast CE phase (in Msun)
        rc1_i : float
            Core radius of the donor after the fast CE phase (in Rsun)
        comp_star : SingleStar object
            The companion star
        mc2_i : float
            Core mass of the companion after the fast CE phase (in Msun)
        rc2_i : float
            Core radius of the companion after the fast CE phase (in Rsun)
        separation_postCEE : float
            Binary's separation after the fast CE phase (in cm)
        verbose : bool
            In case we want information about the CEE.

        Returns
        -------
        m1c_f: float
            Donor mass after the complete CE (in Msun)
        r1c_f: float
            Donor radius after the complete CE (in Rsun)
        m2c_f: float
            Companion mass after the complete CE (in Msun)
        r2c_f: float
            Companion radius after the complete CE (in Rsun)
        separation_f : float
            Binary's final separation upon exiting the CE (in Rsun)
        orbital_period_f : float
            Binary's final orbital period upon exiting the CE (in days)
        merger : bool
            Whether the binary merged in the CE


Calculate the post-common-envelope parameters upon exiting a CEE.

        This prescription assumes the he_core_mass/radius (or
        co_core_mass/radius for CEE of stripped_He*) becomes the value
        determined by MESA pre CEE. It stripes the envelope between the core
        defined by the core_definition_H/He_fraction and the MESA core by
        assuming an instantaneous wind loss phase from the donor (or both
        components in case of a double CE) after the successful ejection of the
        outer envelope part lost during the fast CE phase.

        Parameters
        ----------
        donor : SingleStar object
            The donor star
        mc1_i : float
            Core mass of the donor after the fast CE phase (in Msun)
        rc1_i : float
            Core radius of the donor after the fast CE phase (in Rsun)
        comp_star : SingleStar object
            The companion star
        mc2_i : float
            Core mass of the companion after the fast CE phase (in Msun)
        rc2_i : float
            Core radius of the companion after the fast CE phase (in Rsun)
        separation_postCEE : float
            Binary's separation after the fast CE phase (in cm)
        verbose : bool
            In case we want information about the CEE.

        Returns
        -------
        m1c_f: float
            Donor mass after the complete CE (in Msun)
        r1c_f: float
            Donor radius after the complete CE (in Rsun)
        m2c_f: float
            Companion mass after the complete CE (in Msun)
        r2c_f: float
            Companion radius after the complete CE (in Rsun)
        separation_f : float
            Binary's final separation upon exiting the CE (in Rsun)
        orbital_period_f : float
            Binary's final orbital period upon exiting the CE (in days)
        merger : bool
            Whether the binary merged in the CE


Apply the alpha-lambda common-envelope prescription.

        It uses energetics to calculate the shrinakge of the orbit
        (and possible merger) of the two components, as well as upadate
        their new masses, during a common-envelope phase.

        Parameters
        ----------
        binary : BinaryStar object
            Instance of the binary to evolve.
        donor : SingleStar object
            The donor star
        comp_star : SingleStar object
            The companion star
        lambda1_CE : float
            Lambda previously calculated for the donor's envelope
            binding energy.
        mc1_i : float
            core mass of the donor
        rc1_i : float
            core radius of the donor
        donor_type : string
            String dictating whether the donor has a H-envelope or He-envelope
        lambda2_CE : float
            Lambda previously calculated for the companion's envelope
            binding energy.
        mc2_i : float
            core mass of the companion
        rc2_i : float
            core radius of the companion
        comp_type : string
            String dictating whether the companion has a
            H-envelope or He-envelope.
        double_CE : bool
            In case we have a double CE situation.
        verbose : bool
            In case we want information about the CEE.
        common_envelope_option_after_succ_CEE: str
            Options are:

            1) "one_phase_variable_core_definition"
                he_core_mass/radius (or co_core_mass/radius for CEE of
                stripped_He*) are replaced according to the new core boundary
                used for CEE (based on core_definition_H/He_fraction) but no
                other change in period after succesful ejection at
                alpha-lambda prescription.
            2) "two_phases_stableMT"
                he_core_mass/radius (or co_core_mass/radius for CEE of
                stripped_He*) staying as preCEE and after succesful ejection at
                alpha-lambda prescription, we assume an instantaneous stableMT
                phase (non-conservative, with mass lost from accretor) from the
                donor (or from donor and simultaneously the accretor at
                double_CE), taking away the extra "core" mass as defined by the
                core boundary used for CEE (based on
                core_definition_H/He_fraction).
            3) "two_phases_windloss"
                he_core_mass/radius (or co_core_mass/radius for CEE of
                stripped_He*) staying as preCEE and after succesful ejection
                at alpha-lambda prescription, we assume a instantaneous
                windloss phase from the donor (or from donor and simultaneously
                the accretor at double_CE), taking away the extra "core" mass
                as defined by the core boundary used for CEE (based on
                core_definition_H/He_fraction).
        core_definition_H_fraction: float
            The value of the H abundance to define the envelope-core boundary
            in He_cores.
        core_definition_He_fraction: float
            The value of the He abundance to define the envelope-core boundary
            in CO_cores.
        mass_loss_during_CEE_merged: Boolean
             If False, then no mass loss from this step for a merged CEE
             If True, then we remove mass according to the alpha-lambda prescription
              assuming a final separation where the inner core(s) RLOF starts, and the same lambda(s)


Update the binary and component stars upon exiting a CEE.

        The binary's parameters (orbital period, separation, state, etc.) are
        updated along with the donor's (and in the case of a double CE the
        companion's) parameters as well. Note that certain parameters are set
        to np.nan if they are undetermined after the CE.

        Parameters
        ----------
        binary: BinaryStar object
            The binary system
        donor : SingleStar object
            The donor star
        mc1_f : float
            Final core mass of the donor (in Msun)
        rc1_f : float
            Final core radius of the donor (in Rsun)
        donor_type : string
            Descriptor for the stellar type of the donor's core
        comp_star : SingleStar object
            The companion star
        mc2_f : float
            Final core mass of the companion (in Msun)
        rc2_f : float
            Final core radius of the companion (in Rsun)
        comp_type : string
            Descriptor for the stellar type of the companion or it's core
        double_CE : bool
            Whether the CEE is a double CE or not
        separation_f : float
            Final binary separation upon exiting the CEE (in Rsun)
        orbital_period_f : float
            Final orbital period upon exiting the CEE (in days)
        common_envelope_option_after_succ_CEE : string
            Which type of post-common envelope evolution is used to remove
            the final layers around the core
        core_definition_H_fraction : float
            The fractional abundance of H defining the He core (0.3, 0.1, or
            0.01)
        core_definition_He_fraction : float
            The fractional abundance of He defining the CO core (typically 0.1)
        verbose : bool
            In case we want information about the CEE.


 Calculate the amount of mass lost during a stellar merger in a CEE

        From the stellar profiles the mass ejected until merger is calculated.
        Note that this function only returns non-zero mass-loss values if a
        profile is available.

        Parameters
        ----------
        donor : SingleStar object
            The donor star
        m1_i : float
            Initial mass of the donor (in Msun)
        mc1_i : float
            Initial core mass of the donor (in Msun)
        rc1_i : float
            Initial core radius of the donor (in Rsun)
        comp_star : SingleStar object
            The companion star
        m2_i : float
            Initial mass of the companion (in Msun)
        mc2_i : float
            Initial core mass of the companion (in Msun)
        rc2_i : float
            Initial core radius of the companion (in Rsun)
        separation_i : float
            Initial separation of the binary (in cm)
        alpha_CE : float
            Common envelope efficiency parameter (unitless)
        radius1 : float
            Initial radius of the donor (in Rsun)
        radius2 : float
            Initial radius of the companion (in Rsun)
        double_CE : bool
            Whether the CEE is a double CE or not
        verbose : bool
            In case we want information about the CEE.

        Returns
        -------
        Mejected_donor : float
            Mass ejected from the donor (in Msun)
        Mejected_comp : float
            Mass ejected from the companion (in Msun)