    Concat duplicated western edge data along eastern edge and flipped data along tripole seam
    to avoid gaps in plots.
    Assumes the last dimension of d is x and second-last is y.

    d: xarray.DataArray or numpy.MaskedArray (or numpy.Array - UNTESTED!)

    lon: boolean indicating whether this is longitude data in degrees
        (in which case 360 is added to duplicated eastern edge).
        Ignored if d is a DataArray.

    tripole_flip: boolean indicating whether to reverse duplicated data on tripole seam.
        You'd normally only do this with coord data.
        Ignored if d is a DataArray.

    Returned array shape has final 2 dimensions increased by 1.


Simplify cache orchestration.

    Parameters
    ----------
    tag: str
        Normally every function call the cache with their own tag.
        We sugest "module.function" or "module.Class.function"

    function: callable
        The function to be cached

    force: bool (default=False)
        If the vale of the cache must be ignored and re-execute the
        function.

    cache_expire: bool or None
        Time in seconds to expire the function call

    args and kwargs:
        All the parameters needed to execute the function.

    Returns
    -------
    The result of calling the function or the cached version of the same value.


Return the internal cache of the client the internal cache.


Access the remote index of the Carpyncho-Dataset.

        The index is stored internally for 1 hr.

        Parameters
        ----------
        reset: bool
            If its True the entire cache is ignored and a new index is
            donwloaded and cached.

        Returns
        -------
        dict with the index structure.


Retrieve the available catalogs for a given tile.

        Parameters
        ----------
        tile: str
            The name of the tile to retrieve the catalogs.

        Returns
        -------
        tuple of str:
            The names of available catalogs in the given tile.

        Raises
        ------
        ValueError:
            If the tile is not found.


Check if a given catalog and tile exists.

        Parameters
        ----------
        tile: str
            The name of the tile.
        catalog:
            The name of the catalog.

        Returns
        -------
        bool:
            True if the convination tile+catalog exists.


Retrieve the information about a given catalog.

        Parameters
        ----------
        tile: str
            The name of the tile.
        catalog:
            The name of the catalog.

        Returns
        -------
        dict:
            The entire information of the given catalog file. This include
            url, md5 checksum, size in bytes, number of total records,
            etc.

        Raises
        ------
        ValueError:
            If the tile or the catalog is not found.


Show available tiles.


Show the available catalogs for a given tile.


Check if a given catalog and tile exists.


Retrieve the information about a given catalog.


Retrives a catalog from th Carpyncho dataset collection.

        tile:
            The name of the tile.
        catalog:
            The name of the catalog.
        out:
            The location to store the catalog.
        force:
            Download a new version of the catalog even if it already exists in
            the cache.


Apply the PSFTransform to an image.

        Parameters
        ----------
        image : np.ndarray
            image to apply the transform to
        workers: int | None
            Maximum number of workers to use for parallel computation of FFT.
            If negative, the value wraps around from os.cpu_count(). See scipy.fft.fft for more details.
        pad_mode: str
            how to pad the image when computing ffts, see np.pad for more details.
        saturation_threshold: float
            pixels brighter than this threshold are filled with their neighborhood average before PSF correction
            and then refilled with the raw value after correction to avoid producing artifacts
        saturation_dilation: int
            a nonnegative number of times to morphologically dilate the saturation mask before application
        neighborhood_width: int
            an odd positive number indicating the size of the neighborhood used for filling saturated pixels
        Returns
        -------
        np.ndarray
            image with psf transformed


Get the slice objects for a coordinate patch in the padded cube.


Visualize the transfer kernels.


Save a PSFTransform to a file. Supports h5 and FITS.

        Parameters
        ----------
        path : pathlib.Path
            where to save the PSFTransform

        Returns
        -------
        None


Load a PSFTransform object. Supports h5 and FITS.

        Parameters
        ----------
        path : pathlib.Path
            file to load the PSFTransform from

        Returns
        -------
        PSFTransform


Convert FunctionalPSF to an ArrayPSF.


Decorate a SimpleFunctionalPSF.


Decorate to create a VariedFunctionalPSF.


Save the PSF model to a file. Supports h5 and FITS.

        Parameters
        ----------
        path : pathlib.Path
            where to save the PSF model

        Returns
        -------
        None


Load the PSF model from a file. Supports h5 and FITS.

        Parameters
        ----------
        path : pathlib.Path
            where to load the PSF model from

        Returns
        -------
        ArrayPSF
            loaded model


Visualize the PSF model.


Visualize the fft of the PSF.


Build the PSF model.

        Parameters
        ----------
        images :  list[pathlib.Path] | np.ndarray | Generator
            images to use

        Returns
        -------
        (ArrayPSF, dict)
            an array PSF and the counts of stars in each component


Visualize the number of stars identified within each patch.

    Parameters
    ----------
    counts : dict[tuple[int, int], int]
        The counts returned by an ArrayPSFBuilder.build
    ax : matplotlib.axes.Axes
        An Axes object on which to plot. If not provided, a new Figure will be
        generated.
    label_pixel_bounds : bool
        If True, the axes of the plot will be labeled with the pixel range
        spanned by each patch.


Determine the grid of overlapping neighborhood patches.

    Parameters
    ----------
    image_shape : tuple of 2 ints
        shape of the image we plan to correct
    size : int
        size of the square patches we want to create

    Returns
    -------
    np.ndarray
        an array of shape Nx2 where return[:, 0]
        are the x coordinate and return[:, 1] are the y coordinates


Retrieve coordinates the transfer kernel is defined on.

        Returns
        -------
        list[tuple[int, int]]
            coordinates the transfer kernel is defined on.


 Make a square gaussian kernel.

    size is the length of a side of the square
    fwhm is full-width-half-maximum, which
    can be thought of as an effective radius.


Confirms that the covering fully covers the image four times, i.e. each point is sample four times.


        Download the dataset into file system
        :param destPath: use the current directory as default
        :return:


        A subtag will be added if it has a value
        :param topTag: a tag that will contain subtags to be added
        :param list: list of tag names that will be added
        :param data: value of the subtag
        :return: tag containing subtags


        :param data: boolean type
        :return: CMR specific notation for a boolean


        This function is to remove the non value from the tag
        :param parentTag: Top level tag
        :param subTagName: subtags ot tag children
        :param tagValue: the value of the tag
        :return:


        :param data: a dictionary of the data you want to ingest to CMR
        :return: XML data according to CMR format


        Search the CMR granules
        :param limit: limit of the number of results
        :param kwargs: search parameters
        :return: list of results (<Instance of Result>)


            Search the CMR granules

            :param limit: limit of the number of results
            :param kwargs: search parameters
            :return: list of results (<Instance of Result>)


        Search the CMR collections
        :param limit: limit of the number of results
        :param kwargs: search parameters
        :return: list of results (<Instance of Result>)


        purpose: check if the token has been expired
        :return: True if the token has been expired; False otherwise.


        Purpose : a private function to parse the xml file and returns the dataset ID
        :param pathToXMLFile:
        :return:  the dataset id


        Purpose : a private function to parse the xml file and returns the datasetShortName
        :param pathToXMLFile:
        :return:  the datasetShortName


            Purpose : a private function to parse the xml file and returns the datasetShortName
            :param pathToXMLFile:
            :return:  the datasetShortName


        :purpose : ingest the collections using cmr rest api
        :param XMLData: a parameter that holds the XML data that needs to be ingested it can be a file
        :return: the ingest collection request if it is successfully validated


        Delete an existing colection
        :param dataset_id: the collection id
        :return: response content of the deletion request


        :purpose : ingest granules using cmr rest api
        :XMLData XML data to engist to cmr:
        :return: the ingest granules request if it is successfully validated


        :purpose Convert json format to XML format
        :param data: Json data
        :return: XML data


        :purpose : ingest granules using cmr rest api
        :param pathToTextFile: a comma seperated values text file

        :return: logs of the requests and the overall successful ingestions


        :purpose : To validate the colection before the actual ingest
        :param data: the collection data
        :param dataset_id:
        :return: the request to validate the ingest of the collection


        purpose : Requesting a new token
        :return: the new token


        :param granule_ur: The granule name
        :return: the content of the deletion request


        Get the public IP address of the machine running the program
        (used to request ECHO token)
        :return: machine's public IP


Read all text from the XML file


        replacing the expired token by a new one in the config file
        :return:


Create a new request session for the CMR object


    Duplicate console output to specified log file. Both stdout
    and stderr of this process and all children should be included.


    Detect panoramas (bag files and associated SciCam images). Return
    pano metadata.


    Write pano metadata to a YAML file, to be used as a configfile for
    snakemake.


Add new_meta to the existing pano metadata in the YAML file.


Set up the parser and parse the args.


If some command arguments have spaces, quote them. Then concatenate the results.


Run a command and write the output to a file. In verbose mode also print to screen.


Invoke the geometry_mapper tool to compute needed camera poses and clouds.


Invoke the voxblox batch_tsdf tool to fuse the depth images.


Merge individual reconstructions from previous invocations of this tool.


    Given two locations of labels, return true if the two labels are considered "duplicates" based
    specified limit.

    @param p1       array representing 3D position of label
    @param p2       array representing 3D position of label
    @param limit    max distance to be considered same location


    @param rect1    2D array representing rectangle (upper left and lower right coordinates)
    @param rect2    2D array representing rectangle (upper left and lower right coordinates)
    @returns        true if rect1 and rect2 overlap


    @param img      array of image
    @param startx   start x pixel
    @param starty   start y pixel
    @param endx     end x pixel
    @param endy     end y pixel
    @returns a cropped image of img[startx:endx, starty:endy]


        Generates a pandas dataframe from csv file with columns 'label', 'location' (location in image), 'image' (path to image),
        'PCL Intersection', and 'Mesh Intersection' to be used to find labels.

        @param file_path    path to csv file
        @returns dataframe  pandas dataframe with all the information from csv file


        @param image_folder     folder containing images to parse
        @param result_folder    if not None, folder to store resulting files
        @param increment        if True, stores the resulting files for each file in folder
        @param final_file       if None, creates a csv file to store parsed labels. If not None, adds to file provided.
        @returns                pandas dataframe with all the labels and info parsed from images in specified folder


        @param image_file       path to image to parse for text
        @param result_folder    if not None, folder to store resulting files
        @param increment        if True, stores the resulting files for each file in folder
        @returns                pandas dataframe with all the labels and info parsed from images in specified image file


@returns parseq models for OCR


@returns craft models for OCR


        Given an image, return the bag the image is from.

        @param img_file     the path to the ISS image
        @returns string     the name of the bag file the image originated from


        Given the string of the output from find_point_coordinate, returns a dictionary of the values.

        @param string           output from find_point_coordinate
        @returns dictionary     parsed values from the string output


        @param image_path       path to image to parse
        @param result_folder    if provided will save the dataframe as a csv file to the folder
        @param all_locations    set to contain all the locations of labels found
        @param final_file       if provided will save all the labels and their corresponding info to the csv file
        @param increment        if true, will save the image with all the labels boxed and marked to result folder


        @param data         dictionary for all the parameters to be passed into find_point_coordinate
        @param new_location 2D list representing location of the label in the image (pixels)
        @param ros_command  list representing ros command used to call find_point_coordinate


        Given parameters will save the labels and the corresponding info (pixel boundary box and 3D locations) from image_df to dataframe.

        @param image_df         pandas dataframe that stores all the labels found for specific image
        @param data             dictionary for all the parameters to be passed into find_point_coordinate
        @param ros_command      list representing ros command used to call find_point_coordinate
        @param all_locations    set to contain all the locations of labels found
        @param result_path      location to save all the found labels for specific image as csv file
        @param final_file       file that saves all the labels found for numerous images
        @param image_path       path to image
        @param increment        if true, will save the labels found to a csv file


        @param image        openCV array of image
        @param df           pandas dataframe of columns "label" and "location" where "location" is the upper left
                            and lower right points of the rectangular bounding box for the corresponding label
        @param result_path  if provided will save the labeled image to the result folder.
        @returns array of image with the labels and boundary boxes displayed


        Returns true is label and input_label are similar.

        @param label        string
        @param input_label  string
        @returns true if label and input_label is within a similarity threshold


        Search for specified label and if display_img is true, create an interactive graph for Jupyter Notebook
        display.

        @param label        string to search for in dataframe
        @param display_img  if True, display images with label boxed and cropped.
        @param jupyter      True if program is ran in Jupyter Notebook (necessary for interactive display)
        @throws error       if display_img is True, but the image path specified in the dataframe does not exist.


this function gets called if we hit the left button


        @param image_file   path to image currently being searched
        @param df           dataframe for all labels in specified image
        @param label        label to be searched
        @param display_img  if True, display images with label boxed and cropped.
        @returns            images array that holds images file paths for each rectangle.
                            rects array that holds rectangle positions of each label
                            results array that holds the 3D location of the labels in the panorama/ISS
                            if display_img is False, full and crop will always be empty.
        @throws error       if display_img is True, but the image path specified in the dataframe does not exist.


    plot a sphere surface
    Input:
        c: 3 elements list, sphere center
        r: 3 element list, sphere original scale in each axis ( allowing to draw elipsoids)
        subdiv: scalar, number of subdivisions (subdivision^2 points sampled on the surface)
        ax: optional pyplot axis object to plot the sphere in.
        sigma_multiplier: sphere additional scale (choosing an std value when plotting gaussians)
    Output:
        ax: pyplot axis object


    plots points and their corresponding gmm model in 3D
    Input:
        points: N X 3, sampled points
        w: n_gaussians, gmm weights
        mu: 3 X n_gaussians, gmm means
        stdev: 3 X n_gaussians, gmm standard deviation (assuming diagonal covariance matrix)
    Output:
        None


Optimize the cost-distance (weight-distance) flow between the
        two GMMs and use the optimized distance as the EMD distance metric.


Find the Earth Mover's Distance between two GMMs


Find the Gaussian in Theta that contributes the
    highest degree of positive change (i.e., removal results
    in the lowest EMD) and return "best" Theta GMM from which such
    Gaussian has been removed


Greedily remove Gaussians that contribute the most change
    and place them into a tertiary "change" GMM


Flag those c++11 features that we only allow in certain places.

    Args:
      filename: The name of the current file.
      clean_lines: A CleansedLines instance containing the file.
      linenum: The number of the line to check.
      error: The function to call with any errors found.


        If action is invalid in `sim_state`, return the reason why. If valid, return an empty
        string. The default implementation always returns an empty string. Derived classes can
        override as needed.


Return True if the action can be executed in `sim_state`.


        Modify `sim_state` as needed at the beginning of action execution. Derived classes that
        need to extend start() should typically invoke the parent method.


        Modify `sim_state` as needed at the end of action execution. Derived classes that need to
        extend end() should typically invoke the parent method.


Apply the action, modifying `sim_state`.


        Warp the simulation forward in time to the next queued event and apply its event callback.
        AKA "wait for something to happen".


Return True if this action has been completed in `sim_state`.


Advance robot goal indices past completed goals.


        Return True if `robot` can't execute `action` because a goal in `higher_priority_goals`
        vetoes it.


Apply chosen next action for one robot and update all robot execution states as needed.


Try to apply each robot's next action if it is idle.


Achieve all goals in the multi-robot system.


Return True if the robot is already in the desired region in `exec_state`.


Return `trace` formatted in the standard PDDL plan output format used by POPF.


    Return the result of parsing the file at `input_path` as a LISP S-expression (encompasses
    PDDL domains and problem instances).


Primary driver function for custom planning.


Parse command-line arguments and invoke survey_planner().


The main function that answers a query.


Parse arguments and invoke pddl_query().


Return the first non-zero between `a` and `b`, or zero if both are zero.


    Return path to abbreviated version of `pano_path`. Generate the abbreviated version if it
    doesn't already exist.


Return the YAML parse result for the file at `yaml_path`.


    Return a YamlMapping representation of `action`. This is the only place
    we really need domain-specific logic.


    Return the result of converting `goal` from a YAML object with named fields to a PDDL goal
    predicate, looking up info in `config` as needed.


    Return `lines` joined with carriage returns, prepending `indent` spaces to each line after the
    first.


    Returns consecutive pairs drawn from `elts`. Back-port itertools.pairwise() to earlier Python
    versions.


    Given `elts` an iterable of 2-tuples, return a new iterable that includes each 2-tuple twice,
    once in its original order and once reversed.


Return distinct pairs of items drawn from `elts`.


Return object instance declarations in PDDL format.


The main function that generates the problem.


Parse arguments and invoke problem_generator().


Return a YamlMapping representation of `plan_action`.


Return a list of PlanActions read from the PDDL plan at `plan_path`.


Save plan `yaml_actions` to `output_path` in YAML format.


Save a plot image of plan `yaml_actions` to `plot_path`.


    The main function that interprets an entire plan file.

    However, if you are receiving one action at a time from an executor, you may prefer to import
    this module and call yaml_action_from_pddl() directly.


Parse arguments and invoke plan_interpreter().


Wrapper for subprocess.run() that supplies default encoding and logs each command.


    Wait until `path` exists for up to `timeout_seconds`. Poll for existence every
    'check_period_seconds`. Raise TmuxTimeoutError on timeout.


The main driver function.


Parse command line arguments and call tmux_inject() main driver.


Like itertools.pairwise(), which is not available in some Python versions.


    If your plot (x, y) can be interpreted as (lon, lat) covering the whole sphere,
    use this function to set up nice plot bounds and grid ticks.


Plot sequence of frame centers.


    Returns image center coordinates such that images cover the range
    -@range_radius .. +@range_radius with at least the specified
    @overlap. If one image suffices, it will be centered at 0 (and the
    edges of the image will extend beyond the range if it is smaller
    than @fov).  If more than one image is needed to cover the range,
    the boundary images will cover exactly to the edges of the specified
    range (modulo @attitude_tolerance) and the images will be evenly spaced.

    :param float range_radius: Images must cover -range_radius .. +range_radius (degrees).
    :param float fov: Field of view of each image (degrees).
    :param float overlap: Minimum required overlap between consecutive images, as a proportion of the image field of view (0 .. 1).
    :param float attitude_tolerance: Ensure overlap criterion is met even if relative attitude between a pair of adjacent images, or between an image and the desired pano boundary, is off by at most this much (degrees).
    :return: A vector of orientations of image centers.


    Returns image center coordinates such that the images cover the full pan
    range -180 .. 180 with at least the specified @overlap between all consecutive images,
    including at the wrap-around, and the image sequence is centered at pan = 0.

    :param float fov: Field of view of each image (degrees).
    :param float overlap: Minimum required overlap between consecutive images, as a proportion of the image field of view (0 .. 1).
    :param float attitude_tolerance: Ensure overlap criterion is met even if relative attitude between a pair of adjacent images, or between an image and the desired pano boundary, is off by at most this much (degrees).
    :return: A vector of orientations of image centers (degrees).


    Returns image center coordinates for a row of images at tilt value
    @tilt that cover the range -@pan_radius .. +@pan_radius with at least
    the specified @overlap. Special complete wrap-around behavior is
    triggered when @pan_radius is exactly 180.

    :param float pan_radius: Cover pan angle of -pan_radius to +pan_radius (degrees).
    :param float h_fov: Horizontal field of view of each image (degrees).
    :param float v_fov: Vertical field of view of each image (degrees).
    :param float overlap: Minimum required overlap between consecutive images, as a proportion of the image field of view (0 .. 1).
    :param float attitude_tolerance: Ensure overlap criterion is met even if relative attitude between a pair of adjacent images is off by at most this much (degrees).
    :param float tilt: The tilt of the image center (degrees).
    :return: A vector of pan orientations of image centers (degrees).


    Return image center coordinates that cover the specified pan and tilt ranges,
    with the specified @overlap. Special complete wrap-around behavior is triggered when
    the pan_radius is exactly 180.

    :param float pan_radius: Cover pan angle of -pan_radius to +pan_radius (degrees).
    :param float tilt_radius: Cover tilt angle of -tilt_radius to +tilt_radius (degrees).
    :param float h_fov: Horizontal field of view of each image (degrees).
    :param float v_fov: Vertical field of view of each image (degrees).
    :param float overlap: Minimum required overlap between consecutive images, as a proportion of the image field of view (0 .. 1).
    :param float attitude_tolerance: Ensure overlap criterion is met even if relative attitude between a pair of adjacent images is off by at most this much (degrees).
    :return: (image_centers, nrows, ncols). A list of orientations of image centers, the number of rows in the panorama, and the number of columns.


    :param int imageSizePixels: Image size (pixels).
    :param float focalLengthPixels: Focal length (pixels).
    :param float omega: Distortion coefficient omega for FOV model.
    :param float kappa: Radial distortion coefficients kappa for Tsai model.
    :return: Image field of view (degrees).


circleangleloop(r, p, z)

  Calculate half central angle of the arc of circle of radius r
  (which concentrically spans the inside of the star during integration)
  that is inside a circle of radius p (planet)
  with separation of centers z.
  This is a zeroth order homogeneous function, that is,
  circleangle(alpha*r, alpha*p, alpha*z) = circleangle(r, p, z).

  This version uses a loop over r.

  Input:
    r  one dimensional numpy array
    p  scalar
    z  scalar
  They should all be non-negative, but there is no other restriction.

  Output:
    circleangle  one dimensional numpy array, same size as r


circleanglemask(r, p, z)

  Calculate half central angle of the arc of circle of radius r
  (which concentrically spans the inside of the star during integration)
  that is inside a circle of radius p (planet)
  with separation of centers z.
  This is a zeroth order homogeneous function, that is,
  circleangle(alpha*r, alpha*p, alpha*z) = circleangle(r, p, z).

  This version uses masked array operations.

  Input:
    r  one dimensional numpy array
    p  scalar
    z  scalar
  They should all be non-negative, but there is no other restriction.

  Output:
    circleangle  one dimensional numpy array, same size as r


circleanglesorted(r, p, z)

  Calculate half central angle of the arc of circle of radius r
  (which concentrically spans the inside of the star during integration)
  that is inside a circle of radius p (planet)
  with separation of centers z.
  This is a zeroth order homogeneous function, that is,
  circleangle(alpha*r, alpha*p, alpha*z) = circleangle(r, p, z).

  This version uses a binary search on the sorted r.

  Input:
    r  one dimensional numpy array, must be increasing
    p  scalar
    z  scalar
  They should all be non-negative, but there is no other restriction.

  Output:
    circleangle  one dimensional numpy array, same size as r


    Asynchronously handles incoming WebSocket connections and messages,
    and manages connection events such as connect, disconnect, and messaging.


    Handles the download process for data based on specified parameters, supporting both EarthAccess and pangeo-forge workflows.

    Args:
        current_job (Job): The current job object containing information about the job.
        short_name (str): Short name identifier for the dataset.
        date_range (str): String specifying the date range for the dataset query.
        concept_id (str, optional): The unique identifier for the dataset, if applicable.
        bounding_box (tuple, optional): Tuple specifying the geographic bounding box for the dataset query.
        isPangeoForge (bool): Flag to determine if the job is for Pangeo Forge; otherwise, it's for Earth Access.

    This function sets the job status, performs a EarthAccess search with non-None parameters,
    and processes results according to the specified workflow (Pangeo Forge or Earth Access).
    It also handles broadcasting status updates through the specified connection manager.


    Asynchronously retrieves the file paths from the job registry if the job is completed.

    Args:
        uid (str): Unique identifier for the job.
        jobs (dict): Dictionary containing job statuses and data.

    Returns:
        A list of file paths if available, or a job status indicating the current state or issues (e.g., not available, in progress, no granules).


    Asynchronously retrieves and processes the metadata for the specified job using EarthAccess API and xarray.

    Args:
        uid (str): Unique identifier for the job.
        jobs (dict): Dictionary of jobs which may contain granule results and other metadata.

    Returns:
        A dictionary containing processed metadata or a job status; or an error message if metadata cannot be parsed.


    Asynchronously retrieves the status of a specified job.

    Args:
        uid (str): Unique identifier for the job.
        jobs (dict): Dictionary containing job details and statuses.

    Returns:
        The current status of the job if available; otherwise, returns a status indicating the job is not available.


Calls a function, passing through only those keyword arguments that are not None.


Zips all zarr files located in the specified directory into a single zip file.


Uploads file to S3 and returns the CloudFront URL if successful.


Uploads a directory to S3 and broadcasts the upload status.


Processes result granules, generates zipped zarr files and uploads to S3.


Next: make sure redshift dependence works.


First, look at background flux itself.


    Analytic approximation to the ionization history.

    Assumes constant ionization rate, no recombinations.


    Analytic approximation to thermal history.

    Assumes constant heating rate.


Convert yield to erg / g.


        Can we just determine a luminosity density by scaling the SFRD?

        The answer will be "no" for any population with halo-mass-dependent
        values for photon yields (per SFR), escape fractions, or spectra.


        Dictionary of kwargs to pass on to an ares.source instance.

        This is basically just converting pop_* parameters to source_*
        parameters.


Exact clone of `src` except forces source_ssp=False.


        Convert from fractional luminosity in reference band to given bounds.

        If limits are None, will use (pop_Emin, pop_Emax).

        Parameters
        ----------
        Emin : int, float
            Minimum energy [eV]
        Emax : int, float
            Maximum energy [eV]

        Returns
        -------
        Multiplicative factor that converts LF in reference band to that
        defined by ``(Emin, Emax)``.


        Compute the mean energy per photon in the provided band.

        If sed_tab or yield provided, will need Spectrum instance.
        Otherwise, assumes flat SED?

        Parameters
        ----------
        Emin : int, float
            Minimum photon energy to consider in eV.
        Emax : int, float
            Maximum photon energy to consider in eV.

        Returns
        -------
        Photon energy in eV.


        Adjust Mmin or Mmax so that Mmax > Mmin and/or obeys user-defined
        floor and ceiling.


        Get the luminosity (per SFR) for all possible metallicities.

        Returns
        -------
        A function that takes in log10(metallicity) and returns
        log10(luminosity in erg/s/Hz/(Msun/yr)).


        Star formation rate density from halos just crossing threshold.

        Essentially the second term of Equation A1 from Furlanetto+ 2017.


        Compute the luminosity density in some bandpass for all redshifts.

        This is the most general way of computing the luminosity density as it
        takes into account all (existing) Mh- and z-dependent quantities.

        Returns
        -------
        Interpolant for luminosity density in units of erg / s / (comoving cm)**3.


        Compute the photon luminosity density in some bandpass at some redshift.

        Returns
        -------
        Luminosity density in units of photons / s / (comoving cm)**3.


        Correction factor for MAR.

        \eta(z) \int_{M_{\min}}^{\infty} \dot{M}_{\mathrm{acc}}(z,M) n(z,M) dM
            = \bar{\rho}_m^0 \frac{df_{\mathrm{coll}}}{dt}|_{M_{\min}}


For backward compatibility. Just calls self.Luminosity.


        Compute the luminosity function at redshift z.

        Returns
        -------
        Number of galaxies per unit luminosity per unit volume.


        Number of objects in each Mmin bin. Only use this for setting
        up Ensemble objects?


        These are the star-formation efficiencies derived from abundance
        matching.


        SFR as a function of redshift and halo mass.

            ..note:: Units are Msun/yr.

        This does NOT set the SFR to zero in halos with M < Mmin or M > Mmax!
        Doing so screws up spline fitting in SFR...but if we don't need the
        SFR function for anything...shouldn't we just do it?


        SFRD as a function of redshift.

            ..note:: Units are g/s/cm^3 (comoving).


        Simple semi-analytic model for the components of galaxies.

        Really just the right-hand sides of a set of ODEs describing the
        rate of change in the halo mass, stellar mass, and metal mass.
        Other elements can be added quite easily.

        All terms have units of per year. The last equation is simply
        the evolution of time wrt redshift.

        Parameters
        ----------
        z : int, float
            current redshift
        y : array
            halo mass, gas mass, stellar mass, gas-phase metallicity

        Returns
        -------
        An updated array of y-values.


Jacobian for _SAM_1z


        Compute the final mass of a halos that begin at Mmin and grow for dt.

        Parameters
        ----------
        dt : int, float
            Growth time [years]

        Returns
        -------
        Array of formation redshifts, final redshifts, and final masses.


        Take results of a SAM and grab data for a single formation redshift.

        Parameters
        ----------
        z : int, float
            Redshift of interest
        zarr : np.ndarray
            Array of all redshifts used in SAM.
        data : dict

        Returns
        -------
        Dictionary containing trajectories


        In this case, the formation time of a halo matters.

        Returns
        -------
        Dictionary of quantities, each having shape (z, z).

        The first dimension corresponds to formation time, the second axis
        represents trajectories. So, e.g., to pick out all halo masses at a
        given observed redshift (say z=6) you would do:

            zarr, data = self.Trajectories()
            k = np.argmin(np.abs(zarr - 6))
            Mh = data[:,k]

        A check on this


        Evolve a halo from initial mass M0 at redshift z0 forward in time.

        .. note :: If M0 is not supplied, we'll assume it's Mmin(z0).

        Parameters
        ----------
        z0 : int, float
            Formation redshift.
        M0 : int, float
            Formation mass (total halo mass).

        Returns
        -------
        redshifts, halo mass, gas mass, stellar mass, metal mass


Delta-function profile for the delta component of power spectrum (discrete galaxies)


Compute integrand of angular power spectrum integral.


Super non-general at the moment sorry.


        Reconstructed luminosity function for a given wavelength.
        **Only for Star-forming populations currently

        Population must be set with pars:
            pop_sed = 'eldridge2009'
            pop_tsf = 12 -  population age [Myr]

        Parameters
        ----------
        z : int, float
            Redshift. Currently does not interpolate between values in halos.tab_z if necessary.
        x : float
            Absolute (AB) magnitudes.
        Lambda : float
            Wavelength in Angstroms.

        Returns
        -------
        Number density.


Wrapper for getting stellar mass from a halo mass using the SMHM ratio.


For getting halo mass from a stellar mass using the SMHM ratio.


        Using the SMHM ratio, given a halo mass, returns the corresponding stellar mass

        Parameters
            ----------
            z : int, float
                Redshift.
            haloMass : float
                per stellar mass
            N, M_1, beta, gamma : Parameterized Quantities
                Dependant on z


        Stellar Mass Function from a double power law, following Moster2010

        Parameters
        ----------
        z : int, float
            Redshift. Currently does not interpolate between values in halos.tab_z if necessary.
        logbins : float
            log10 of Stellar mass bins. per stellar mass
        sf_type: string
            Specifies which galaxy population to use: total ='smf_tot' (default),
            star-forming ='smf_sf', quiescent ='smf_q'

        Returns
        -------
        Phi : float (array)
            Number density of galaxies [cMpc^-3 dex^-1]


        Stellar formation rate density.

        Parameters
        ----------
        z : int, float (array)
            Redshift.

        Returns
        -------
        SFRD : float (array)
            [M_o/yr/Mpc^3]


        Main sequence stellar formation rate from Speagle2014

        Parameters
        ----------
        z : int, float
            Redshift.
        mass : float (array)
            if haloMass=False (default) is the log10 stellar masses [stellar mass]
            else log10 halo masses [stellar mass]

        Returns
        -------
        logSFR : float (array)
            log10 of MS SFR [yr^-1]


        Specific stellar formation rate.

        Parameters
        ----------
        z : int, float
            Redshift.
        mass : float (array)
            if haloMass=False (default) is the log10 stellar masses [stellar mass]
            else log10 halo masses [stellar mass]

        Returns
        -------
        logSSFR : float (array)
            log10 of SSFR [yr^-1]


        Compute BH formation rate density.

        Units = cgs

        A bit odd to have this in mass units (would rather #/time/vol) but
        for the fcoll model one doesn't need to invoke a BH mass, hence
        the difference between the linked FRD model and the fcoll model below.


rho_bh in Msun / cMpc^3 / yr.


Compute the BH mass density.


Compute the BH accretion rate density.


        Compute the emissivity of this population as a function of redshift
        and rest-frame photon energy [eV].

        ..note:: If `E` is not supplied, this is a luminosity density in the
            (Emin, Emax) band.

        Parameters
        ----------
        z : int, float

        Returns
        -------
        Emissivity in units of erg / s / c-cm**3 [/ eV]


        Return the luminosity density in the (Emin, Emax) band.

        Parameters
        ----------
        z : int, flot
            Redshift of interest.

        Returns
        -------
        Luminosity density in erg / s / c-cm**3.


        Return the photon luminosity density in the (Emin, Emax) band.

        Parameters
        ----------
        z : int, flot
            Redshift of interest.

        Returns
        -------
        Photon luminosity density in photons / s / c-cm**3.


Formation rate density in # of clusters / yr / cMpc^3.


        Return the normalized mass function at redshift z, which includes
        clusters formed at all z' > z.


        Compute UV luminosity function at redshift `z`.

        Parameters
        ----------
        x : int, float, array [optional]
            Magnitudes at which to output the luminosity function.
            If None, will return magnitude grid used internally, set
            by mass resolution for cluster mass function and
            age resolution (set by pop_age_res).
        mags : bool
            Must be True for now.

        Returns
        -------
        if x is None:
            Returns tuple of (magnitudes, luminosity function)
        else:
            Returns luminosity function at supplied magnitudes `x`.


Integrate GCLF and make sure we recover FRD * dt.


Array of luminosity bin edges.


Array of times (since Big Bang) corresponding to observed redshifts.


Array of ages corresponding to redshifts at which we tabulate LF.


        Compute the emissivity of this population as a function of redshift
        and rest-frame photon energy [eV].

        Parameters
        ----------
        z : int, float

        Returns
        -------
        Emissivity in units of erg / s / c-cm**3 [/ eV]


        Compute the comoving star formation rate density (SFRD).

        Given that we're in the StellarPopulation class, we are assuming
        that all emissivities are tied to the star formation history. The
        SFRD can be supplied explicitly as a function of redshift, or can
        be computed via the "collapsed fraction" formalism. That is, compute
        the SFRD given a minimum virial temperature of star forming halos
        (Tmin) and a star formation efficiency (fstar).

        If supplied as a function, the units should be Msun yr**-1 cMpc**-3.

        Parameters
        ----------
        z : float
            redshift

        Returns
        -------
        Co-moving star-formation rate density at redshift z in units of
        g s**-1 cm**-3.


In the odd units of stars / cm^3 / s.


        This is not quite the standard definition of zeta. It has an extra
        factor of fbaryon since fstar is implemented throughout the rest of
        the code as an efficiency wrt baryonic inflow, not matter inflow.


        Expand an array to `thin` times its size. Group elements such that
        neighboring bundles of `thin` elements are objects that formed
        at the same redshift.


        From a set of smooth halo assembly histories, build a bigger set
        of histories by thinning, and (optionally) adding scatter to the MAR.


        Run models. If deterministic, will just return pre-determined
        histories. Otherwise, will do some time integration.


Compute emissivity over a grid of redshifts and setup interpolant.


        Take draws from cluster mass function until stopping criterion met.

        Return the amount of mass formed in this burst.


        Determin index of time-array in which to deposit some gas, energy,
        etc., given current time and requested delay.


Take halo histories and paint on galaxy histories in deterministic way.


        This is called when pop_sam_method == 1.

        The main difference between this model and pop_sam_method == 0 is that
        we try to 'do feedback properly', i.e., rather than prescribing the
        SFE as a function of redshift and mass, we dump energy/momentum in,
        with possible delay, and compare to binding energy etc. on a timestep
        by timestep basis. Should recover minimalist model when delay is zero.


        For backward compatibility as we move to get_* method model.

        See `get_mags` below.


        For backward compatibility as we move to get_* method model.

        See `get_lum` below.


        Convenience routine to retrieve `cam` and `filters` via short-hand.

        Parameters
        ----------
        z : int, float
            Redshift of interest.
        presets : str
            Name of presets package to use, e.g., 'hst', 'jwst', 'hst+jwst'.
        for_beta : bool
            If True, will restrict to filters used to compute UV slope.
        wave_range : tuple
            If for_beta==False, can restrict photometry to specified range
            of rest wavelengths (in Angstroms). If None, will return all
            photometry.

        Returns
        -------
        Tuple containing (i) list of cameras, and (ii) list of filters.


For backward compatibility -- see `get_AUV` below.


        Compute gradient in UV color at fixed stellar mass.

        Parameters
        ----------
        z : int, float
            Redshift of interest.
        dlam : int
            Wavelength resolution to use for Beta calculation.
        Mstell : int, float, np.ndarray
            Stellar mass at which to evaluate slope. Can be None, in which
            case we'll return over a grid with resolution 0.5 dex.
        model : str
            Fit Beta(Mstell) with this function and then
            determine slope at given Mstell via interpolation (after
            analytic differentiation). Options: 'quad2', 'quad3',
            or 'linear'.


For backward compatibility. See `get_surface_density`.


Load results from past run.


Output model (i.e., galaxy trajectories) to file.


        (void) -> DustEmission

        Creates and / or returns an instance of a DustEmission object used to calculate
        dust emissions from all the galaxies at all redshifts for a given frequency band.

        To adjust the frequency band, set the "dust_fmin", "dust_fmax", and "dust_Nfreqs"
        keywords to the desired frequencies (in Hz) and number of frequencies between
        dust_fmin and dust_fmax to be probed.

        To adjust the band of redshifts, set the "dust_zmin", "dust_zmax", and "dust_Nz"
        keywords.


        (number, number, integer) -> 1darray, 3darray

        This is a wrapper for DustPopulation.dust_sed.

        -----------

        RETURNS

        frequencies, SED : 1darray, 3darray

        first axis: galaxy index
        second axis: frequency index
        third axis: redshift index

        -----------

        PARAMETERS

        fmin: number
            minimum frequency of the band

        fmax: number
            maximum frequency of the band

        Nfreqs: integer
            number of frequencies between fmin and fmax to be calculated


    Return the appropriate Galaxy* instance depending on if any quantities
    are being parameterized by hand.

    kwargs should NOT be ParameterFile instance. Still trying to remind
    myself why that is.


Construct list of *Population class instances.


        Mass growth rate of halos of mass M at redshift z.

        ..note:: This is the *DM* mass accretion rate. To obtain the baryonic
            accretion rate, multiply by Cosmology.fbaryon.


        The integrated DM accretion rate.

        Parameters
        ----------
        z : int, float
            Redshift
        source : str
            Can be a litdata module, e.g., 'mcbride2009'.

        Returns
        -------
        Integrated DM mass accretion rate in units of Msun/yr/cMpc**3.


Compute differential brightness temperature for initial conditions.


        Run a 21-cm simulation.

        Returns
        -------
        Nothing: sets `history` attribute.


        Generator for the 21-cm signal.

        .. note:: Basically just calling MultiPhaseMedium here, except we
            compute the spin temperature and brightness temperature on
            each step.

        Returns
        -------
        Generator for MultiPhaseMedium object, with notable addition that
        the spin temperature and 21-cm brightness temperature are now
        tracked.


        Save results of calculation. Pickle parameter file dict.

        Notes
        -----
        1) will save files as prefix.history.suffix and prefix.parameters.pkl.
        2) ASCII files will fail if simulation had multiple populations.

        Parameters
        ----------
        prefix : str
            Prefix of save filename
        suffix : str
            Suffix of save filename. Can be hdf5 (or h5) or pkl.
            Anything else will be assumed to be ASCII format (e.g., .txt).
        clobber : bool
            Overwrite pre-existing files of same name?


        Save tables of rate coefficients (functions of column density).

        Parameters
        ----------
        prefix : str
            Prefix of output files.


        Run simulation from start to finish.

        Returns
        -------
        Nothing: sets `history` attribute.


Evolve properties of gas parcel in time.


        Run a simulation, compute power spectrum at each redshift.

        Returns
        -------
        Nothing: sets `history` attribute.


        Wavenumbers to output power spectra.

        .. note :: Can be far more crude than native resolution of
            matter power spectrum.


        Scales on which to compute correlation functions.

        .. note :: Can be more crude than native resolution of matter
            power spectrum, however, unlike `self.k`, the resolution of
            this quantity matters when converting back to power spectra,
            since that operation requires an integral over R.


Generator for the power spectrum.


        Loop over populations, determine background intensity.

        Parameters
        ----------
        include_pops : list
            For internal use only!


        Return background intensity at z=zf evolved to z=0 assuming optically
        thin IGM.

        This is just the second term of Eq. 25 in Mirocha (2014).


Grab radiation background at a single energy at z=0.


Convert the z=0 background intensity to a temperature in K.


        Propage radiation background from `zf` to z=0 assuming optically
        thin universe.

        Parameters
        ----------
        zf : int, float
            Final redshift to include in flux.
        popids : tuple, list
            Can restrict flux to that generated by certain source populations.
            If None, will return total z=0 flux from all populations.
        units : str
            Control output units. By default, result is in erg/s/cm^2/sr for
            units=='cgs'. Other options include:

                units='si' returns nu*Inu in nano-watts / m^2 / sr


Compute soft X-ray background flux at z=0.


        Evolve radiation background in time.

        .. note:: Assumes we're using the generator, otherwise the time
            evolution must be controlled manually.

        Returns
        -------
        Nothing: sets `history` attribute containing the entire evolution
        of the background for each population.


        Loop over flux generators and retrieve the next values.

        ..note:: Populations need not have identical redshift sampling.

        Returns
        -------
        Current redshift and dictionary of fluxes. Each element of the flux
        dictionary corresponds to a single population, and within that, there
        are separate lists for each sub-band over which we solve the RTE.


        Compute ionization and heating rate coefficients.

        Parameters
        ----------
        z : float
            Current redshift.

        Returns
        -------
        Dictionary of rate coefficients.


        Save results of calculation.

        Notes
        -----
        1) will save files as prefix.rfield.suffix.
        2) ASCII files will fail if simulation had multiple populations.

        Parameters
        ----------
        prefix : str
            Prefix of save filename
        suffix : str
            Suffix of save filename. Can be hdf5 (or h5) or pkl.
            Anything else will be assumed to be ASCII format (e.g., .txt).
        clobber : bool
            Overwrite pre-existing files of same name?


Initialize (up to two) GasParcels.


        Generator for a two-phase intergalactic medium.

        Returns
        -------
        Tuple containing the current time, redshift, and dictionaries for the
        IGM and CGM data at a single snapshot.


Prepend provided initial conditions to the data storage lists.


        Compute rate coefficients for next time-step based on current data.

        .. note:: This only sets temperature-dependent rate coefficients.

        Parameters
        ----------
        data : dict
            Dictionary containing gas properties of each cell.
        kwargs : optional keyword arguments
            ACCEPTS: k_ion, k_ion2, k_heat
            Must be: shape (`grid_cells`, number of absorbing species)

        Returns
        -------
        Nothing -- sets `rate_coefficients` attribute.


        Evolve properties of gas parcel in time.

        Parameters
        ----------
        t : float
            Time at outset of this step [in time_units]
        dt : float
            Step-size
        tf : float
            Final time, i.e., time to stop the calculation.

        Returns
        -------
        Generator for the evolution of this gas parcel. Each iteration yields
        the current time, current time-step, and a dictionary containing all
        grid quantities at this snapshot.


        Scales on which to compute correlation functions.

        .. note :: Can be more crude than native resolution of matter
            power spectrum, however, unlike `self.tab_k`, the resolution of
            this quantity matters when converting back to power spectra,
            since that operation requires an integral over R.


        Run self.N models.

        Parameters
        ----------
        prefix : str
            Prefix for all output files.
        save_freq : int
            Number of steps to take before writing data to disk. Note that if
            you're running in parallel, this is the number of steps *each
            processor* will take before writing to disk.
        clobber : bool
            Overwrite pre-existing files of the same prefix if one exists?
        restart : bool
            Append to pre-existing files of the same prefix if one exists?

        Returns
        -------


        Set the data (duh).

        The structure is as follows. The highest level division is between
        different quantities (e.g., 'lf' vs. 'smf'). Each of these quantities
        is an element of the returned dictionary. For each, there is a list
        of dictionaries, one per redshift. Each redshift dictionary contains
        the magnitudes (or masses) along with number density measurements
        and error-bars.


        Set x and ydata at the same time, either by passing in
        a simulation instance, a dictionary of parameters, or a
        sequence of brightness temperatures corresponding to the
        frequencies defined in self.frequencies (self.xdata).


        Hacky at the moment. Preventative measure against is_log=True for
        spectrum_logN. Could generalize.


    Convert string to parameter value.

    Parameters
    ----------
    p : str
        Name of parameter that the prior for this paramemeter is linked to.
    par : str
        Name of parameter who's prior is linked.
    pars : list
        List of values for each parameter on this step.

    Returns
    -------
    Numerical value corresponding to this linker-linkee relationship.


    Generate initial position vectors for nwalkers.

    Parameters
    ----------
    pars : list
        Names of parameters
    prior_set : DistributionSet object

    nwalkers : int
        Number of walkers


        The DistributionSet object which is used to initialize the walkers. If
        self.guesses_prior_set is set, it will be used here. Otherwise, the
        same DistributionSet which will be used in the likelihood calculation
        will be used to initialize the walkers.


        A setter for the PriorSet which will be used to initialize the walkers.
        This attribute is optional. If it is not set, the DistributionSet which
        is used in the likelihood calculation is used to initialize the
        walkers.

        value a DistributionSet object


Generate initial position vectors for all walkers.


        Initial guesses for walkers.

        .. note :: You can either supply a 1-D array, representing best guess
            for each parameter AND set the ``jitter`` attribute, which is a
            fractional offset in each dimension about this best guess point.
            OR you can supply


        If any walkers have been re-initialized to locations outside the
        prior range, push them back into the acceptable range.


        Re-initialize walkers after burn-in.

        Doing this a little more carefully now. Just focusing on last
        `nwalkers` elements of the chain, and will iteratively find
        a new point around which to center walkers based on ranked list of
        likelihoods AND only accepting points within bulk of final distribution.

        Note that we're correcting for something that would likely be fixed
        by a longer burn-in, and as a result will print a warning message
        if we've kludged the walker positions relative to the naive
        approach.

        Parameters
        ----------
        chain : np.ndarray
            An array with shape (nwalkers, nparams). The last snapshot of the
            burn-in.
        logL : np.ndarray
            log likelihoods from burn-in


        Run MCMC.

        Parameters
        ----------
        prefix : str
            Prefix for all output files.
        steps : int
            Number of steps to take.
        burn : int
            Number of steps to burn.
        save_freq : int
            Number of steps to take before writing data to disk.
        clobber : bool
            Overwrite pre-existing files of the same prefix if one exists?
        restart : bool, str
            Append to pre-existing files of the same prefix if one exists?
            Can also supply the filename of the checkpoint from which to
            restart.


Run sampler and handle I/O.


        Write blobs to disk.

        Parameters
        ----------
        blobs : list

        uncompress : bool
            True for MCMC, False for model grids.


        Figure out which models have already been run.

        Note that how this works depends on if the gridding has been changed.

        Parameters
        ----------
        prefix : str
            File prefix of files ending in *.pkl to be read in.


Create GridND instance, construct N-D parameter space.


        Run model grid, for each realization thru a given turning point.

        Parameters
        ----------
        prefix : str
            Prefix for all output files.
        save_freq : int
            Number of steps to take before writing data to disk. Note that if
            you're running in parallel, this is the number of steps *each
            processor* will take before writing to disk.
        clobber : bool
            Overwrite pre-existing files of the same prefix if one exists?
        restart : bool
            Append to pre-existing files of the same prefix if one exists?

        Returns
        -------


Determine if Tmin is an axis in our model grid.


        Determine which processors are to run which models.

        Parameters
        ----------
        method : int
            0 : OFF
            1 : Minimize the number of values of `par' each processor gets.
                Good for, e.g., Tmin.
            2 : Maximize the number of values of `par' each processor gets.
                Useful if increasing `par' slows down the calculation.

        Returns
        -------
        Nothing. Creates "assignments" attribute, which has the same shape
        as the grid, with each element the rank of the processor assigned to
        that particular model.


Generate output filename.


Create a fitter class and run the fit!


Return index of axis value closest to supplied value.


List of all GridAxis instances.


Names of all axes.


Dimensions of grid.


Total number of elements in grid.


Number of dimensions in grid.


List of Nd-element tuples corresponding to all_kwargs parameter sets.


Create a new axis, perhaps a product of two pre-existing axes.


Return instance of axis via its name or index number.


Return name of axis corresponding to given index.


Return index of axis corresponding to given name.


        Find location (tuple of indices) of given model (dictionary) in an array
        of shape self.data.shape.


Find location of given model (dictionary) in self.all_kwargs.


        Effectively do a numpy.meshgrid, but for any single parameter.

        The axes of our model grid are 1D, but often we'll perform
        operations on an N-D grid, so mapping the 1D axes values to N-D
        makes grabbing their values more convenient.

        Parameters
        ----------
        axis : str
            Name of axis to meshgrid.

        Is there a pre-existing vectorized method of doing this?

        Returns
        -------
        "Meshed," or N-D, version of input axis.


Take 1D data (like self.all_kwargs) and shape to grid.


        Slice through N dimensions.  Must provide dictionary
        describing higher dimensions we're slicing through ('slices').


Compute prior over entire grid.


        Marginalize over all axes except those in list 'space'.
        Currently only supporting 1D priors.

        Parameters
        ----------
        space : list
            List of axes (provide their names as strings) to include for the
            resulting N-D PDF. That is, marginalize over all axes *NOT*
            supplied via this argument.
        likelihood : np.ndarray
            Array, same shape as grid, denoting likelihood of every model.
        priors : NOT IMPLEMENTED


Compute mean and standard deviation of 1-D marginalized PDF.


        Compute shape of PDF array after marginalizing over axes, and
        also return list of axes names themselves (in order).


        Return list of parameter sets that have an unmarginalized
        likelihood greater than some threshold.


        Apply given function to single model and store it in its rightful
        place in self[name] or return.


Update dataset in self.


Store data in self.


Build N-dimensional parameter space via inner-product.


        From list of models (each a dictionary), recover the original
        kwargs, and build model grid.

        Parameters
        ----------
        all_kwargs : list
            Each of element is a dictionary, describing a single model.


        Get rate coefficients for ionization and heating. Sort into dictionary.

        Parameters
        ----------
        rfield : RadialField instance
            Contains attributes representing column densities and such.


        Compute rate coefficients for ionization and heating.

        Parameters
        ----------
        data : dict
            Data for current snapshot.
        t : int, float
            Current time (needed to make sure sources are on).


        Compute all source-dependent rates.

        (For given absorber assuming a multi-frequency SED)


        Returns photo-ionization rate coefficient for single frequency over
        the entire grid.


Returns photo-ionization rate coefficient for continuous source.


        Photo-electric heating rate coefficient due to photo-electrons previously
        bound to `species.'  If this method is called, it means TabulateIntegrals = 1.


        Secondary ionization rate which we denote elsewhere as gamma (note little g).

            absorber = species being ionized by photo-electron
            donor = species the photo-electron came from

        If this routine is called, it means TabulateIntegrals = 1.


Shell volume in length_units**3.


Return list of all neutral species.


Return list of all ionized species.


Return list of absorbers (don't include electrons).


Return number of absorbing species.


        Return dictionary containing abundances of parent
        elements of all ions.


        Return list (matching evolving_fields) with integers describing
        species type:
            0 = neutral
           +1 = ion
           -1 = other


        Return dictionary containing ionization threshold energies (in eV)
        for all absorbers.


        Return dictionary containing functions that compute the bound-free
        absorption cross-sections for all absorbers.


        Return dictionary containing conversion factor between species
        fraction and number density for all species.


Create a slab.


Set electron density - must have run set_density beforehand.


Compute total particle number density.


Compute column densities for all absorbing species.


        The vector 'q' is an array containing the values of all ion fractions and the
        gas energy.  This routine sets up the mapping between elements in q and the
        corrresponding physical quantities.

        Will be in order of increasing Z, then de, then ge.


Return volume of shell at distance r, thickness dr.


Volume of intersection between two spheres of radii R1 < R2.


Just a vectorized version of the overlap calculation.


        Overlap volumes, i.e., volumes in which a source affects two points
        in different ways. For example, V11 is the volume in which a source
        ionizes both points (at separation `dr`), V12 is the volume in which
        a source ionizes one point and heats the other, and so on.

        In this order: V11, V12, V13, V22, V23, V33


Volume in which a single source only affects one


Relative density != relative over-density.


        Fraction of volume filled by bubbles.

        This is never actually used, but for reference, the mean ionized
        fraction would be 1 - exp(-this). What we actually do is re-normalize
        the bubble size distribution to guarantee Q = zeta * fcoll. See
        MeanIonizedFraction and BubbleSizeDistribution for more details.


        This is the excess probability that a point is ionized given that
        we already know another point (at distance r) is ionized.


Mass array used for bubbles.


        Compute the ionized bubble size distribution.

        Parameters
        ----------
        z: int, float
            Redshift of interest.
        zeta : int, float, np.ndarray
            Ionizing efficiency.

        Returns
        -------
        Tuple containing (in order) the bubble radii, masses, and the
        differential bubble size distribution. Each is an array of length
        self.halos.tab_M, i.e., with elements corresponding to the masses
        used to compute the variance of the density field.


        This may not be quite right, since we just integrate over the mass
        range we have....


        Compute the probability that a point is something.

        These are the one point terms in brackets, e.g., <x>, <x delta>, etc.

        Note that use of the asterisk is to imply that both quatities
        are in the same set of brackets. Maybe a better way to handle this
        notationally...


        Essentially a wrapper around JointProbability that scales
        terms like <cc'>, <xc'>, etc., from their component probabilities
        <hh'>, <ih'>, etc.

        Parameters
        ----------
        z : int, float
        zeta : int, float
            Ionization efficiency
        R : np.ndarray
            Array of scales to consider.
        term : str

        Returns
        -------
        Tuple: total, one-source, two-source contributions to joint probability.


        Model in which IGM partitioned into three phases: ionized, hot, bulk.

        .. note :: If ps_include_temp==False, this is just a two-zone model
            since there is no heated phase in this limit.


Compute the correlation function of some general term.


        Find value of 'contrast' fluctuation given mean temperature Tk and
        assumed kinetic temperature of heated regions, Th.


        Pre-compute cross sections and such for each source population.

        Returns
        -------
        Nothing. Sets the following attributes:

        sigma_E
        log_sigma_E
        fheat, flya, fion


Return energy of a photon observed at (z, E) and emitted at zp.


Flux corresponding to one photon per hydrogen atom at redshift z.


        Convert an ionization/heating rate to a rate coefficient.

        Provides units of per atom.


        Compute heating rate density due to emission from this population.

        Parameters
        ----------
        z : int, float
            Redshift of interest.
        species : int
            Atom whose liberated electrons cause heating.
            Can be 0, 1, or 2 (HI, HeI, and HeII, respectively)

        ===============
        relevant kwargs
        ===============
        fluxes : np.ndarray
            Array of fluxes corresponding to photon energies in self.igm.E.
        return_rc : bool
            Return actual heating rate, or rate coefficient for heating?
            Former has units of erg s**-1 cm**-3, latter has units of
            erg s**-1 cm**-3 atom**-1.

        Returns
        -------
        Proper heating rate density in units of in erg s**-1 cm**-3 at redshift z,
        due to electrons previously bound to input species.


        Compute growth rate of HII regions.

        Parameters
        ----------
        z : float
            current redshift
        species : int
            Ionization rate for what atom?
            Can be 0, 1, or 2 (HI, HeI, and HeII, respectively)

        ===============
        relevant kwargs
        ===============
        fluxes : np.ndarray
            Array of fluxes corresponding to photon energies in self.igm.E.
        return_rc : bool
            Return actual heating rate, or rate coefficient for heating?
            Former has units of erg s**-1 cm**-3, latter has units of
            erg s**-1 cm**-3 atom**-1.

        Returns
        -------
        Ionization rate. Units determined by value of return_rc keyword
        argument, which is False by default.


        Compute volume averaged hydrogen ionization rate.

        Parameters
        ----------
        z : float
            redshift
        species : int
            HI, HeI, or HeII (species=0, 1, 2, respectively)

        Returns
        -------
        Volume averaged ionization rate in units of ionizations per
        second. If return_rc=True, will be in units of ionizations per
        second per atom.


        Compute volume averaged secondary ionization rate.

        Parameters
        ----------
        z : float
            redshift
        species : int
            Ionization rate of what atom?
            Can be 0, 1, or 2 (HI, HeI, and HeII, respectively)
        donor : int
            Which atom gave the electron?
            Can be 0, 1, or 2 (HI, HeI, and HeII, respectively)

        ===============
        relevant kwargs
        ===============
        fluxes : np.ndarray
            Array of fluxes corresponding to photon energies in self.igm.E.
        return_rc : bool
            Return actual heating rate, or rate coefficient for heating?
            Former has units of erg s**-1 cm**-3, latter has units of
            erg s**-1 cm**-3 atom**-1.

        Returns
        -------
        Volume averaged ionization rate due to secondary electrons,
        in units of ionizations per second.


        Flux of Lyman-alpha photons induced by photo-electron collisions.

        Can only be sourced by X-ray populations.


        Compute right-hand side of rate equation ODEs.

        Equations 1, 2, 3 and 9 in Mirocha et al. (2012), except
        we're solving for ion fractions instead of number densities.

        Parameters
        ----------
        t : float
            Current time.
        q : np.ndarray
            Array of dependent variables, one per rate equation.
        args : list
            Extra information needed to compute rates. They are, in order:
            [cell #, ionization rate coefficient (IRC), secondary IRC,
             photo-heating rate coefficient, particle density, time]


Compute the Jacobian for the system of equations.


        Compute values of rate coefficients which depend only on
        temperature and/or number densities of electrons/ions.


        Compute Lyman series line blanketing following Madau (1995).

        Parameters
        ----------
        zobs : int, float
            Redshift of object.
        owaves : np.ndarray
            Observed wavelengths in microns.


        Compute slope in some wavelength range or using photometry.

        Parameters
        ----------
        zobs : int, float
            Redshift of observation.
        rest_wave: tuple
            Rest-wavelength range in which slope will be computed (Angstrom).
        dlam : int
            Sample the spectrum with this wavelength resolution (Angstrom).
        window : int
            Can optionally operate on a smoothed version of the spectrum,
            obtained by convolving with a boxcar window function if this width.


        Over-sample time axis while stellar populations are young if the time
        resolution is worse than 1 Myr / grid point.


Cache object for spectral synthesis of stellar luminosity.


Calculate what the bounds of the table must be for a given grid.


Return list of quantities to compute.


Figure out ND space of all lookup table elements.


        Return name of table. Will be called from dictionary or hdf5 using
        this name.


        Return a dictionary of lookup tables, and also store a copy as
        self.itabs.


Tabulate the optical depth as a function of energy and column density.


        Optical depth due to all absorbing species at given column density.

        Parameters
        ----------
        N : array
            Each entry is the column density for a particular element.


        Optical depth of species integrated over entire spectrum at a
        given column density.  We just use this to determine which cells
        are inside/outside of an I-front (OpticalDepthDefiningIfront = 0.5
        by default).


Returns the optical depth at energy E due to column density ncol of species.


        Returns the optical depth at energy E due to column densities
        of all absorbers.

        Parameters
        ----------
        E : float, list
            Energy of photon to consider [eV]
        N : list, dictionary
            Column densities for all absorbers


        Energy-dependent optical depth as a function of column density.

        ..note:: Includes the contributions from all absorbers.

        This is sorted by absorber only because each absorber has its own
        array of energies.


        Equation 10 in Mirocha et al. 2012.

        Parameters
        ----------
        N : list
            Column density for each absorbing species.
        absorber : str
            Name of absorber, probably 'h_1', 'he_1', or 'he_2'.
        ind : int
            [Optional] index where input column density lives in self.Nall.


        Equation 11 in Mirocha et al. 2012.

        Parameters
        ----------
        N : list
            Column density for each absorbing species.
        absorber : str
            Name of absorber, probably 'h_1', 'he_1', or 'he_2'.
        ind : int
            [Optional] index where input column density lives in self.Nall.


Equation 2.20 in the manual.


Equation 2.21 in the manual.


Equation 2.18 in the manual.


Equation 2.19 in the manual.


Return fractional Lyman-alpha excitation.


        Write table to hdf5.

        Parameters
        ----------
        prefix : str
            Prefix for output files. Suffix will be .hdf5.


Load table from hdf5.


        Non-column-density dimension in lookup table.

        Is it ionized fraction or time?


Create interpolation table.


    These are grid parameters -- we'll strip off the prefix in
    MultiPhaseMedium calculations.


    Parameters associated with populations of objects, which give rise to
    meta-galactic radiation backgrounds.


    Compute number of frequency bins required for given log-x grid.

    Defining the variable x = 1 + z, and setting up a grid in log-x containing
    Nx elements, compute the number of frequency bins required for a 1:1
    mapping between redshift and frequency.


Split apart an array into its positive and negative chunks.


Add a population ID tag to each parameter.


Find ParameterizedQuantity parameters and tag with `num`.


List of ID numbers -- one for each population.


Return dictionary of parameters that aren't associated with a population.


        Return dictionary of parameters associated with population `num`.

        This will take any parameters with ID numbers, and any parameters
        with the `hmf_` prefix, since populations need to know about that
        stuff. Also, dustcorr parameters, optical depth stuff.


Convert underscores to brackets.


Split apart parameter prefix and ID number.


    Break apart parameter name, a population ID #, and potentially another
    identification number that corresponds to a ParameterizedQuantity.


Count the number of populations to be used for this calculation.


Count the number of parameterized halo properties in this model.


    Count the number of parameterized halo properties in this model.

    Sort them by population ID #.

    Returns
    -------
    List of lists: ParameterizedQuantity ID numbers for each population.
    NOTE: they are not in order.


List of parameterized halo properties.


        Parse kwargs dictionary.

        There has to be a better way...

        If Npops == 1, the master dictionary should *not* have any parameters
        with curly braces.
        If Npops > 1, all population-specific parameters *must* be associated
        with a population, i.e., have curly braces in the name.


Show the parameters that are not defaults.


Run through parsed parameter file looking for conflicts.


Problems using MultiPhaseMedium or MetaGalacticBackground.


    Storage bin for predefined problem types.

    Parameters
    ----------
    ptype : int, float
        Problem type!

    Problem Types
    -------------
    - 0-100 (1-D radiative transfer)
    - 100+  (Global 21-cm)

    Returns
    -------
    Dictionary of parameters and values for given ptype.


Take asymmetric errorbars and return symmetrized version.


    Parameters
    ----------
    pars[0] : float
        Baseline / offset.
    pars[1] : float
        Amplitude / normalization.
    pars[2] : float
        Mean
    pars[3] : float
        Variance.


    Compute 1-D (possibly asymmetric) errorbar for input PDF.

    Parameters
    ----------
    x : np.ndarray
        bins
    y : np.ndarray
        PDF
    nu : float
        Integrate out until nu-% of the likelihood has been enclosed.

    Example
    -------
    For a Gaussian, should recover 1, 2, and 3 sigma easily:
    >>> x = np.linspace(-20, 20, 10000)
    >>> y = np.exp(-x**2 / 2. / 1.)
    >>> print error_1D(x, y, 0.6827), error_1D(x, y, 0.9545), error_1D(x, y, 0.9973)

    Returns
    -------
    If tailed is None:
    Tuple containing (maximum likelihood value, (lower errorbar, upper errorbar)).


    Find 2-D contour given discrete samples of posterior distribution.

    Parameters
    ----------
    x : np.ndarray
        Array of samples in x.
    y : np.ndarray
        Array of samples in y.
    bins : np.ndarray, (2, Nsamples)

    method : str
        'raw', 'nearest', 'linear', 'cubic'


    Integrate outward at "constant water level" to determine proper
    2-D marginalized confidence regions.

    ..note:: This is fairly crude -- the "coarse-ness" of the resulting
        PDFs will depend a lot on the binning.

    Parameters
    ----------
    L : np.ndarray
        Grid of likelihoods.
    nu : float, list
        Confidence intervals of interest.

    Returns
    -------
    List of contour values (relative to maximum likelihood) corresponding
    to the confidence region bounds specified in the "nu" parameter,
    in order of decreasing nu.


    Compute correlation matrix.

    Parameters
    ----------
    x : list
        Each element is an array of data for that dimension.
    mu : list
        List of mean values in each dimension.


Convert bin edges to bin centers.


Convert bin centers to bin edges.


    Quantify the scatter in some relationship between two variables, x and y.

    Parameters
    ----------
    x : np.ndarray
        Independent variable
    y : np.array
        Dependent variable
    xbin_c : np.ndarray
        Bin centers for `x`
    weights : np.ndarray
        Can weight each samples by some factor.
    inclusive : bool
        Include samples above or below bounding bins in said bins.
    method_avg : str
        How to quantify the average y value in each x bin.
        Options: 'avg', 'median', 'mode'
    method_std : str, float
        How to quantify the spread in y in each x bin.
        Options: 'std', 'normal', 'lognormal', 'bounds', 'pdf', float
        If a float is provided, assume it's a percentile, e.g.,
        method_std=0.68 will return boundaries of region containing 68% of
        samples.
    cdf_lim : float
        If fitting a normal or log-normal function to the distribution in each
        bin, include the PDF up until this value of the CDF when fitting the
        distribution. Essentially a kludge to exclude long tails in fit, to
        better capture peak and width of (main part of) the distribution.


    Bin samples in x and y.

    This is for backward compatibility. It's just a wrapper around
    `quantify_scatter` defined above.


        Write initial conditions. If redshift dumps wanted, store
        initial dataset as both dd and rd.


        Store data or don't.  If (t + dt) or (z + dz) passes our next checkpoint,
        return new dt (or dz).


May be conflict if this time/redshift corresponds to DD and RD.


        Compute next timestep based on when our next data dump is, and
        when the source turns off (if ever).


        Limit timestep based on maximum allowed change in fields.  Which
        fields determined by method parameter.


Create a pretty label for this parameter (if possible).


    Writes a pickle file containing the given value at the given file name.

    value: the object to pickle
    file_name: the file in which to save the pickled value
    ndumps: number of individual calls to dump.
            If ndumps==1, then value is pickled directly
            If ndumps>1, then value is interpreted as a sequence (list or
                         tuple) of length ndumps of objects to pickle
    open_mode: the opening mode of the pickle file (either 'w' or 'a')
    safe_mode: if True, function is guaranteed not to overwrite existing files
    verbose: Boolean determining whether a string should be printed describing
             what file is being saved by this function


    Reads the pickle file located at the given file name.

    file_name: the name of the file which is assumed to be a pickled object
    nloads: number of separate calls to load to make.
            If nloads==1, one object is loaded and returned
            If nloads>1, a sequence of nloads objects is loaded and returned
            If nloads is None, load is called until it raises an error and this
                               function returns a sequence whose length is
                               given by the number of successful calls to
                               pickle.load and whose values are the unpickled
                               objects
    verbose: Boolean determining whether string should be printed echoing the
             location of the file being read

    returns: the object(s) pickled in the file located at file_name


    Deletes the given file if it exists and clobber is set to True.

    file_name: the file to delete, if it exists
    clobber: if clobber is False, nothing is done
    verbose: if verbose is True, a message indicating the file is being removed
             is printed to the user


    Deletes the given file if it exists.

    file_name: the file to delete, if it exists
    verbose: if verbose is True, a message indicating the file is being removed
             is printed to the user


    Writes the given quantity to a pickle file at the given path, regardless of
    whether there is a file currently existing there.

    quantity: the object to save in the pickle file at the given path
    file_name: path to name of desired file. If a file already exists there, it
               will be deleted.
    verbose: if verbose is True, a message indicating the file is being removed
             is printed to the user


    Read data from the literature.

    Parameters
    ----------
    prefix : str
        Everything preceeding the '.py' in the name of the module.
    path : str
        If you want to look somewhere besides $ARES/input/litdata, provide
        that path here.


Take fluxes sorted by band and flatten to single energy dimension.


    Return an array as function of redshift and (flattened) energy.

    The input 'arr' will be a nested thing that is pretty nasty to deal with.

    The first dimension corresponds to band 'chunks'. Elements within each
    chunk may be a single array (2D: function of redshift and energy), or, in
    the case of sawtooth regions of the spectrum, another list where each
    element is some sub-chunk of a sawtooth background.


Take flattened fluxes and re-sort into band-grouped fluxes.


    Take list of dictionaries and re-sort into 2-D arrays.

    Parameters
    ----------
    all_data : list
        Each element is a dictionary corresponding to data at a particular
        snapshot.
    prefix : str
        Will prepend to all dictionary keys in output dictionary.

    Returns
    -------
    Dictionary, sorted by gas properties, with entire history for each one.


    Reads arbitrary meta-data blobs from emcee that have been pickled.

    Parameters
    ----------
    chain : str
        Name of file containing flattened chain.
    logL : str
        Name of file containing likelihoods.
    pars : str
        List of parameters corresponding to second dimension of chain.

    Returns
    -------
    All the stuff.


    Take a 3-D array, eliminate dimension corresponding to walkers, thus
    reducing it to 2-D


    Take a 2-D array, eliminate dimension corresponding to walkers, thus
    reducing it to 1-D


    Handle some conventions used in the pre "pop_*" parameter days.

    .. note :: Only applies to simple global 21-cm models right now, i.e.,
        problem_type=101, ParameterizedQuantity parameters, and the
        pop_yield vs. pop_rad_yield change.

    Parameters
    ----------
    ptype : int, float
        Problem type.

    Returns
    -------
    Dictionary of parameters to subsequently be updated.


    Compute the derivative of y with respect to x via forward difference.

    Parameters
    ----------
    x : np.ndarray
        Array of x values
    y : np.ndarray
        Array of y values

    Returns
    -------
    Tuple containing x values and corresponding y derivatives.


    Compute the derivative of y with respect to x via central difference.

    Parameters
    ----------
    x : np.ndarray
        Array of x values
    y : np.ndarray
        Array of y values

    Returns
    -------
    Tuple containing x values and corresponding y derivatives.


Compute the first derivative of y wrt x using five point method.


    Smooth 1-D function `y` using boxcar of width `kernel` (in pixels).

    Kernel options: 'boxcar' and 'gaussian'


        Setup arrays for 1D interpolation.

        Use numpy, but do something numpy doesn't do, which is check to make
        sure x-values are ascending.


Interpolate in 2D.


Interpolate in 3D.


    Take a string, add a prefix and suffix (some number of # symbols).

    Optionally justify string, 'c' for 'center', 'l' for 'left', and 'r' for
    'right'. Defaults to left-justified.


Take table, row names, column names, and output nicely.


    Print information about a population to the screen.

    Parameters
    ----------
    pop : ares.populations.*Population instance


    Print information about simulation to screen.

    Parameters
    ----------
    sim : ares.simulations.Global21cm or PowerSpectrum21cm instance.


    Print information about radiation background calculation to screen.

    Parameters
    ----------
    igm : glorb.evolve.IGM instance
    zarr : np.ndarray
        Redshift points.
    xarr : np.ndarray
        Ionized fraction values at corresponding redshifts.


        Compute 21-cm signal given Gaussian model parameters.

        Input parameters assumed to be in the following order:

        A, nu, sigma, bias_temp

        where Jref, Tref, and xref are the step heights, zref_? are the step
        locations, and dz_? are the step-widths.

        Note that Jref is in units of J21.

        Returns
        -------
        ares.analysis.Global21cm instance, which contains the entire signal
        and the turning points conveniently in the "turning_points"
        attribute.


Compute heating rate coefficient.


Compute ionization rate coefficient.


        Compute 21-cm signal given tanh model parameters.

        Input parameters assumed to be in the following order:

        Jref, zref_J, dz_J,
        Tref, zref_T, dz_T,
        xref, xref_J, dz_x

        where Jref, Tref, and xref are the step heights, zref_? are the step
        locations, and dz_? are the step-widths.

        Note that Jref is in units of J21.

        Returns
        -------
        ares.analysis.Global21cm instance, which contains the entire signal
        and the turning points conveniently in the "turning_points"
        attribute.


        Create a master dictionary containing the MUV points, phi points,
        and (possibly asymmetric) errorbars for all (or some) data available.

        .. note:: Since we store errorbars in +/- order (if asymmetric), but
            matplotlib.pyplot.errorbar assumes -/+ order, we swap the order here.

        Parameters
        ----------
        z : int, float
            Redshift, dummy!


Make a nice plot showing UVLF and UV CMD constraints and models.


Plot Beta(z) at fixed MUV and (optionally) Mstell.


        Plot the luminosity function data at a given redshift.

        Parameters
        ----------
        z : int, float
            Redshift of interest
        wavelength : int, float
            Wavelength (in Angstroms) of LF.
        sed_model : instance
            ares.sources.SynthesisModel
        imf : str
            Stellar initial mass function. Will be used to convert stellar
            masses, if supplied.


Make color-color plot including high-z selection criteria.


Annotate sources properly color-coded.


Make a huge plot.


Plot many samples


Set up scipy.interpolate.interp1d instances for all fields.


Interpolate value of any field in self.history to redshift z.


Find midpoint of reionization.


Compute CMB optical depth history.


        Take plot with redshift on x-axis and add top axis with corresponding
        (observed) 21-cm frequency.

        Parameters
        ----------
        ax : matplotlib.axes.AxesSubplot instance


        By default, we plot quantities vs. redshift, ascending from left to
        right. This method will flip the x-axis, so that redshift is
        decreasing from left to right.


Add inset 'slider' thing.


        Plot kinetic, CMB, and spin temperatures vs. redshift.

        Parameters
        ----------


        Plot ionized fraction evolution.

        Parameters
        ----------
        zone : str
            Either "cgm", "igm", or None. If None, will plot mean ionized
            fraction evolution


Plot ionization rates as a function of redshift.


        Plot (cumulative) optical depth to CMB evolution.

        Parameters
        ----------
        obs_mu : float
            Observationally constrained CMB optical depth. If supplied, will
            draw shaded region denoting this value +/- the error (obs_sigma,
            see below).
        obs_sigma : float
            1-sigma error on CMB optical depth.
        show_obs : bool
            Show shaded region for observational constraint?


        Compute optical depth to electron scattering of the CMB.
        Equation 2 of Shull & Venkatesan 2008.

        Only includes optical depth to CMB contribution from a time after
        the final redshift in the dataset. It is assumed that the universe
        is fully ionized at all times, and that helium reionization occurs
        at z = 3.

        Returns
        -------
        Post-EoR (as far as our data is concerned) optical depth.


    Take plot with frequency on x-axis and add top axis with corresponding
    redshift.

    Parameters
    ----------
    ax : matplotlib.axes.AxesSubplot instance
        Axis on which to add a redshift scale.


    Take plot with redshift on x-axis and add top axis with corresponding
    time since Big Bang.

    Parameters
    ----------
    ax : matplotlib.axes.AxesSubplot instance


        Plot differential brightness temperature vs. redshift (nicely).

        Parameters
        ----------
        ax : matplotlib.axes.AxesSubplot instance
            Axis on which to plot signal.
        fig : int
            Figure number.

        Returns
        -------
        matplotlib.axes.AxesSubplot instance.


        Plot correlation function of input fields.

        Parameters
        ----------
        ax : matplotlib.axes.AxesSubplot instance
            Axis on which to plot signal.
        fig : int
            Figure number.

        Returns
        -------
        matplotlib.axes.AxesSubplot instance.


        Plot bubble size distribution.

        Parameters
        ----------
        ax : matplotlib.axes.AxesSubplot instance
            Axis on which to plot signal.
        fig : int
            Figure number.
        by_volume : bool
            If True, uses bubble volume rather than radius.

        Returns
        -------
        matplotlib.axes.AxesSubplot instance.


Plot the fraction of the volume composed of ionized bubbles.


        Plot the fraction of the volume composed of ionized bubbles.

        Parameters
        ----------


        Split apart a correlation function into its positive and negative
        chunks.


    Convert heating rate coefficients to a total heating rate using
    number densities of relevant ion species.

    Returns
    -------
    Total heating in units of [erg / s / cMpc**3]


Construct array of models in the order in which we'll plot them.


        Animate variations of a single parameter.

        Parameters
        ----------
        par : str
            Parameter to vary.
        pivots : list, tuple

        ..note:: should implement override for kwargs, like change color of
            line/symbol if some condition violated (e.g., tau_e).


Basically run a series of Plot1D.


        Determine if we have just passed a turning point.

        Parameters
        ----------
        z : np.ndarray
            Redshift (descending order).
        dTb : np.ndarray
            Corresponding brightness temperatures.


        If turning point is unphysical, something went wrong.
        Fall back to simpler estimate.


    Find the attribute nested somewhere in an object that we need to compute
    the value of blob `blob_name`.

    ..note:: This is the only place I ever use eval (I think). It's because
        using __getattribute__ conflicts with the __getattr__ method used
        in analysis.Global21cm.

    Parameters
    ----------
    blob_name : str
        Full name of blob (might be nested)
    obj_base : instance
        Usually just an instance of BlobFactory, which is inherited by
        simulation classes, so think of this as an instance of an
        ares.simulation class.


Estimate for the size of each blob (per walker per step).


        Create a list of blobs, one per blob group.

        ..note:: This should only be run for individual simulations,
            not in the analysis of MCMC data.

        Returns
        -------
        List, where each element has shape (ivar x blobs). Each element of
        this corresponds to the blobs for one blob group, which is defined by
        either its dimensionality, its independent variables, or both.

        For example, for 1-D blobs, self.blobs[i][j][k] would mean
            i = blob group
            j = index corresponding to elements of self.blob_names
            k = index corresponding to elements of self.blob_ivars[i]


        Returns
        -------
        index of blob group, index of element within group, dimensionality,
        and exact dimensions of blob.


        Re-organize background fluxes to a more easily-analyzable shape.

        Parameters
        ----------
        popid : int
            Population ID number.
        emissivity : bool
            If True, return emissivities. If False, return fluxes.


        Operations on the best fit to the CXRB from Moretti et al. 2009 from 2keV-2MeV.

        Energy units are in keV.
        Flux units are keV^2/cm^2/s/keV/sr

        Convert energies to eV throughout, change default flux units
        Include results from Markevich & Hickox


        Sum over populations and stitch together different bands to see the
        meta-galactic background flux over a broad range of energies.

        .. note:: This assumes you've already run the calculation to
            completion.

        Parameters
        ----------
        z : int, float
            Redshift of interest.


        Return total CXRB flux (resolved + unresolved) in erg / s / cm^2 / deg^2.
        Plotting this should reproduce Figure 11 in Moretti et al. 2009 (if
        fit == 1) modulo the units.