    Standalone function for stitching.
    Interprets map_array, a 1- or 2-rank list containing MosaicTile class
    instances arranged in proper locations. If there is not a tile
    (determined by checking for the mrefl3d attribute), then no attempt will be
    made to stitch. This method does some simple error checks to avoid problems
    but the user is primarily responsible for not inputing garbage.
    After that, it will iteratively call MosaicStitch.stitch_ns() and
    MosaicStitch.stitch_we() to do the heavy lifting.
    direction = Expected to be a string showing which direction to stitch
                (we or ns), and is only used if this function is sent a
                1-D map_array.
    Returns a MosaicStitch() class containing every tile provided in map_array,
    with each tile located where map_array told it to be.
    This function is standalone due to weird errors occurring if it was
    part of the MosaicStitch() class.


    Sent 3-D reflectivity array, 2-D lat/lon arrays and 1-D height arrays,
    compute the volume of each grid cell. Assumes km. Set as independent
    function so that it is easier for other programs to use it for their
    specific grids. For MosaicTiles and Stitches, send the mrefl3d, Latitude,
    Longitude, and Height attributes. Assumes constant grid spacing in horiz.
    Returns volumes of 3-D grid cells (km**3) & areas of 2-D grid cells (km**2)


    Given an epoch time (seconds since 1/1/1970), return a string useful
    as a plot title. Set the use_second flag to also include seconds in
    the string.


Pass thru first doing N-S stitches, then E-W after


Adds a model-dataset pair to fit.

        Parameters
        ----------
        model : `barry.models.Model`
            The model class to fit.
        dataset : `barry.datasets.Dataset`
            The dataset to fit.
        extra_args : kwargs, optional
            Any extra information you want returned with the chains from model fitting.
            I often use this to name my pairs to make it convenient to load into `ChainConsumer`.


Load in all the chains and fitting results

        Parameters
        ----------
        split_models : bool, optional
            Keep the models split and separate. Set this to false to combine the chains (very specific user
            case for this, think hard if you feel like you want to set it to `False`).
        split_walkers : bool, optional
            Split up each walker to make things like convergence diagnostics easier. Defaults to `False`

        Returns
        -------
            fits : list
                A list of each model+dataset pair (assuming `split_models` is `True`).
                Each element contains, in order:
                    - log_posterior[steps]
                    - weights[steps] (not log)
                    - chain[steps:dimensions]
                    - the model
                    - the dataset
                    - dict containing any `extra` information passed in.


Produces a plot of the maximum a posteriori model in the chain and returns the model, parameters and chi-squared at this point

    Returns
    -------
    chi2: float
        The chi squared value at the maximum a posteriori point
    bband: list
        A list of the best-fit values for any analytically marginalised points at the maximum a posteriori point.
    model : np.ndarray
        The model multipoles
    smooth : np.ndarray
        The dewiggled model multipoles


Runs the BAO Extractor method and returns the extracted BAO signal.

        Warning that this is the estimator given in Eq5 Nishimichi 2018

        As such, make sure your k values are finely sampled and linearly spaced. Alas for
        our data, this isn't always possible to do because the window function wrecks us.

        Parameters
        ----------
        ks : np.array
            The k values for the BAO power spectrum
        pk : np.array
            The power spectrum at `ks`

        Returns
        -------


Process the power spectrum to get a mix of extracted BAO and P(k)

        Parameters
        ----------
        ks : np.ndarray
            Wavenumbers
        pk : np.ndarray
            Power at wavenumber
        mask : np.ndarray (bool mask), optional
            Which k values to return at the end. Used to remove k values below / above certain values.
            I pass them in here because if we reorder the k values the masking cannot be done outside this function.


        Fit the model

        Parameters
        ----------
        model : class <Model>
            An instance of one of barry's model classes
        save_dims : int, optional
            Only return values for the first ``save_dims`` parameters.
            Useful to remove numerous marginalisation parameters if running
            low on memory or hard drive space.
        uid : str, optional
            A unique identifier used to differentiate different fits
            if two fits both serialise their chains and use the
            same temporary directory

        Returns
        -------
        dict
            A dictionary containing the chain and the weights


Runs the sampler over the model and returns the flat chain of results

        Parameters
        ----------
        model : class <Model>
            An instance of one of barry's model classes
        save_dims : int, optional
            Only return values for the first ``save_dims`` parameters.
            Useful to remove numerous marginalisation parameters if running
            low on memory or hard drive space.
        uid : str, optional
            A unique identifier used to differentiate different fits
            if two fits both serialise their chains and use the
            same temporary directory
        Returns
        -------
        dict
            A dictionary with key "chains" containing the final
            flattened chain of dimensions
             ``(num_dimensions, num_walkers * (num_steps - num_burn))``


Just runs a simple grid search and stores the grid points in the chain file.

        Parameters
        ----------
        model : class <Model>
            An instance of one of barry's model classes
        save_dims : int, optional
            Only return values for the first ``save_dims`` parameters.
            Useful to remove numerous marginalisation parameters if running
            low on memory or hard drive space.
        uid : str, optional
            A unique identifier used to differentiate different fits
            if two fits both serialise their chains and use the
            same temporary directory
        Returns
        -------
        dict
            A dictionary of results containing:
                - *chain*: the best fit point
                - *posterior*: the likelihood at this point


Load existing results from a file


Ensures that the position object, which can be none from loading, is a
        valid [starting] position.


Runs the sampler over the model and returns the flat chain of results

        Parameters
        ----------
        model : class <Model>
            An instance of one of barry's model classes
        save_dims : int, optional
            Only return values for the first ``save_dims`` parameters.
            Useful to remove numerous marginalisation parameters if running
            low on memory or hard drive space.
        uid : str, optional
            A unique identifier used to differentiate different fits
            if two fits both serialise their chains and use the
            same temporary directory
        Returns
        -------
        dict
            A dictionary of results containing:
                - *chain*: the chain
                - *weights*: chain weights if applicable
                - *posterior*: posterior values for each point in the chain
                - *evidence*: Bayesian evidence for the model/data combo.


Runs the sampler over the model and returns the flat chain of results

        Parameters
        ----------
        model : class <Model>
            An instance of one of barry's model classes
        save_dims : int, optional
            Only return values for the first ``save_dims`` parameters.
            Useful to remove numerous marginalisation parameters if running
            low on memory or hard drive space.
        uid : str, optional
            A unique identifier used to differentiate different fits
            if two fits both serialise their chains and use the
            same temporary directory
        Returns
        -------
        dict
            A dictionary of results containing:
                - *chain*: the chain
                - *weights*: chain weights if applicable


 " Just runs a simple optimisation and stores the best fit in the chain file.

        Parameters
        ----------
        model : class <Model>
            An instance of one of barry's model classes
        save_dims : int, optional
            Only return values for the first ``save_dims`` parameters.
            Useful to remove numerous marginalisation parameters if running
            low on memory or hard drive space.
        uid : str, optional
            A unique identifier used to differentiate different fits
            if two fits both serialise their chains and use the
            same temporary directory
        Returns
        -------
        dict
            A dictionary of results containing:
                - *chain*: the best fit point
                - *posterior*: the likelihood at this point


Computes the power spectrum model using the Ding et. al., 2018 EFT0 propagator

        Parameters
        ----------
        k : np.ndarray
            Array of (undilated) k-values to compute the model at.
        p : dict
            dictionary of parameter names to their values
        smooth : bool, optional
            Whether or not to generate a smooth model without the BAO feature
        shape : bool, optional
            Whether or not to include shape marginalisation terms.
        dilate : bool, optional
            Whether or not to dilate the k-values of the model based on the values of alpha (and epsilon)

        Returns
        -------
        kprime : np.ndarray
            Wavenumbers of the computed pk
        pk0 : np.ndarray
            the model monopole interpolated to kprime.
        pk2 : np.ndarray
            the model quadrupole interpolated to kprime. Will be 'None' if the model is isotropic
        pk4 : np.ndarray
            the model hexadecapole interpolated to kprime. Will be 'None' if the model is isotropic


Defines model parameters, their bounds and default value.


Computes the smoothed linear power spectrum and the wiggle ratio

        Parameters
        ----------
        om : float
            The Omega_m value to generate a power spectrum for

        Returns
        -------
        pk_smooth_lin : np.ndarray
            The power spectrum smoothed out
        pk_ratio : np.ndarray
            the ratio pk_lin / pk_smooth, transitioned using sigma_nl


Get raw ks and p(k) multipoles for a given parametrisation dilated based on the values of alpha and epsilon

        Parameters
        ----------
        p : dict
            dictionary of parameter names to their values
        smooth : bool, optional
            Whether or not to generate a smooth model without the BAO feature
        shape : bool, optional
            Whether or not to include shape marginalisation terms.

        Returns
        -------
        ks : np.ndarray
            Wavenumbers of the computed pk
        pk0 : np.ndarray
            the model monopole interpolated using the dilation scales.
        pk2 : np.ndarray
            the model quadrupole interpolated using the dilation scales. Will be 'None' if the model is isotropic


Returns the polynomial components for 3 terms per multipole

        Parameters
        ----------
        k : np.ndarray
            Array of k values for the shape terms
        p : dict
            dictionary of parameter name to float value pairs
        pk: np.ndarray
            the power spectrum components without polynomials

        Returns
        -------
        shape : np.ndarray
            The polynomial terms to be added directly to each multipole
        poly: np.ndarray
            The additive terms in the model not added to the multipoles, necessary for analytical marginalisation


Take the window effects into account.

        Parameters
        ----------
        pk_generated : np.ndarray
            The p(k) values generated at the window function input ks
        data : dict
            The data dictionary containing the window scale `w_scale`,
            transformation matrix `w_transform`, integral constraint `w_pk`
            and mask `w_mask`

        Returns
        -------
        pk_normalised : np.ndarray
            The transformed, corrected power spectrum
        mask : np.ndarray
            A boolean mask used for selecting the final data out of pk_normalised.
            Mask is not applied in this function because for the BAO extractor
            post processing we want to take the powers outside the mask into account
            and *then* mask.


Computes the power spectrum model using the Seo et. al., 2016 method

        Parameters
        ----------
        k : np.ndarray
            Array of (undilated) k-values to compute the model at.
        p : dict
            dictionary of parameter names to their values
        smooth : bool, optional
            Whether or not to generate a smooth model without the BAO feature

        Returns
        -------
        kprime : np.ndarray
            Wavenumbers of the computed pk
        pk0 : np.ndarray
            the model monopole interpolated to kprime.
        pk2 : np.ndarray
            the model quadrupole interpolated to kprime. Will be 'None' if the model is isotropic
        pk4 : np.ndarray
            the model hexadecapole interpolated to kprime. Will be 'None' if the model is isotropic
        poly: np.ndarray
            the additive terms in the model, necessary for analytical marginalisation


Computes the power spectrum model using the Beutler et. al., 2017 method

        Parameters
        ----------
        k : np.ndarray
            Array of (undilated) k-values to compute the model at.
        p : dict
            dictionary of parameter names to their values
        smooth : bool, optional
            Whether or not to generate a smooth model without the BAO feature

        Returns
        -------
        kprime : np.ndarray
            Wavenumbers of the computed pk
        pk0 : np.ndarray
            the model monopole interpolated to kprime.
        pk2 : np.ndarray
            the model quadrupole interpolated to kprime. Will be 'None' if the model is isotropic
        pk4 : np.ndarray
            the model hexadecapole interpolated to kprime. Will be 'None' if the model is isotropic
        poly: np.ndarray
            the additive terms in the model, necessary for analytical marginalisation


Computes the power spectrum model using the Chen et. al., 2019 propagator

        Parameters
        ----------
        k : np.ndarray
            Array of (undilated) k-values to compute the model at.
        p : dict
            dictionary of parameter names to their values
        smooth : bool, optional
            Whether or not to generate a smooth model without the BAO feature
        shape : bool, optional
            Whether or not to include shape marginalisation terms.
        dilate : bool, optional
            Whether or not to dilate the k-values of the model based on the values of alpha (and epsilon)

        Returns
        -------
        kprime : np.ndarray
            Wavenumbers of the computed pk
        pk0 : np.ndarray
            the model monopole interpolated to kprime.
        pk2 : np.ndarray
            the model quadrupole interpolated to kprime. Will be 'None' if the model is isotropic
        pk4 : np.ndarray
            the model hexadecapole interpolated to kprime. Will be 'None' if the model is isotropic


Computes the power spectrum model using the model from Noda et. al., 2019

        Parameters
        ----------
        k : np.ndarray
            Array of (undilated) k-values to compute the model at.
        p : dict
            dictionary of parameter names to their values
        smooth : bool, optional
            Whether or not to generate a smooth model without the BAO feature
        shape : bool, optional
            Whether or not to include shape marginalisation terms.
        dilate : bool, optional
            Whether or not to dilate the k-values of the model based on the values of alpha (and epsilon)

        Returns
        -------
        kprime : np.ndarray
            Wavenumbers of the computed pk
        pk0 : np.ndarray
            the model monopole interpolated to kprime.
        pk2 : np.ndarray
            the model quadrupole interpolated to kprime. Will be 'None' if the model is isotropic
        pk4 : np.ndarray
            the model hexadecapole interpolated to kprime. Will be 'None' if the model is isotropic


Computes the correlation function model using the Beutler et. al., 2017 power spectrum
            and 3 bias parameters and polynomial terms per multipole

        Parameters
        ----------
        dist : np.ndarray
            Array of distances in the correlation function to compute
        p : dict
            dictionary of parameter name to float value pairs
        smooth : bool, optional
            Whether or not to generate a smooth model without the BAO feature

        Returns
        -------
        sprime : np.ndarray
            distances of the computed xi
        xi : np.ndarray
            the model monopole, quadrupole and hexadecapole interpolated to sprime.
        poly: np.ndarray
            the additive terms in the model, necessary for analytical marginalisation


Converts the xi components to a full model but with 3 polynomial terms for each multipole

        Parameters
        ----------
        dist : np.ndarray
            Array of distances in the correlation function to compute
        p : dict
            dictionary of parameter name to float value pairs
        xi_comp : np.ndarray
            the model monopole, quadrupole and hexadecapole interpolated to sprime.

        Returns
        -------
        sprime : np.ndarray
            distances of the computed xi
        xi : np.ndarray
            the convert model monopole, quadrupole and hexadecapole interpolated to sprime.
        poly: np.ndarray
            the additive terms in the model, necessary for analytical marginalisation


Overwrites the camb template power spectrum with the given values. For instance, if you have a fixed template from a file


A function available for overriding that precomputes values that depend only on the outputs of CAMB.

        Parameters
        ----------
        camb : CambGenerator
            Stores the ks, pklin, etc
        om : float
            Value of Omega_m, which you can use to get the Camb ks, pklin and nonlinear pks
        h0 : float
            Value of h, which you can use as above

        Returns
        -------
        A dictionary mapping specific keywords to their computed values. Or None.


Scale parameter values to the unit hypercube. If you want other dists and nested sampling, overwrite this


Unscale from the unit hypercube to parameter values. If you want other dists and nested sampling, overwrite this.


Perform local optimisation to try and find the best fit of your model to the dataset loaded in.

        Parameters
        ----------
        tol : float, optional
            Optimisation tolerance

        Returns
        -------
        best_fit_params : dict
            A dictionary mapping parameter names to best fit values
        log_posterior : float
            The value of the best fit log posterior


np.interp function with linear extrapolation


        Linear interpolation of pk in log,log,
        taking care of extrapolation (also linear in log,log)
        and numerical precision


The Mellin transform of the spherical bessel transform.


Update the tilt for a particular nu. Assume low ring coordinates.


        Extrapolate function by evaluating a log-index of left & right side.

        From Chirag Modi's CLEFT code at
        https://github.com/modichirag/CLEFT/blob/master/qfuncpool.py

        The warning for divergent power laws on both ends is turned off. To turn back on uncomment lines 26-33.


    Computes the matter density at redshift based on the present day value.

    Assumes Flat LCDM cosmology, which is fine given this is also assumed in CambGenerator. Possible improvement
    could be to tabulate this using the CambGenerator so that it would be self consistent for non-LCDM cosmologies.

    :param omega_m: the matter density at the present day
    :param z: the redshift we want the matter density at
    :return: the matter density at redshift z


    Compute the E-function; the ratio of the Hubble parameter at redshift z to the Hubble-Lemaitre constant.

    Assumes Flat LCDM cosmology, which is fine given this is also assumed in CambGenerator. Would not be necessary if
    we tabulated Omega_m_z using the CambGenerator.

    :param omega_m: the matter density at the present day
    :param z: the redshift we want the E-function at
    :return: The E-function at redshift z given the matter density


Performs bilinear interpolation on the entire pk array


    Catches all exceptions raised in function

    Rise http exceptions like that:
    raise HTTPException(detail='Not found!', status_code=404)

    If excepted not http exception, return status is 500


Get the length of a halo's progenitors


Returns the rendered index page

    Returns
    -------
    ``flask.render_template`` obj
        The rendered template for the index page.


        This method is called when the plugin is stopped.
        It should perform any special clean up necessary to terminate
        the operation.  The GUI will be destroyed by the plugin manager
        so there is no need for the stop method to do that.
        This method may be called many times as the plugin is opened and
        closed for modal operations, and may be omitted if there is no
        special cleanup required when stopping.


Check if the passed arguments are valid for processing


Function to get different parameters of a population file


Method to create the plotting window and fill it with buttons.


Function to switch logarithm booleans


Test if pulsar is inside region bounded by survey.


Calculate whether pulsar is inside FWHM/2 of pointing position.
        Currently breaks as soon as it finds a match. !!!Could be a closer
        position further down the list!!!


Use numpy-foo to determine closest obs pointing


Calculate the S/N ratio of a given pulsar in the survey


Aperture array factor


Calculate the flux at this frequency


Calculate the flux assuming GPS spectrum shape, spindex===b


Calculate tsky from Haslam table, scale to survey frequency


Add scintillation effects and modify the pulsar's S/N


Modify pulsar flux (actually S/N)
        according to the modulation index


Calculate the degradation of SNR For a pulsar in a survey with no
        acceleration searching (Bagchi, Lorimer & Wolfe 2013


        Increment self.amount by 'add_ammount' or default to incrementing
        by 1, and then rebuild the bar string.


        Update self.amount with 'new_amount', and then rebuild the bar
        string.


        Figure new percent complete, and rebuild the bar string base on
        self.amount.


Calculate the flux of the pulsar


Calculate pulsar efficiency at 1400 MHz, L1400 / Edot


Return the Edot of the pulsar in erg / s


Evolve a pulsar through galactic potential


Calculate the X, Y, Z alactic coords for the pulsar.


Use NE2001 distance model.


Use Lyne, Manchester & Taylor distance model to compute DM.


Use NE2001 model to get the DISS scattering timescale


Convert l, b to RA, Dec using SLA fortran (should be faster).


Convert RA, Dec to l, b using SLA fortran.
    Be sure to return l in range -180 -> +180


Convert galactic xyz in kpc to l and b in degrees.


Convert galactic coords to Galactic XYZ.


Calculate bhat et al 2004 scattering timescale for freq in MHz.


Scale the scattering timescale from 1.4 GHz to frequency


    Calculate the angular distance (deg) between two
    points in galactic coordinates


Make spiral arms, as seen in Fuacher-Giguere & Kaspi 2006


Exponential distribution around origin, with scale height scale.


Read in tsky.ascii into a list from which temps can be retrieved


S/N ratio decrease in a standard pulsar search


S/N ratio decrease in an accel pulsar search


S/N ratio decrease in an accel & jerk pulsar search


Tauris and Manchester 1998 beaming fraction


Weltevrede & Johnston 2008 beaming model


    Karastergiou & Johnston 2007 beam model -
    Load the pre-run reesults


    Karastergiou & Johnston 2007 beam model - get width from pulsar
    parameters


Do the rvm calculation


Correct value x for rounding errors


        Join pops in poplist to this population object. Returns a new object

        Be aware that population properties such as distribution type etc will
        be retained ONLY for the original population model.


Write the population object to a file


Write population to an ascii file


        Make an object that can be plotted using wxView, based on the
        attributes of the pulsars in the population


Draw a value randomly from the specified power law


Draw a bin number form a home-made distribution
        (dist is a list of numbers per bin)


Get a birth veolocity for the pulsar


Pick an alignment angle for pulsar, depending on model chosen


Work out if the pulsar is beaming --- model-dependent


Equation 14 from  Ridley & Lorimer


Spindown model from Faucher-Giguere & Kaspi 2006


Equation 6 - Ridley & Lorimer 2010


Equation 3 - Ridley & Lorimer 2010


    Equations 9 and 10 in Ridley & Lorimer -
    due to Contopoulos & Spitkovsky 2006


    Eq 8 in Ridley & Lorimer - but it's the deathline from
    Bhattacharya et al 1992


Calculate flux assuming radiometer equation


Calculate the S/N ratio assuming radiometer equation


Returns the rest of the radiometer equation (aside from
        SNR/Flux


Loads in either a model from disk (popfile, cPickle),
       or pass in a model from memory (popmodel)


Write a survey results population to a binary file.


Run the surveys and detect the pulsars.


    Generate a population of pulsars.

    Keyword args:
    ngen -- the number of pulsars to generate (or detect)
    surveyList -- a list of surveys you want to use to try and detect
        the pulsars
    pDistType -- the pulsar period distribution model to use (def=lnorm)
    radialDistType -- radial distribution model
    electronModel -- mode to use for Galactic electron distribution
    pDistPars -- parameters to use for period distribution
    siDistPars -- parameters to use for spectral index distribution
    lumDistPars -- parameters to use for luminosity distribution
    radialDistPars -- parameters for radial distribution
    zscale -- if using exponential z height, set it here (in kpc)
    scindex -- spectral index of the scattering model
    gpsArgs -- add GPS-type spectrum sources
    doubleSpec -- add double-spectrum type sources
    nostdout -- (bool) switch off stdout


Picks a period at random from Dunc's
       distribution as mentioned in IAU
       (China 2012) proceedings


A model for MSP period distribution.


Returns a boolean indicating if the pulsar is beaming at Earth.


Calculate the opening angle of pulsar, and the beamwidth.
        Based on model outlined in Smits et al. 2009


Pick an inclination angle from 0-> 90 degrees.
        Based on model outlined in Smits et al. 2009


Read in the given file and make a dataobj


	Searches the given directory and its subdirectories for files with a
		.pvtt extension. Saves all the tables to a .npz file and if the pvtt files includes a none_coords.pvtt file it will eliminates duplicate nodes.

	Args:
		argv[0]: output file name

	Returns:
		nothing


    Create rectangular prism geometry

    Parameters
    ----------
    ds      : a three element array of floats
        the cell dimensions in meters
    len_s   : a three element array of floats
        the encompassing volume dimensions in meters

    Returns
    -------
    Geom    : a 3D numpy array of 0 zeros and ones
        The Geometry of the dog bone inside the array defined by 1s and 0s are empty space


    main, runs the script

    Parameters
    ----------
    NONE

    Returns
    -------
    NONE


    Creates the VTU File for a specified geometry

    Parameters
    ----------
    fname      : a string
        the vtu file name
    block_dim  : an array of float
        the dimensions of the block in meters
    ds         : an array of floats with the dimensions of each cell
    vol_frac   : target porosity volume fraction

    Returns
    -------
    NONE


Returns the trajectory of the test particle


        Aligns new FLT's to reference catalog.

        Parameters
        ----------
        self : object
            DashData object created from an individual IMA file.
        subtract_background : bool, optional
            If True, runs subtract_background_reads functions.
        align_method : string, optional
            Defines alignment method to be used. Default is None (input files
            will align to each other).
        ref_catalog : cat file, optional
            Defines reference image that will be referenced for CATALOG
            alignment method.
        create_diff_source_lists : bool, optional
            Specifies whether or not to create a segmentation image and source
            list from the difference files
        updatehdr : bool, optional
            Specifies whether to update the headers after aligning during
            TweakReg. Default is True.
        updatewcs : bool, optional
            Specifies whether to update the WCS after aligning during TweakReg.
            Default is True.
        wcsname : str, optional (as long as name you choose doesn't already exist)
            Specifies name of WCS. Default is 'DASH'
        threshold : float, optional
        cw : float, optional
        searchrad : float, optional
            Radius (in pixels) that TweakReg will search around sources to find
            matches. Default is 20 pixels.
        astrodriz : bool, optional
            Specifies whether to drizzle images together using Astrodrizzle.
            Default is True.
        cat_file : str, optional
            Name of catfile to be used to align sources in TweakReg. Default is
            the catfile created by setting create_diff_source_lists to True,
            catalogs/diff_catfile.cat
        drz_output : str, optional
            Name of output file after drizzling using AstroDrizzle. Default is
            the root name of the original IMA.

        Outputs
        -------
        Shifts file : txt file
            File containing shifts during TweakReg
        WCS Shifts file : fits file
            File containing WCS shifts during TweakReg
        Residual plot : png
            Plot showing residuals from TweakReg alignment
        Vector plot : png
            Plot showing vector poitnings from TweakReg alignment
        Aligned FLT's : fits file
            Same diff files created in split_ima that have been aligned using TweakReg
        Drizzled Image : fits file
            Setting astrodriz to True will output a drizzled image form a single
            exposure (produced only if astrodriz is set to True)


        Creates segmentation map, from original FLT file, that is used in
        background subtraction and to fix cosmic rays.

        Parameters
        ----------
        self : object
            DashData object created from an individual IMA file.

        Output
        ------
        Segmentation Image : fits file
            Segmentation map
        Source List : .dat file
            List of sources and their properties


        Creates segmentation image and source list from difference files.

        Parameters
        ----------
        self : object
            DashData object created from an individual IMA file
        cat_images : list, str
            List of difference files with full path name
        remove_column_names : bool
            Specifies whether to remove the header from the source lists so
            TweakReg can read them
        nsigma : float
        sig : float
        npixels : float

        Outputs
        -------
        Segmentation Image : fits file
            Segmentation map
        Source List : .dat file
            List of sources and their properties


        Resets cosmic rays within the seg maps of objects and uses L.A.Cosmic
        to find them again.

        Parameters
        ----------
        self : object
            DashData object created from an individual IMA file.
        rm_custom : bool
            Specifies whether or not the user would like to remove custom flags
            within the boundaries of sources, as defined by the segmentation map
            created from the original FLT.
        flag : int
            Specifies flag the user would like the remove within the boundaries
            of sources.
        lacosmic_param : dic
            Dictionary of the L.A.Cosmic parameters that users may want to specify.
            If not set, then presets are used.

        Output
        ------
        Fixed for cosmic rays diff files : fits
            Same diff files created in split_ima that have now been corrected
            for cosmic ray errors.


        Makes a new association table for the reads extracted from a given IMA.
        Parameters
        ----------
        self : object
            DashData object created from an individual IMA file.
        Outputs
        ----------
        ASN files : fits file
            Fits file formatted as an association file that holds
            the names of the difference files created by split_ima
            and the root name of the individual IMA file.


        Will create individual files for the difference between
        adjacent reads of a IMA file. Will also add more attributes
        to the DashData object.
        Parameters
        ----------
        self : object
            DashData object created from an individual IMA file.
        Outputs
        ----------
        N files : fits files
            Fits files of the difference between adjacent IMA reads.


        Performs median background subtraction for each individual difference file.
        Uses the DRZ and SEG images produced in FLT background subtraction.
        Parameters
        ----------
        self : object
            DashData object created from an individual IMA file.
        subtract : bool
            Does not subtract the background by default, but still writes it to
            the header.
            Set to True to subtract background.
        reset_stars_dq : bool
            Set to True to reset cosmic rays within objects to 0 because the
            centers of stars are flagged.
        Outputs
        -------
        Background Subtracted N files : fits files
            Fits files of the difference between adjacent IMA reads that have
            been background subtracted.


    Runs entire DashData pipeline under a single function.

    Parameters
    ----------
    ima_file_name : str
        File name of ima file.
    flt_file_name : str
        File name of FLT file.
    align_method : str, optional
        Method to align difference files using TweakReg. Default is None, which
        aligns reads to the first read.
        Setting align_method equal to 'CATALOG' will align the reads to a catalog.
    ref_catalog : str, optional
        Catalog to be aligned to if using CATALOG align method.
    drz_output : str, optional
        Name to call final drizzled output image ( + '_drz_sci.fits' ).
        Default is root_name + '_drz_sci.fits'.
    subtract_background : bool
        Determines whether background is subtracted or not during align
        function.
        Default is False since during this main function,
        the background is subtracted separately.
    wcsname : str
        Name for WCS during TweakReg.
    threshold : float
        qwerty
    cw : float
        qwerty
    updatehdr : bool
        Determines whether to update headers during TweakReg. Default is True.
    updatewcs : bool
        Determines whether to update WCS information during TweakReg. Default
        is True.
    searchrad : float
        qwerty
    astrodriz : bool
        Determines whether or not to run astrodrizzle. Default is True.

    Outputs
    -------
    N files : fits files
        Fits files of the difference between adjacent IMA reads.
    N files : fits files
        Fits files of the difference between adjacent IMA reads.
    Shifts file : txt file
        File containing shifts during TweakReg
    WCS Shifts file : fits filr
        File containing WCS shifts during TweakReg
    Drizzled science image : fits
        Drizzled science image from one exposure reduced using the DASH
        pipeline.
    Weighted science image : fits
        Weighted drizzled science image from one exposure reduced using the
        DASH pipeline.


Return checksums for experiment in exp_dir.


Filter out and return checksums from output.


Filter out and return checksums from dates.


Run the test experiment in exp_dir


Increment the forcing datetime by dt.


Plot the power spectrum measurements for a given
        experiment


Returns a list of the different experiments for which we
        have results given the input cltype


Sets the xlabel of the plot


Generate a default BB plot with most of the current measurements plotted


Generate a default TT plot


Generate a default TE plot


Generate a default EE plot


Generate a default dd plot


Adding in an upper bound for bins that might need it. Some experiments report
        measurements that are not very significant and people might want to plot these as
        upper limits.


	Writes the "NRM matrix" that gets pseudo-inverterd to provide
	(arbitrarily constrained) zero-mean phases of the holes.

	makeA taken verbatim from Anand's pseudoinverse.py

	 input: nh - number of holes in NR mask
	 input: verbose - True or False
	 output: A matrix, nh columns, nh(nh-1)/2 rows  (eg 21 for nh=7)

	Ax = b  where x are the nh hole phases, b the nh(nh-1)/2 fringe phases,
	and A the NRM matrix

	Solve for the hole phases:
		Apinv = np.linalg.pinv(A)
		Solution for unknown x's:
		x = np.dot(Apinv, b)

	Following Noah Gamper's convention of fringe phases,
	for holes 'a b c d e f g', rows of A are

	    (-1 +1  0  0  ...)
	    ( 0 -1 +1  0  ...)

	which is implemented in makeA() as:
		matrixA[row,h2] = -1
		matrixA[row,h1] = +1

	To change the convention just reverse the signs of the 'ones'.

	When tested against Alex'' NRM_Model.py "piston_phase" text output of fringe phases,
	these signs appear to be correct - anand@stsci.edu 12 Nov 2014

	anand@stsci.edu  29 Aug 2014


	As above, write the "kernel matrix" that converts fringe phases
	to closure phases. This can be psuedo-inverted to provide a
	subset of "calibrated" fringe phases (hole-based noise removed)

	 input: nh - number of holes in NR mask
	 input: verbose - True or False
	 output: L matrix, nh(nh-1)/2 columns, comb(nh, 3) rows  (eg 35 for nh=7)

	Kx = b, where:
		- x are the nh(nh-1)/2 calibrated fringe phases
		- b the comb(nh, 3) closure phases,
	and K the kernel matrix

	Solve for the "calibrated" phases:
		Kpinv = np.linalg.pinv(K)
		Solution for unknown x's:
		x = np.dot(Kpinv, b)

	Following the convention of fringe phase ordering above, which should look like:
	h12, h13, h14, ..., h23, h24, ....
	rows of K should look like:

	    (+1 -1  0  0  0  0  0  0 +1 ...) e.g., h12 - h13 + h23
	    (+1 +1  0 +1  ...)

	which is implemented in makeK() as:
		matrixK[n_cp, f12] = +1
		matrixK[n_cp, f13] = -1
		matrixK[n_cp, f23] = +1

	need to define the row selectors
	 k is a list that looks like [9, 9+8, 9+8+7, 9+8+7+6, 9+8+7+6+5, ...]
	 -----up to nh*(nh-1)/2
	 i is a list that looks like [0,9, 9+8, 9+8+7, 9+8+7+6, 9+8+7+6+5, ...]
	 -----up to nh*(nh-1)/2 -1
	because there are 9 fringe phases per single hole (decreasing by one to avoid repeating)
	hope that helps explain this!

	agreenba@pha.jhu.edu  22 Aug 2015


	Calculate Zernike polynomial (m, n) given a grid of radial
	coordinates rho and azimuthal coordinates theta.
	Adapted from Werkhoven, modified to the orthonormal basis from Noll 1976


radial component of zernike (m,n), given radial coordinates rho


find a way to do single indexing for zernikes
	   can be described by the zernike pyramid.
	http://www.opt.indiana.edu/VSG/Library/VSIA/VSIA-2000_taskforce/TOPS4_2.html


        As described at top of this file
        signal in each plane is complex


	Calculate the radial component of Zernike polynomial (m, n)
	given a grid of radial coordinates rho.

	>>> zernike_rad(3, 3, 0.333)
	0.036926037000000009
	>>> zernike_rad(1, 3, 0.333)
	-0.55522188900000002
	>>> zernike_rad(3, 5, 0.12345)
	-0.007382104685237683


	Calculate Zernike polynomial (m, n) given a grid of radial
	coordinates rho and azimuthal coordinates phi.

	>>> zernike(3,5, 0.12345, 1.0)
	0.0073082282475042991
	>>> zernike(1, 3, 0.333, 5.0)
	-0.15749545445076085


	Calculate Zernike polynomial with Noll coordinate j given a grid of radial
	coordinates rho and azimuthal coordinates phi.

	>>> zernikel(0, 0.12345, 0.231)
	1.0
	>>> zernikel(1, 0.12345, 0.231)
	0.028264010304937772
	>>> zernikel(6, 0.12345, 0.231)
	0.0012019069816780774


		Input: surface: input surface to be fit (2D array)
		Output: zcoeffs: 1d vector of coefficients of the fit (self.nzern in length)
		Output: rec_wf: the 'recovered wavefront' - i.e. the fitted zernikes, in same array size as surface
		Output: res_wf: surface - rec_wf, i.e. the residual error in the fit


Generate a zero mean aberration (w/o piston) in radians


OD will be set to half the array size to match defaults above


    Check if the galaxies are there and then remove the image if its
    not there.

    If more than 1/3 of the pixels are duds we don't want that gal.


        Returns a reaction in TeX format.

        Returns
        -------
        str
            TeX formated reaction string.


Read a network from a file.

        This function reads a chemistry network from a file and
        creates a network instance. Supported formats are chm, osu and
        kida.

        Parameters
        ----------
        f : file
            Network file
        fileformat : str
            Network file format ("chm", "osu" or "kida")

        Returns
        -------
        `network_reader`
            Network


Read a network in the chm format.

            Parameters
            ----------
            f : file
                Network file

            Returns
            -------
            `network_reader`
                Network


Read a network in the osu format.

            Parameters
            ----------
            f : file
                Network file

            Returns
            -------
            `network_reader`
                Network


Format a species in osu format to chm format.


Read a network in the kida format.

            Parameters
            ----------
            f : file
                Network file

            Returns
            -------
            `network_reader`
                Network


Format a species in kida format to chm format.


Write network in a file.

        Parameters
        ----------

        f : file
            Network file handle
        renumber : bool, optional
            Renumber reactions (default False)


Find reactions with the same reaction number.

        Returns
        -------
        list of str
            List of duplicated reaction_numbers.


Find duplicate reactions.

        Returns
        -------
        list of int
            List of reaction_numbers of duplicated reactions.


Read chem_file and source_file attributes from an hdf5 output file

    Parameters
    ----------
    filename : str
        Path to output file.

    Returns
    -------
    chemfile : str
        chem_file attribute
    sourcefile : str
        source_file attribute


Returns a list of species that are available in an hdf5 file

    Parameters
    ----------
    filename : str
        Path to output file.

    Returns
    -------
    list if str
        Species list


Read abundances for a specific specie from an hdf5 output file and
    return arrays of time and abundances

    Parameters
    ----------
    filename : str
        Path to the output file
    specie : str
        Name of specie to read abundance of

    Returns
    -------
    timesteps : list of float
        List of timesteps
    abundance : list of float
        List of abundances


Read a rout from a hdf5 output file and return arrays of time, shell number, formation/destruction rates.

    Parameters
    ----------
    filename : str
        Path to the output file.
    specie : str
        Name of specie to read route of.

    Returns
    -------
    timesteps : list of float
        List of timesteps.
    shells : list of float
        List of shell numbers.
    formation_reac : list of `reaction`
        List of formation reactions.
    formation_rate : list of float
        List of formation rates.
    destruction_reac : list of `reaction`
        List of destruction reactions.
    destruction_rate : list of float
        List of destruction rates.


Convert a hdf5 output file specific species to .abun and .rout legacy format.

    Parameters
    ----------
    filename : str
        Path to the output file
    species : str
        Name of specie to read abundance and route of


Read an abund file and return arrays of time and abundances.

    Parameters
    ----------
    filename : str
        Path to the abund file.

    Returns
    -------
    timesteps : list of floats
        List of timesteps
    abundances : list of floats
        List of abundances


Read a rout file and return arrays of time, cell number,
    formation/destruction rates

    Parameters
    ----------
    filename : str
        Path to the output file.

    Returns
    -------
    timesteps : list of float
        List of timesteps.
    shells : list of float
        List of shell numbers.
    formation_reac : list of `reaction`
        List of formation reactions.
    formation_rate : list of float
        List of formation rates.
    destruction_reac : list of `reaction`
        List of destruction reactions.
    destruction_rate : list of float
        List of destruction rates.


Returns a species in TeX format

    Parameters
    ----------
    species : str
        Species name

    Returns
    -------
    str
        TeX formated species string


        Solve chemical reaction for a certain time

        Arguments
        ---------
        time : float
           Time to solve the system at
        new_cell : `cell`
           Cell class to use in solver, optionnal


Create the UCE-match database


enter matched loci in database


check for contigs that match more than 1 UCE locus


Check for UCE probes that match more than one contig


Write some nice output to stdout


    Value of the event-dependent terms in the SNR calculation.
    Needs additional factors dependent on integration/maximisation over inclination.

    `chirp_mass` expected in kg, and `luminosity_distance` in m.

    All quantities must be in Solar System Barycentre reference frame.

    If `use_cache` is True, integrals over frequencies are interpolated from a
    precomputed table. Otherwise, they are computed on the fly (slower!).

    If `numerical` is set to a function of frequency containing the numerical interpolated
    "geometrical" response, this one is used and cache is ignored (slower, could be
    implemented with cache).


    Approximate SNR, averaged over inclination.

    `chirp_mass` expected in kg, and `luminosity_distance` in m.

    All quantities must be in Solar System Barycentre reference frame.

    If `use_cache` is True, integrals over frequencies are interpolated from a
    precomputed table. Otherwise, they are computed on the fly (slower, and not
    vectorised!).

    If `numerical` is set to a function of frequency containing the numerical interpolated
    "geometrical" response, this one is used and cache is ignored (slower, could be
    implemented with cache).


    Approximate SNR, maximised over inclination, i.e. usually overestimated.

    Useful for conservative catalogues, in which events with actual SNR higher than a
    given one are less likely to be missed if estimated this way (but events with actually
    lower SNR will be included too).

    `chirp_mass` expected in kg, and `luminosity_distance` in m.

    All quantities must be in Solar System Barycentre reference frame.

    If `use_cache` is True, integrals over frequencies are interpolated from a
    precomputed table. Otherwise, they are computed on the fly (slower, and not
    vectorised!).


Power-law component of mass population.


Assumes won't get any mprime<=0 value!


Non-normalised m1 pdf.


Normalised m1 pdf.


    Generate N draws from the m1 mass function, sampling from the population mixture and
    applying smoothing via rejection sampling.

    Slow but more precise method.


Generate N draws from the m1 mass function using inverse CDF transform sampling.


Normalised q|m1 pdf, where q=m2/m1.


Normalised joint prior for m1, q.


Normalised joint prior for m1, m2.


    Draws m2 conditioned to a given m1 sample, drawing from the power law and rejecting
    with the smoothing function.


    drop-in replacement for the yaml dumper with some tweaks:

    - Order is preserved in dictionaries and other mappings
    - Tuples are dumped as lists
    - Numpy arrays (``numpy.ndarray``) are dumped as lists
    - Numpy scalars are dumped as numbers, preserving type


    Prepares an interpolator for invCDF sampling.

    ``x`` samples are assumed sorted.

    Integrates the pdf ``pdf_func`` using quad. Use ``pdf_args`` to pass arguments to it
    at integration.

    Uses ``scipy.interpolate.splrep`` to create an interpolator. Use ``splrep_kwargs`` to
    pass keyword arguments to it, e.g. ``{"k": 1}``.

    Returns a tuple of the the CDF samples and the interpolator.


Sample N events. Returns amplitude1, amplitude2, cos1, cos2.


Load catalogue in LISA format, and converts to source reference frame.


        Generates redshifts and masses. And the rest of the parameters if `lazy=True`.

        All quantities generated in source reference frame.


        Adds the derived quantities `FinalFrequency` and `InBandTime`.

        If present, they are overwritten when `force=True` (default `False`).


Generates the rest of the parameters: spins, initial freq, etc.


Chirp mass of individual events (source reference frame) in Msun units.


        Save the population to a pair of files .yaml and .h5, containing respectively
        the parameters of the population and the population events.

        If `LISA=True`, it is saved in LISACode's format (LISACode needed).


Save into LISACode format.


Returns a copy of the data in the detector reference frame.


        Adds a column `snr_avg_inclination` with an approximate calculation of the SNR,
        averaging over possible inclinations of the given event.


        Adds a column `snr_max_inclination` with an approximate calculation of the SNR,
        maximising over possible inclinations of the given event.


        Computes the average (realisation-independent) background as a numerical
        integration of the number density with the current population paramters.

        Returns unitless characteristic strain as a function of frequency (in Hz)
        that goes like f**(-4/3)

        Make `omega2_units=True` (default: False) to return the background in Omega h^2
        units, and in this case the frequency dependency is f**2/3.

        Use ``z_max`` to override the maximum redshift used for the integral, and thus
        get the actual value. The recommended value is ``z_max=5`` for a ``<1%``
        error with respect to ``z_max=inf``.

        ``epsabs`` and ``epsrel`` are precision arguments of ``scipy.integrate.[X]quad``.
        A value of ``1e-4`` (default) for both is enough to make the numerical error
        larger than the population realisation error (~0.5%), though larger values may be
        enough.

        Result is cached for subsequent calls.
        Pass ``use_cached=False`` (default: ``True``) to force recomputation.


        Computes the expected background from the sum of individual strains.

        Returns unitless characteristic strain as a function of frequency (in Hz)
        that goes like f**(-4/3)

        Make `omega2_units=True` (default: False) to return the background in Omega h^2
        units, and in this case the frequency dependency is f**2/3.

        Result is cached for subsequent calls.
        Pass ``use_cached=False`` (default: ``True``) to force recomputation.

        ``extra_factor`` multiplies the integrand, for tests. It can be an array
        with one element per member of the population. Combine with ``use_cached=False``!


        Computes the expected background from the sum of individual strains, binned over
        frequencies with bin width `delta_f` (e.g. the inverse
        of the chunk length, ~11 days for LISA).

        Assigns to each event its initial frequency if ``use="in"`` (default), or its
        final frequency if ``use="out"``, computed for an observation time in years of
        `T_obs_yr` (default: 4 years).

        Ignoring drifting is a good approximation at low frequencies only, for the
        purpose of computing the gaussian f^(-4/3) part of the background.

        Returns a tuple of (frequency binning, unitless strain).

        Make `omega2_units=True` (default: False) to return the background in Omega h^2
        units.

        The frequencies are the left-most ones per bin, and the left and rightmost bins
        correspond to the min/max frequency of the events in the population.

        To sum a sub-sample of the population, give subsample > 1 (int, default 1).


        Plot distribution for (pairs of) source parameters.

        Use ``frame="source"`` (default) or ``"detector"`` to choose the reference frame
        of the quantities plotted (where applicable).

        If two parameters are specified, a 2d histogram will be produced, unless a
        ``color_by`` parameter is specified, in which case it will produce a scatter plot.


    Leading-order (Newtonian) frequency drifting.

    All quantities in SI units.

    Initial and final observed frequencies are the result of evaluating for
    t=0 and t=min(t_coal, t_obs) (clipped to the experimental bandwidth).

    Eq. (11a) from https://arxiv.org/abs/1806.10734,
    or integrating df/dr from eq. (4.196) in Maggiore, for f=0 at t=t_coal.


    Leading-order (Newtonian) inverse frequency drifting.

    All quantities in SI units.

    Initial and final observed frequencies are defined respectively at t=0 and
    t=min(t_coal, t_obs) (clipped to the experimental bandwidth).

    From Eq. (11a) from https://arxiv.org/abs/1806.10734,
    or integrating df/dr from eq. (4.196) in Maggiore, for f=0 at t=t_coal.


Merger rate in GPc^-3 yr^-1 units.


    Redshift-dependent term for an evolving merger rate following Madau & Dickinson
    1403.0007.

    Rising power ``r`` is negative, and declining power ``d`` is positive, since they are
    understood towards smaller ``z``.


    Redshift-dependent term for an evolving merger rate following Madau & Dickinson
    1403.0007.

    For negative ``d``, turns into a simple power law.


    Redshift-dependent merger rate following the SFR of Madau & Dickinson 1403.0007.

    Rising power ``r`` is negative, and declining power ``d`` is positive, since they are
    understood towards smaller ``z``.

    If ``safe=True`` (default), negative ``d`` values are allowed, and it turns into a
    simple power law.

    ``z_0`` is the redshift at which the pivot rate ``R_0`` is defined.

    For the position of the peak, one can specify either the actual position ``z_peak``,
    or the divisor ``c`` of the ``(1+z)`` term in the denominator (written sometimes as
    ``(1 + z_peak)``, though is not the actual peak position).


    Redshift-dependent power-law merger rate with power ``p``.

    ``z_0`` is the redshift at which the pivot rate ``R_0`` is defined.


Number density of events per second (in detector frame) with respect to z.


    Average total number of events. Simulate realisation sizes with

        import scipy.stats as stats
        n_avg = avg_n_events(...)
        n_realisation = stats.poisson(n_avg).rvs()

    The standard deviation is `sqrt(avg_n_events)`.


    Draws a random number of events for a population,  generated during time `T_yr` (in
    years, in detector frame) in the redshift range `z_range`.


    Generate redshift for events during time `T_yr` (in years, in detector frame) in the
    redshift range `z_range`.

    Use `Nsamples` to override the number of samples generated (for testing only!
    it will not be consistent in general with the rest of parameters).


Friedman eq. for evolution of H. Returns units of given `H_0`.


    Physical distance travelled by photon received with z:

    ds^2 = 0 --> dr = c dt / a -->
    --> r = c int_{a_emmited}^{a_received=a_0=1} H^-1 da / a^2 = c int_0^z dz / H

    Returns "units of 1/H", i.e. Mpc if H given in units of Km/(s*MPc) (default).


    Physical luminosity distance travelled by photon received with z, equals
    (1 + z) times the physical comoving distance.

    Returns units of Mpc, assuming H in units of Km/(s*MPc)


    Physical volume of comoving volume element within distance to redshift:

    4 / 3 pi r^3

    Returns units of Mpc^3


    (d/dz) of physical volume of comoving volume element within distance to redshift:

    (d/dz) 4 / 3 pi r^3

    Returns units of Mpc^3


Produces a warning if z_max used for background computation is too small.


    Single-event averaged characteristic strain squared at f=1Hz.

    Returns strain in units of s^(-4/3). To be multiplied by f^(-4/3)
    (freq in detector reference frame) to get unitless characteristic strain.

    Masses (in kg) and distances (in m) are expected in source reference frame.
    The generation time ``T_gen`` should be in detector frame and in sec.

    The sum of the values returned by this function for a full population is the Monte
    Carlo version of `char_strain_sq_numerical`.


Product of number density times mass probability density function.


    Characteristic strain squared a at f=1Hz obtained by numerical integration.

    Masses are expected in source reference frame.

    Returns strain in units of s^(-4/3). To be multiplied by f^(-4/3)
    (freq in detector reference frame) to get unitless characteristic strain.

    ``epsabs`` and ``epsrel`` are precision arguments of ``scipy.integrate.[X]quad``.
    A value of ``1e-4`` (default) for both is enough to make the numerical error larger
    than the population realisation error (~0.5%), though larger values may be enough. For
    smaller values, ``char_strain_sq_numerical_triple`` is faster, though less accurate
    (~0.2% undervalued).

    If ``return_terms=True`` (default: ``False``), returns a tuple containing the redshift
    and mass terms separately.


    Computes the redshift part of the background integral, in SI units:

        C * int R(z) H(z)**-1 * (1 + z)**(-4/3)

    where C is the prefactor

        4/3 / np.pi**(1 / 3) * G**(5/3) / c**2

    See ``char_strain_sq_numerical`` for full computation and more documentation.


    Computes the mass part of the background integral, in SI units:

        int dm1 dm2 p(m1, m2) * chirp_mass(m1, m2)**(5/3)

    See ``char_strain_sq_numerical`` for full computation and more documentation.


    Returns unitless individual strain squared at frequency f. Expects source reference
    frame and SI units for all quantities.


    Converts unitless characteristic strain squared to Omega h-squared units:

    :math:`Omega h^2 = 2 pi^2 / 3 / (H0/h)^2 f^2 * h_char^2(f)


    Converts Omega h-squared to unitless characteristic strain squared units:

    :math:`Omega h^2 = 2 pi^2 / 3 / (H0/h)^2 f^2 * h_char^2(f)


Creates output folder if it does not exist.


    Computes the MC-summed background for a single population, without retaining the
    events in memory.

    Returns the characteristic strain squared (unitless) at f=1Hz.


 Date Expand. Expands the date from a two digit year to
        a four digit year. Uses 50 as a split off between the
        1900's and 2000's, where n>50 is assumed to be in the
        1900's.

    Parameters
    ==========
    dat : str
        The date given as a string in format YYMMDD.

    Returns
    =======
    Epoch : str
        The date with the four year format (YYYYMMDD)


 Sort the TLEs into date order, expanding the date code
        to account for the century boundary

    Parameters
    ==========
    tle : list
        Two line element.

    Returns
    =======
    TLEs : list
        Sorted TLE's.


 Finds the TLE's from given files.

    Parameters
    ==========
    args : list
        List of all files (str's) for processing multiple files.
    kwargs : dict
        Key word arguments. Used for setting optional params.
        Defaults used if missing.
        Defaults:(CommonName='', SatelliteNumber='', IntDesignator='',
                  ParseMethod=ParseMethods['None'], OutputFile='',
                  DumpToFile=False, PurgeDuplicates=False, Verbose=None)

    Returns
    =======
    t[2] : str
        1st Line from the first TLE in the sorted list.
    t[0] : str
        2nd Line from the first TLE in the sorted list.
    t[1] : str
        0th Line (Sat name and info) from the first TLE in the sorted list.


 Finds the path for the 'name'.

    Parameters
    ==========
    path : str
        path of the file
    name : str
        name of the file or directory being searched for

    Returns
    =======
    path : str
        The path 'name' is found in (excludes 'name' in the string)


 Sets up the option parser.

    Returns
    =======
    parser : OptionParser
        A configured OptionParser object.


 Creates a neatly formatted Ephem text file.

    Parameters
    ==========
    epochs : list or spacepy.time.Ticktock
        List of Ticktock objects (or just one) with times.
    lat : list
        List of Latitudes for each epoch.
    lon : list
        List of Longitudes for each epoch.
    rad : list
        List of radii for each epoch (in Re).
    options : optparse.Values
        Organized options from the command line.

    Returns
    =======
    None


 Generator that increments a datetime object by one day.

        Parameters
        ==========
        startval : datetime
            Starting date.

        Returns
        =======
        None


 Takes input iterable of datetimes and splits into a list
        of datetimes by month.

    Parameters
    ==========
    inputiter : list
        List of spacepy.time.Ticktock objects.

    Returns
    =======
    outlist : list
        A two dimensional list -- list containing monthly-lists of
        Ticktock objects.


 Given bird (e.g. 'ns41'), mission (GPS) and cadence
        (in minutes) make header for Ephm txt files.

    Parameters
    ==========
    bird : str
        The bird/satellite.
    mission :
        Mission name for the INFO field.
    cadence :
        Cadence/frequency of information; placed at the end of the INFO field.
    date :
        Date of the information.

    Returns
    =======
    hline : list
        Header for Ephem txt files.


 Wrapper for multiprocessing.

    Parameters
    ==========
    inputs : list
        Contains parameters for this function (for multi-processing).
        Should contain epochs, TLEpath, and options, in respective order.

    Returns
    =======
    None


    Easy wrapper to just return values without having to create an instance of
    Lgm_T89c.

    All input parameters can be either their type or a list of the that type, all
    inputs must be the same length

    Parameters
    ----------
    pos : list
        3-element list of the position to do the calculation
    time : datetime
        date and time of when to do the calculation
    Kp : int
        Kp value for the calculation
    coord_system : str, optional
        the coordinate system of the position, default=GSM
    INTERNAL_MODEL : str, optional
        the internal magnetic field model to use, default=LGM_IGRF

    Returns
    -------
    out : list
        Magnetic field vector in GSM coordinates in nT

    Examples
    --------
    >>> from lgmpy import Lgm_T89c
    >>> import datetime
    >>> Lgm_T89c.T89c([1,2,3], datetime.datetime(1999, 1, 16, 12, 34, 12), 3)
    [-509.297442..., -619.8167352..., -426.193633024...]

    See Also
    --------
    Lgm_T89c.Lgm_T89c


    code to return a simple measure of L
    Inputs:
    - GSM position of northern most point (from Closed_Field)


    Function to see if a field line is closed

    Either MagEphem or pos and date must be specified

    Parameters
    ----------
    MagEphem : Lgm_MagEphemInfo, optional
        If a populated Lgm_MagEphemInfo class is passed in the data is pulled
        from it
    pos : list, optional
        3-element list of the position in system coord_system
    date : datetime, optional
        date and time of the calculation
    height : float, optional
        height above the earth to consider a particle lost [km], default=100
    tol1 : float, optional
        TODO what do I set?  default=0.01
    tol2 : float, optional
        TODO what do I set?  default=1e-7
    bfield : str, optional
        The magnetic field model to use, default=Lgm_B_T89
    Kp : int, optional
        Kp index for the calculation, default=2
    coord_system : str
        the coordinate system of the input position, default=GSM
    extended_out : bool
        switch on extended vs regular output, see examples for details,
        default=False

    Returns
    -------
    out : str
        a string with the open of closed value for the input
            - LGM_OPEN_IMF
            - LGM_CLOSED
            - LGM_OPEN_N_LOBE
            - LGM_OPEN_S_LOBE
            - LGM_INSIDE_EARTH
            - LGM_TARGET_HEIGHT_UNREACHABLE

    Examples
    --------
    >>> from lgmpy import Closed_Field
    >>> import datetime
    >>> Closed_Field([3,1,0], datetime.datetime(2000, 12, 3))
    'LGM_CLOSED'
    >>> Closed_Field([6,1,12], datetime.datetime(2000, 12, 3))
    'LGM_OPEN_IMF'
    >>> Closed_Field([-16,1,5], datetime.datetime(2000, 12, 3))
    'LGM_OPEN_N_LOBE'


    Easy wrapper to just return values without having to create an instance of
    Lgm_TS04.

    All input parameters can be either their type or a list of the that type, all
    inputs must be the same length

    Parameters
    ----------
    pos : list
        3-element list of the position to do the calculation
    time : datetime
        date and time of when to do the calculation
    Kp : int
        Kp value for the calculation
    coord_system : str, optional
        the coordinate system of the position, default=GSM
    INTERNAL_MODEL : str, optional
        the internal magnetic field model to use, default=LGM_IGRF

    Returns
    -------
    out : list
        Magnetic field vector in GSM coordinates in nT

    Examples
    --------
    >>> from lgmpy import Lgm_T89
    >>> import datetime
    >>> Lgm_T89.T89([1,2,3], datetime.datetime(1999, 1, 16, 12, 34, 12), 3)
    [-509.297442..., -619.8167352..., -426.193633024...]

    See Also
    --------
    Lgm_T89.Lgm_T89


    Function that does the conversion

    .. warning::

        This function is not called by the user

    Parameters
    ==========
    pos_in : Lgm_Vector
        the input position to convert
    to_str : str
        a string giving the acronym for the output coordinate system
    cdict : dict
        the coordinate transform dictionary
    cTrans : Lgm_CTrans
        the Lgm_CTrans object used in the conversion

    Returns
    =======
    out : Lgm_Vector
        vector of the new position


    Convert coordinates between almost any system using LanlGeoMag

    Parameters
    ----------
    position : list
        a three element vector of positions in input coord system
    time : datetime
        a datimetime object representing the time at the desired conversion
    system_in : str
        a string giving the acronym for the input coordinate system
    system_out : str
        a string giving the acronym for the desired output coordinate system
    de_eph : bool or int (optional)
        a boolean stating whether JPL DE421 is to be used for Sun, etc.

    Returns
    -------
    out : list
        3-element list of the converted coordinate

    Examples
    --------
    >>> from lgmpy import magcoords
    >>> import datetime
    >>> magcoords.coordTrans([-4,0,0], datetime.datetime(2009,1,1),'SM','GSM')
    [-3.60802691..., 2.5673907444...e-16, -1.72688788616...]
    >>> magcoords.coordTrans([-3.608026916281573, 2.5673907444456745e-16, -1.7268878861662329], datetime.datetime(2009,1,1),'GSM','SM')
    [-3.99999999..., 4.0592529337...e-16, 8.8817841970...3e-16]

    TODO
    ----
    extend interface to get necessary args from a MagModel or cTrans structure


    Function to return the L-value of a position using either McIlwain or Hilton
    approximation

    Parameters
    ==========
    pos : list
        3-element position int he specified coord_system
    time : datetime
        date and time for the calculation
    alpha : float, optional
        the pitch angle for the L calculation, default=90
    Bfield : str, optional
        the magnetic field model to use, default=Lgm_B_T89
    method : str, optional
        the L-value formula to use, McIlwain or Hilton, default=Hilton
    Kp : int
        Kp index value for the calculation
    coord_system : str
        the input coordinate system, default=GSM
    extended_out : bool
        keyword specifying short or extended output, default=False

    Returns
    =======
    out : dict
        dictionary of the values, see examples for documentation of dictionary

    Examples
    ========
    >>> from lgmpy import magcoords
    >>> import datetime
    >>> magcoords.Lvalue([3, 0, 1], datetime.datetime(2000, 1, 1), extended_out=False)
    {'I': 0.2434969602..., 'L': 3.195481841...}

    The ``extended_out=False`` output is:
        - I : I value at the given point
        - L : L value at the given point

    >>> from lgmpy import magcoords
    >>> import datetime
    >>> magcoords.Lvalue([3, 0, 1], datetime.datetime(2000, 1, 1), extended_out=True)
    {'Blocal': 1024.1142193703838,
    'Bmin': 921.8869150...,
    'Bmirr': 1024.1142193...,
    'I': 0.24349696021...,
    'L': 3.1954818410...,
    'M': 30119.614287...}

    The ``extended_out=True`` output is:
        - I : I value at the given point
        - L : L value at the given point
        - Bmin : minimum B at the input position (nT)
        - Bmirror : mirror B at the input position (nT)
        - M : TODO what exactly and I, magnetic moment?


        change a Lgm_Vector to a list

        Returns
        -------
        out : list
            the contents of the Lgm_Vector changed into a list

        Examples
        --------
        >>> from lgmpy import Lgm_Vector
        >>> dat = Lgm_Vector.Lgm_Vector(1,2,3)
        >>> dat.tolist()
        [1.0, 2.0, 3.0]


        change a Lgm_Vector to a numpy array

        Returns
        -------
        out : list
            the contents of the Lgm_Vector changed into a list

        Examples
        --------
        >>> from lgmpy import Lgm_Vector
        >>> dat = Lgm_Vector.Lgm_Vector(1,2,3)
        >>> dat.tolist()
        [1.0, 2.0, 3.0]


        compute the cross product of two vectors

        Parameters
        ----------
        other : other Lgm_Vector to cross prod (on the right)

        Returns
        -------
        out : the cross product of the 2 vectors (Lgm_Vector)

        Examples
        --------
        >>> from lgmpy import Lgm_Vector
        >>> dat = Lgm_Vector.Lgm_Vector(1,2,3)
        >>> dat.crossProduct(dat)
        [0.0, 0.0, 0.0]
        >>> dat2 = Lgm_Vector.Lgm_Vector(3,2,1)
        >>> dat.crossProduct(dat2)
        [-4.0, 8.0, -4.0]


        Find the magnitude of a vector

        Returns
        -------
        out : double
            A double value that is the magnitude of the vector

        Examples
        --------
        >>> from lgmpy import Lgm_Vector
        >>> dat = Lgm_Vector.Lgm_Vector(1,2,3)
        >>> dat.magnitude()
        3.74165738...


        Normalize the vector in place. Replaces the contents of self.

        Examples
        --------
        >>> from lgmpy import Lgm_Vector
        >>> import numpy as np
        >>> dat = Lgm_Vector.Lgm_Vector(1,2,3)
        >>> dat.normalize()
        >>> print(dat)
        [0.26726124..., 0.53452248..., 0.801783725...]


        compute the dot product of two vectors

        Parameters
        ----------
        other : other Lgm_Vector to dot product

        Returns
        -------
        out : the dot product of the 2 vectors (double)

        Examples
        --------
        >>> from lgmpy import Lgm_Vector
        >>> dat = Lgm_Vector.Lgm_Vector(1,2,3)
        >>> dat.dotProduct(dat)
        14.0
        >>> dat2 = Lgm_Vector.Lgm_Vector(3,2,1)
        >>> dat.dotProduct(dat2)
        10.0


        Scale a vector by a scalar and replace self

        Parameters
        ----------
        val : the value to scale the vector by (int, long, float)

        Examples
        --------
        >>> from lgmpy import Lgm_Vector
        >>> dat = Lgm_Vector.Lgm_Vector(1,2,3)
        >>> dat.scale(10)
        >>> print(dat)
        [10.0, 20.0, 30.0]


        Find Magnitude of difference between to vectors

        Parameters
        ----------
        other : another Lgm_Vector

        Returns
        -------
        out : the difference in magnitude (double)

        Examples
        --------
        >>> from lgmpy import Lgm_Vector
        >>> dat = Lgm_Vector.Lgm_Vector(1,2,3)
        >>> dat2 = Lgm_Vector.Lgm_Vector(3,2,1)
        >>> dat.diffMag(dat2)
        2.8284271247461903


        Force the vector to have a given magnitude in place

        Parameters
        ----------
        val : the magnitude of the vector

        Examples
        --------
        >>> from lgmpy import Lgm_Vector
        >>> dat = Lgm_Vector.Lgm_Vector(1,2,3)
        >>> dat.forceMagnitude(10)
        >>> print(dat)
        [2.672612..., 5.3452248..., 8.0178372...]


        In computer graphics, Slerp is shorthand for spherical linear interpolation, introduced by Ken Shoemake in the
        context of quaternion interpolation for the purpose of animating 3D rotation. It refers to constant-speed
        motion along a unit-radius great circle arc, given the ends and an interpolation parameter between 0 and 1.

        Parameters
        ----------
        other : another Lgm_Vector
        frac  : float
            Fractional distance between the two unit vectors to interpolate

        Returns
        -------
        out : Lgm_Vector
            New vector between self and other

        Examples
        --------
        >>> from lgmpy import Lgm_Vector
        >>> v1 = Lgm_Vector.Lgm_Vector(1,2,3)
        >>> v1.normalize()
        >>> v2 = Lgm_Vector.Lgm_Vector(3,7,1)
        >>> v2.normalize()
        >>> print(v1.slerp(v2, 0)
        []
        >>> print(v1.slerp(v2, 1)
        []
        >>> print(v1.slerp(v2, 0.3)
        []


    takes an input Lat, Lon, Rad and returns x, y, z

    Parameters
    ----------
    lat : latitude (deg)
    lon : longitude (deg)
    rad : radius (Distance units)

    Returns
    -------
    out : Lgm_Vector
        A Lgm_Vector in Cartesian coords same units as the input

    Examples
    --------
    >>> from lgmpy import Lgm_Vector
    >>> Lgm_Vector.SphToCart(0,0,1)
    [1.0, 0.0, 0.0]

    >>> Lgm_Vector.SphToCart(45., 45., 1.)
    [0.5000000..., 0.5, 0.70710678...]


    takes an input x, y, z and returns Lat, Lon, Rad

    Parameters
    ----------
    x : x coordinate (Distance unit)
    y : y coordinate (Distance unit)
    z : z coordinate (Distance unit

    Returns
    -------
    lat : output latitude (deg)
    lon : output longitude (deg)
    rad : output radius (Distance unit)

    Examples
    --------
    >>> from lgmpy import Lgm_Vector
    >>> Lgm_Vector.CartToSph(0,0,1)
    (90.0, 0.0, 1.0)

    >>> import math
    >>> Lgm_Vector.CartToSph(math.sqrt(2),0.,math.sqrt(2))
    (45.0, 0.0, 2.0)


    convert a python date or datetime object to a LanlGeoMag's (long int) date format

    Parameters
    ----------
    inval : datetime, ndarray
        datetime object to change to an int (or an array of datetimes to change)

    Returns
    -------
    out : int, list
        int or list of ints corresponding to the datetime

    Examples
    --------
    >>> from lgmpy import Lgm_CTrans
    >>> import datetime
    >>> Lgm_CTrans.dateToDateLong(datetime.datetime(2000, 12, 13))
    20001213L


    convert a python date or datetime object from a Date (long) object

    Parameters
    ----------
    inval : dateLong, int
        int/long to change to a datetime object

    Returns
    -------
    out : datetime, list
        datetime or list of datetime corresponding to the dateLongs


    convert a python datetime object to a Floating point hours (double) object that
    LanlGeoMag Likes to use

    Parameters
    ----------
    inval : datetime, ndarray
        datetime object to change to floating point hours
        (or an array of datetimes to change)

    Returns
    -------
    out : float, list
        floating point hours or a list of fp hours

    Examples
    --------
    >>> from lgmpy import Lgm_CTrans
    >>> import datetime
    >>> Lgm_CTrans.dateToFPHours(datetime.datetime(2000, 12, 13))
    0.0
    >>> Lgm_CTrans.dateToFPHours(datetime.datetime(2000, 12, 13, 12))
    12.0
    >>> Lgm_CTrans.dateToFPHours(datetime.datetime(2000, 12, 13, 12, 30))
    12.5


    convert GSM values to MLT in the lgm way

    Parameters
    ----------
    gsm : array_like
        Nx3 array_like of the GSM position
    dt : array_like
        N elementarray_like of datetime objects

    Returns
    -------
    out : numpy.array
        N element array of the MLT values


    Easy wrapper to just return values without having to create an instance of
    Lgm_OP77

    All input parameters can be either their type or a list of the that type, all
    inputs must be the same length

    Parameters
    ----------
    pos : list
        3-element list of the position to do the calculation
    time : datetime
        date and time of when to do the calculation
    coord_system : str, optional
        the coordinate system of the position, default=GSM
    INTERNAL_MODEL : str, optional
        the internal magnetic field model to use, default=LGM_IGRF

    Returns
    -------
    out : list
        the magnetic field vector in GSM [nT]

    Examples
    --------
    >>> from lgmpy import Lgm_OP77
    >>> import datetime
    >>> Lgm_OP77.OP77([1,2,3], datetime.datetime(1999, 1, 16, 12, 34, 12))
    [-498.5006017..., -614.7106283..., -430.26894377...]

    See Also
    --------
    Lgm_OP77.Lgm_OP77


    Easy wrapper to Lgm_TraceToEarth_py that returns both footpoints

    Parameters
    ----------
    pos : list
        3-element list of the position to do the calculation
    time : datetime
        date and time of when to do the calculation
    coord_system : str, optional
        the coordinate system of the position, default=GSM
    INTERNAL_MODEL : str, optional
        the internal magnetic field model to use, default=LGM_IGRF
    EXTERNAL_MODEL : str, optional
        the external magnetic field model to use, default=LGM_T89
    MAGMODEL_ARGS : dict, optional
        kwarguments to the magnetic field model, example for T89 {'Kp':5}
    TargetHeight : float, optional
        target height for the tracing, default=120km
    tol : float, optional
        tolerance for tracing, default=1e-7

    Returns
    -------
    out : tuple
        north and south footpoint


Convenience function to convert Python datetime to Lgm date and utc format

    Parameters
    ----------
    time_in: datetime.datetime
        the input time to convert to a different system

    Outputs
    -------
    datelong: long
        LanlGeoMag long integer date representation (YYYYMMDD)
    utc: float
        LanlGeoMag floating point time-of-day (UTC) representation


convert from Lgm float UTC time representation to julian day


    Easy wrapper to just return values without having to create an instance of
    Lgm_Dungey

    All input parameters can be either their type or a list of the that type, all
    inputs must be the same length

    Parameters
    ----------
    pos : list
        3-element list of the position to do the calculation
    time : datetime
        date and time of when to do the calculation
    coord_system : str, optional
        the coordinate system of the position, default=GSM
    INTERNAL_MODEL : str, optional
        the internal magnetic field model to use, default=LGM_IGRF

    Returns
    -------
    out : list
        the magnetic field vector in GSM [nT]

    Examples
    --------
    >>> from lgmpy import Lgm_Dungey
    >>> import datetime
    >>> Lgm_Dungey.Dungey([1,2,3], datetime.datetime(1999, 1, 16, 12, 34, 12))
    [-498.5006017..., -614.7106283..., -430.26894377...]

    See Also
    --------
    Lgm_Dungey.Lgm_Dungey


    Easy wrapper to just return values without having to create an instance of
    Lgm_T89.

    All input parameters can be either their type or a list of the that type, all
    inputs must be the same length

    Parameters
    ----------
    pos : list
        3-element list of the position to do the calculation
    time : datetime
        date and time of when to do the calculation
    Kp : int
        Kp value for the calculation
    coord_system : str, optional
        the coordinate system of the position, default=GSM
    INTERNAL_MODEL : str, optional
        the internal magnetic field model to use, default=LGM_IGRF

    Returns
    -------
    out : list
        Magnetic field vector in GSM coordinates in nT

    Examples
    --------
    >>> from lgmpy import Lgm_T89
    >>> import datetime
    >>> Lgm_T89.T89([1,2,3], datetime.datetime(1999, 1, 16, 12, 34, 12), 3)
    [-509.297442..., -619.8167352..., -426.193633024...]

    See Also
    --------
    Lgm_T89.Lgm_T89


Given the name of a library, load it.


Given a path to a library, load it.


    Add libraries to search paths.
    If library paths are relative, convert them to absolute with respect to this
    file's directory


automatically_typedef_structs() aliases "struct_<tag>" to "<tag>" for
    every struct and union.


remove_NULL() removes any NULL definitions from the C headers because
ctypesgen supplies its own NULL definition.


remove_descriptions_in_system_headers() removes descriptions if they came
    from files outside of the header files specified from the command line.


remove_macros() removes macros if --no-macros is set.


filter_by_regexes_exclude() uses regular expressions specified by options
    dictionary to filter symbols.


filter_by_regexes_include() uses regular expressions specified by options
    dictionary to re-include symbols previously rejected by other operations.


If any descriptions from the C code would overwrite Python builtins or
    other important names, fix_conflicting_names() adds underscores to resolve
    the name conflict.


find_source_libraries() determines which library contains each function
    and variable.


Visit each description in `data` and figure out which other descriptions
it depends on, putting the results in desc.requirements. Also find errors in
ctypedecls or expressions attached to the description and transfer them to the
description.


Try to add `name` as a requirement for `desc`, looking `name` up in
`nametable`. Returns True if found.


Find all the descriptions that `desc` depends on and add them as
dependencies for `desc`. Also collect error messages regarding `desc` and
convert unlocateable descriptions into error messages.


Add `desc` to the lookup table so that other descriptions that use
it can find it.


calculate_final_inclusion() calculates which descriptions will be included in the
    output library.

    An object with include_rule="never" is never included.
    An object with include_rule="yes" is included if its requirements can be
        included.
    An object with include_rule="if_needed" is included if an object to be
        included requires it and if its requirements can be included.


Save parser state and restart it.


Restore saved parser state.


    Find each symbol that can be reached from the start symbol.
    Print a warning for any nonterminals that can't be reached.
    (Unused terminals have already had their warning.)


Mark all symbols that are reachable from symbol s.


Raise an error for any symbols that don't terminate.


Apply specifiers to the declaration (declaration may be
    a Parameter instead).


translation_unit :
                        | translation_unit external_declaration
                        | translation_unit define


constant : CONSTANT
                | CHARACTER_CONSTANT


primary_expression : identifier
                          | constant
                          | multi_string_literal
                          | '(' expression ')'


postfix_expression : primary_expression
                  | postfix_expression '[' expression ']'
                  | postfix_expression '(' ')'
                  | postfix_expression '(' argument_expression_list ')'
                  | postfix_expression PERIOD IDENTIFIER
                  | postfix_expression PTR_OP IDENTIFIER
                  | postfix_expression INC_OP
                  | postfix_expression DEC_OP


unary_expression : postfix_expression
                        | INC_OP unary_expression
                        | DEC_OP unary_expression
                        | unary_operator cast_expression
                        | SIZEOF unary_expression
                        | SIZEOF '(' type_name ')'
                        | asm_expression


conditional_expression : logical_or_expression
          | logical_or_expression '?' expression ':' conditional_expression


expression : assignment_expression
                  | expression ',' assignment_expression


declaration : declaration_impl ';'


init_declarator : declarator
                       | declarator '=' initializer


struct_or_union : STRUCT
                       | UNION


struct_attribute : PACKED
                        | TRANSPARENT_UNION
                        | ALIGNED


struct_declarator : declarator
                         | ':' constant_expression
                         | declarator ':' constant_expression


enumerator_list_iso : enumerator
                           | enumerator_list_iso ',' enumerator


enumerator : IDENTIFIER
                  | IDENTIFIER '=' constant_expression


type_qualifier : CONST
                      | VOLATILE


declarator : pointer direct_declarator
                  | direct_declarator


direct_declarator : IDENTIFIER
                         | '(' declarator ')'
                         | direct_declarator '[' constant_expression ']'
                         | direct_declarator '[' ']'
                         | direct_declarator '(' parameter_type_list ')'
                         | direct_declarator '(' identifier_list ')'
                         | direct_declarator '(' ')'


parameter_type_list : parameter_list
                           | parameter_list ',' ELLIPSIS


parameter_declaration : declaration_specifiers declarator
                             | declaration_specifiers abstract_declarator
                             | declaration_specifiers


identifier_list : IDENTIFIER
                       | identifier_list ',' IDENTIFIER


abstract_declarator : pointer
                           | direct_abstract_declarator
                           | pointer direct_abstract_declarator


initializer : assignment_expression
                   | '{' initializer_list '}'
                   | '{' initializer_list ',' '}'


statement : labeled_statement
                 | compound_statement
                 | expression_statement
                 | selection_statement
                 | iteration_statement
                 | jump_statement


external_declaration : declaration
                            | function_definition


define : PP_DEFINE PP_DEFINE_NAME PP_END_DEFINE
              | PP_DEFINE PP_DEFINE_NAME type_name PP_END_DEFINE
              | PP_DEFINE PP_DEFINE_NAME constant_expression PP_END_DEFINE
              | PP_DEFINE PP_DEFINE_MACRO_NAME '(' ')' PP_END_DEFINE
              | PP_DEFINE PP_DEFINE_MACRO_NAME '(' ')' constant_expression PP_END_DEFINE
              | PP_DEFINE PP_DEFINE_MACRO_NAME '(' macro_parameter_list ')' PP_END_DEFINE
              | PP_DEFINE PP_DEFINE_MACRO_NAME '(' macro_parameter_list ')' constant_expression PP_END_DEFINE


define : PP_DEFINE error PP_END_DEFINE


Parse a file.

        If `debug` is True, parsing state is dumped to stdout.


A parse error occured.

        The default implementation prints `lineno` and `message` to stderr.
        The parser will try to recover from errors by synchronising at the
        next semicolon.


The C preprocessor emitted an error.

        The default implementatin prints the error to stderr. If processing
        can continue, it will.


Progress information.

        The default implementationg prints message to stderr.


define `name` `value`
        or #define `name`(`params`) `value`

        name is a string
        params is None or a list of strings
        value is a ...?


define `name` `value`

        name is a string
        value is an ExpressionNode or None


define `name`(`params`) `value`

        name is a string
        params is a list of strings
        value is an ExpressionNode or None


Internal method that calls `handle_declaration`.  This method
        also adds any new type definitions to the lexer's list of valid type
        names, which affects the parsing of subsequent declarations.


A declaration was encountered.

        `declaration` is an instance of Declaration.  Where a declaration has
        multiple initialisers, each is returned as a separate declaration.


Create a token of type and value, at the position where 'production'
    was reduced.  Don't specify production if the token is built-in


Parse a file and save its output


This is a regression functional test for LstarVersusPA (regression)


Unit test for centred dipole - should give known result


Unit test for centred dipole - should give known result

        Quality level only tested up to 5 (max 7) as 6 and 7 may not
        converge to a solution on all machines


Test that Lvalue code returns same value of L returned by Lstar


Lgm_Vector has a x, y, z


Lgm_Vector should be of type LgmDouble


    fill the bad pixel with linear interpolation using surrounding pixels

    Parameters
    ----------
    data : array-like
        An array of image
        If a 3D array containing multiple images,
        the images must be stacked along the 1st dimension (axis=0).
    mask : array-like
        An array indicates bad pixel positions
        The shape must be same as image.
        The value of bad pixel is nonzero, and the others is 0.
        If all pixels are bad, raise ValueError.
    out : cupy.ndarray, default None
        Alternate output array in which to place the result. The default
        is None; if provided, it must have the same shape as the
        expected output, but the type will be cast if necessary.
    dtype : str or dtype, default None
        dtype of ndarray used internally
        If None, use eclair.common.default_dtype.
        If the input dtype is different, use a casted copy.
    fix_NaN : bool, default False
        If true, fix NaN pixel even if it's not specified
        as bad pixel in mask

    Returns
    -------
    fixed : ndarray
        An array of images fixed bad pixel

    Notes
    -----
    NaN is ignored in interpolation calculations,
    but is not fixed if fix_NaN is False.


    Split HDU object into header and data

    Parameters
    ----------
    hdu : astropy HDU object
    dtype : str or dtype, default None
        dtype of array used internally
        If None, use eclair.common.default_dtype.
        If the input dtype is different, use a casted copy.
    xp : module object of numpy or cupy, default cupy
        Whether the return value is numpy.ndarray or cupy.ndarray

    Returns
    -------
    header : astropy.io.fits.Header
    data : ndarray


    Creates HDU from given data

    Parameters
    ----------
    data : ndarray
    header : astropy.io.fits.Header, default None
        The header associated with data.
        If None, a header of the appropriate type is created
        for the supplied data.
    hdu_class : class, default astropy.io.fits.PrimaryHDU
        HDU class

    Returns
    -------
    hdu : HDU object

    Notes
    -----
    This function is intended for use inside eclaire.
    It may be better to call astropy HDU class dilectly.


    Read FITS file and get header and data.

    Parameters
    ----------
    name : str
        path of FITS file
        Whether path-like objects are supported depends on
        the version of Python and Astropy.
    hdu_index : int, default 0
        Index in HDUList of HDU
    kwargs : keyward arguments
        Additional keyword arguments to pass to the hdu_splitter function
        See also hdu_splitter.

    Returns
    -------
    header : astropy.io.fits.Header
    data : ndarray


List of FITS file name


List of FITS header


Array in which image data is stacked


        Removes the items of list, header, and data
        that do not have index in the given indices.

        Parameters
        ----------
        indices : array-like
            indices of items to leave
        in_place : bool, default False
            If True, perform in-place array manipulations for ndarray.
            This saves memory, but the values of the original ndarray
            are not preserved.


        Add containsts of the other instances to self.

        Parameters
        ----------
        *args : FitsContainer or its subclass
            instances which merges with self


        Set array to the attribute

        Parameters
        ----------
        data : ndarray
            Array in which image data are stacked.
        list : array-like, default None
            Sequence of FITS file name.
            If None, use a list of None as many as the length of array.
        header : array-like, default None
            Sequence of FITS header.
            If None, use a list of None as many as the length of array.


        Load headers and data from iterator

        Parameters
        ----------
        iterable : iterable
            An iterable object that returns header and data
            This must return a tuple (header, data).
            'header' and 'data' must be instances of astropy.io.fits.Header
            and 2d ndarray, respectively.
        mapping : callable, default None
            Apply this to each items that 'iterable' returns.
            If None, use a function that returns arguments as is.
        wrapper : callable, default None
            A wrapper function of iterator.
            If None, use a function that returns arguments as is.
        mempool : cupy.cuda.MemoryPool, default None
            This is used for to release the extra memory allocated
            in the process of transferring images to VRAM.
            If you use the custom memory pool (e.g. unified memory pool),
            giving the MemoryPool instance is recommended for
            the efficient memory usage. If None, use the default
            memory pool of CuPy.

        Notes
        -----
        This method iterates the return values of the following expressions.
        ```
        wrapper(mapping(*args) for args in iterable)
        ```


        Load headers and data from FITS files

        Parameters
        ----------
        files : array-like
            A sequence of FITS file path or file-object.
            Whether path-like objects are supported depends on
            the version of Python and Astropy.
        hdu_index : int, default 0
            Index of target HDU in HDUList
        kwargs : keyword arguments
            Additional keyword arguments given to from_iterator

        See Also
        --------
        from_iterator : Load headers and data from iterator


        Load headers and data from a sequence of HDUList

        Parameters
        ----------
        hduls : array-like
            A sequence of HDUList
        hdu_index : int, default 0
            Index of target HDU in HDUList
        kwargs : keyword arguments
            Additional keyword arguments given to from_iterator

        See Also
        --------
        from_iterator : Load headers and data from iterator


        Load headers and data from a sequence of HDU

        Parameters
        ----------
        hdus : array-like
            A sequence of HDU
        kwargs : keyword arguments
            Additional keyword arguments given to from_iterator

        See Also
        --------
        from_iterator : Load headers and data from iterator


        make FITS file with storing FITS header and data

        Parameters
        ----------
        outlist : array-like
            list of output FITS paths
            raise ValueError if the length of this list is different
            from the number of images.
        kwargs : keyward arguments
            These are given to writeto method of HDU object