Transform Plate Carree image and associated csv file into Orthographic.

    Parameters
    ----------
    img : PIL.Image.image or str
        File or filename.
    llbd : list-like
        Long/lat limits (long_min, long_max, lat_min, lat_max) of image.
    craters : pandas.DataFrame
        Craters catalogue.
    iglobe : cartopy.crs.Geodetic instance
        Globe for images.  If False, defaults to spherical Moon.
    ctr_sub : bool, optional
        If `True`, assumes craters dataframe includes only craters within
        image. If `False` (default_, llbd used to cut craters from outside
        image out of (copy of) dataframe.
    arad : float
        World radius in km.  Default is Moon (1737.4 km).
    origin : "lower" or "upper", optional
        Based on imshow convention for displaying image y-axis.  "upper"
        (default) means that [0,0] is upper-left corner of image; "lower" means
        it is bottom-left.
    rgcoeff : float, optional
        Fractional size increase of transformed image height.  By default set
        to 1.2 to prevent loss of fidelity during transform (though warping can
        be so extreme that this might be meaningless).
    slivercut : float from 0 to 1, optional
        If transformed image aspect ratio is too narrow (and would lead to a
        lot of padding, return null images).

    Returns
    -------
    imgo : PIL.Image.image
        Transformed, padded image in PIL.Image format.
    ctr_xy : pandas.DataFrame
        Craters with transformed x, y pixel positions and pixel radii.
    distortion_coefficient : float
        Ratio between the central heights of the transformed image and original
        image.
    centrallonglat_xy : pandas.DataFrame
        xy position of the central longitude and latitude.


Creates circle mask of radius r.


    Creates ring of radius r and thickness dr.

    Parameters
    ----------
    r : float
        Ring radius
    dr : int
        Ring thickness (cv2.circle requires int)


Makes crater mask binary image (does not yet consider crater overlap).

    Parameters
    ----------
    craters : pandas.DataFrame
        Craters catalogue that includes pixel x and y columns.
    img : numpy.ndarray
        Original image; assumes colour channel is last axis (tf standard).
    binary : bool, optional
        If True, returns a binary image of crater masks.
    rings : bool, optional
        If True, mask uses hollow rings rather than filled circles.
    ringwidth : int, optional
        If rings is True, ringwidth sets the width (dr) of the ring.
    truncate : bool
        If True, truncate mask where image truncates.

    Returns
    -------
    mask : numpy.ndarray
        Target mask image.


Adds x and y pixel locations to craters dataframe.

    Parameters
    ----------
    craters : pandas.DataFrame
        Crater info
    imgdim : list, tuple or ndarray
        Length and height of image, in pixels
    cdim : list-like, optional
        Coordinate limits (x_min, x_max, y_min, y_max) of image.  Default is
        [-180., 180., -90., 90.].
    origin : "upper" or "lower", optional
        Based on imshow convention for displaying image y-axis.
        "upper" means that [0,0] is upper-left corner of image;
        "lower" means it is bottom-left.


Crops crater file, and removes craters smaller than some minimum value.

    Parameters
    ----------
    craters : pandas.DataFrame
        Crater dataframe.
    llbd : list-like
        Long/lat limits (long_min, long_max, lat_min, lat_max) of image.
    imgheight : int
        Pixel height of image.
    arad : float, optional
        World radius in km.  Defaults to Moon radius (1737.4 km).
    minpix : int, optional
        Minimium crater pixel size to be included in output.  Default is 0
        (equvalent to no cutoff).

    Returns
    -------
    ctr_sub : pandas.DataFrame
        Cropped and filtered dataframe.


Crops image, so that the crop output can be used in GenDataset.

    Parameters
    ----------
    img : PIL.Image.Image
        Image
    cdim : list-like
        Coordinate limits (x_min, x_max, y_min, y_max) of image.
    newcdim : list-like
        Crop boundaries (x_min, x_max, y_min, y_max).  There is
        currently NO CHECK that newcdim is within cdim!

    Returns
    -------
    img : PIL.Image.Image
        Cropped image


Generates random dataset from a global DEM and crater catalogue.

    The function randomly samples small images from a global digital elevation
    map (DEM) that uses a Plate Carree projection, and converts the small
    images to Orthographic projection.  Pixel coordinates and radii of craters
    from the catalogue that fall within each image are placed in a
    corresponding Pandas dataframe.  Images and dataframes are saved to disk in
    hdf5 format.

    Parameters
    ----------
    img : PIL.Image.Image
        Source image.
    craters : pandas.DataFrame
        Crater catalogue .csv.
    outhead : str
        Filepath and file prefix of the image and crater table hdf5 files.
    rawlen_range : list-like, optional
        Lower and upper bounds of raw image widths, in pixels, to crop from
        source.  To always crop the same sized image, set lower bound to the
        same value as the upper.  Default is [300, 4000].
    rawlen_dist : 'uniform' or 'log'
        Distribution from which to randomly sample image widths.  'uniform' is
        uniform sampling, and 'log' is loguniform sampling.
    ilen : int, optional
        Input image width, in pixels.  Cropped images will be downsampled to
        this size.  Default is 256.
    cdim : list-like, optional
        Coordinate limits (x_min, x_max, y_min, y_max) of image.  Default is
        LRO-Kaguya's [-180., 180., -60., 60.].
    arad : float. optional
        World radius in km.  Defaults to Moon radius (1737.4 km).
    minpix : int, optional
        Minimum crater diameter in pixels to be included in crater list.
        Useful when the smallest craters in the catalogue are smaller than 1
        pixel in diameter.
    tglen : int, optional
        Target image width, in pixels.
    binary : bool, optional
        If True, returns a binary image of crater masks.
    rings : bool, optional
        If True, mask uses hollow rings rather than filled circles.
    ringwidth : int, optional
        If rings is True, ringwidth sets the width (dr) of the ring.
    truncate : bool
        If True, truncate mask where image truncates.
    amt : int, optional
        Number of images to produce.  100 by default.
    istart : int
        Output file starting number, when creating datasets spanning multiple
        files.
    seed : int or None
        np.random.seed input (for testing purposes).
    verbose : bool
        If True, prints out number of image being generated.


Wrapper for Keras 2's Conv2D class.


Custom image generator that manipulates image/target pairs to prevent
    overfitting in the Convolutional Neural Network.

    Parameters
    ----------
    data : array
        Input images.
    target : array
        Target images.
    batch_size : int, optional
        Batch size for image manipulation.

    Yields
    ------
    Manipulated images and targets.


Function that builds the (UNET) convolutional neural network.

    Parameters
    ----------
    dim : int
        Dimension of input images (assumes square).
    learn_rate : float
        Learning rate.
    lmbda : float
        Convolution2D regularization parameter.
    drop : float
        Dropout fraction.
    FL : int
        Filter length.
    init : string
        Weight initialization type.
    n_filters : int
        Number of filters in each layer.

    Returns
    -------
    model : keras model object
        Constructed Keras model.


Generates unique crater distribution by filtering out duplicates.

    Parameters
    ----------
    craters : array
        Crater tuples from a single image in the form (long, lat, radius).
    craters_unique : array
        Master array of unique crater tuples in the form (long, lat, radius)
    thresh_longlat2 : float.
        Hyperparameter that controls the minimum squared longitude/latitude
        difference between craters to be considered unique entries.
    thresh_rad : float
        Hyperparaeter that controls the minimum squared radius difference
        between craters to be considered unique entries.

    Returns
    -------
    craters_unique : array
        Modified master array of unique crater tuples with new crater entries.


First-order estimation of long/lat, and radius (km) from
    (Orthographic) x/y position and radius (pix).

    For images transformed from ~6000 pixel crops of the 30,000 pixel
    LROC-Kaguya DEM, this results in < ~0.4 degree latitude, <~0.2
    longitude offsets (~2% and ~1% of the image, respectively) and ~2% error in
    radius. Larger images thus may require an exact inverse transform,
    depending on the accuracy demanded by the user.

    Parameters
    ----------
    dim : tuple or list
        (width, height) of input images.
    llbd : tuple or list
        Long/lat limits (long_min, long_max, lat_min, lat_max) of image.
    distcoeff : float
        Ratio between the central heights of the transformed image and original
        image.
    coords : numpy.ndarray
        Array of crater x coordinates, y coordinates, and pixel radii.

    Returns
    -------
    craters_longlatdiamkm : numpy.ndarray
        Array of crater longitude, latitude and radii in km.


Top level function that extracts craters from model predictions,
    converts craters from pixel to real (degree, km) coordinates, and filters
    out duplicate detections across images.

    Parameters
    ----------
    CP : dict
        Crater Parameters needed to run the code.
    craters_unique : array
        Empty master array of unique crater tuples in the form
        (long, lat, radius).

    Returns
    -------
    craters_unique : array
        Filled master array of unique crater tuples.


Normalize and rescale (and optionally invert) images.

    Parameters
    ----------
    Data : hdf5
        Data array.
    dim : integer, optional
        Dimensions of images, assumes square.
    low : float, optional
        Minimum rescale value. Default is 0.1 since background pixels are 0.
    hi : float, optional
        Maximum rescale value.


Extracts crater coordinates (in pixels) from a CNN-predicted target by
    iteratively sliding rings through the image via match_template from
    scikit-image.

    Parameters
    ----------
    target : array
        CNN-predicted target.
    minrad : integer
        Minimum ring radius to search target over.
    maxrad : integer
        Maximum ring radius to search target over.
    longlat_thresh2 : float
        Minimum squared longitude/latitude difference between craters to be
        considered distinct detections.
    rad_thresh : float
        Minimum fractional radius difference between craters to be considered
        distinct detections.
    template_thresh : float
        Minimum match_template correlation coefficient to count as a detected
        crater.
    target_thresh : float
        Value between 0-1. All pixels > target_thresh are set to 1, and
        otherwise set to 0.

    Returns
    -------
    coords : array
        Pixel coordinates of successfully detected craters in predicted target.


Extracts crater coordinates (in pixels) from a CNN-predicted target and
    compares the resulting detections to the corresponding human-counted crater
    data.

    Parameters
    ----------
    target : array
        CNN-predicted target.
    csv_coords : array
        Human-counted crater coordinates (in pixel units).
    minrad : integer
        Minimum ring radius to search target over.
    maxrad : integer
        Maximum ring radius to search target over.
    longlat_thresh2 : float
        Minimum squared longitude/latitude difference between craters to be
        considered distinct detections.
    rad_thresh : float
        Minimum fractional radius difference between craters to be considered
        distinct detections.
    template_thresh : float
        Minimum match_template correlation coefficient to count as a detected
        crater.
    target_thresh : float
        Value between 0-1. All pixels > target_thresh are set to 1, and
        otherwise set to 0.
    rmv_oor_csvs : boolean, flag
        If set to 1, remove craters from the csv that are outside your
        detectable range.

    Returns
    -------
    N_match : int
        Number of crater matches between your target and csv.
    N_csv : int
        Number of csv entries
    N_detect : int
        Total number of detected craters from target.
    maxr : int
        Radius of largest crater extracted from target.
    err_lo : float
        Mean longitude error between detected craters and csvs.
    err_la : float
        Mean latitude error between detected craters and csvs.
    err_r : float
        Mean radius error between detected craters and csvs.
    frac_dupes : float
        Fraction of craters with multiple csv matches.


Converts coordinate x/y to image pixel locations.

    Parameters
    ----------
    cx : float or ndarray
        Coordinate x.
    cy : float or ndarray
        Coordinate y.
    cdim : list-like
        Coordinate limits (x_min, x_max, y_min, y_max) of image.
    imgdim : list, tuple or ndarray
        Length and height of image, in pixels.
    origin : 'upper' or 'lower', optional
        Based on imshow convention for displaying image y-axis. 'upper' means
        that [0, 0] is upper-left corner of image; 'lower' means it is
        bottom-left.

    Returns
    -------
    x : float or ndarray
        Pixel x positions.
    y : float or ndarray
        Pixel y positions.


Converts image pixel locations to Plate Carree lat/long.  Assumes
    central meridian is at 0 (so long in [-180, 180)).

    Parameters
    ----------
    x : float or ndarray
        Pixel x positions.
    y : float or ndarray
        Pixel y positions.
    cdim : list-like
        Coordinate limits (x_min, x_max, y_min, y_max) of image.
    imgdim : list, tuple or ndarray
        Length and height of image, in pixels.
    origin : 'upper' or 'lower', optional
        Based on imshow convention for displaying image y-axis. 'upper' means
        that [0, 0] is upper-left corner of image; 'lower' means it is
        bottom-left.

    Returns
    -------
    cx : float or ndarray
        Coordinate x.
    cy : float or ndarray
        Coordinate y.


Returns conversion from km to pixels (i.e. pix / km).

    Parameters
    ----------
    imgheight : float
        Height of image in pixels.
    latextent : float
        Latitude extent of image in degrees.
    dc : float from 0 to 1, optional
        Scaling factor for distortions.
    a : float, optional
        World radius in km.  Default is Moon (1737.4 km).

    Returns
    -------
    km2pix : float
        Conversion factor pix/km


    Extract the kbb mapping of rectification slice to lenslet array
    from the LensletMapping.xlsx file.
    NOTE: the excel file has the first two rows masked, but we will not consider
    them here. The first row is where there is actually flux, corresponding to
    the first slice in the rect. matrix.

    2017-03-28 - T. Do


Return the peak position in units of lags


 gaussian model
    p[0] -- scale factor
    p[1] -- centroid
    p[2] -- sigma
    p[3] -- offset
    p[4] -- slope


 The edge of a slit, convolved with a Gaussian, is well fit by
    the error function. slit_edge_fun is a reexpression of the error
    function in the classica gaussian "sigma" units


Fitting function for a bar edge


    The fitting function used by do_fit_single. This is a single slit edge

    p[0] ---> Sigma
    p[1] ---> Horizontal offset
    p[2] ---> Multipicative offset
    p[3] ---> Additive offset


    The fitting function ussed by "do_fit". The sum of two edge functions.

    p[0] ---> Sigma
    p[1] ---> Horizontal offset
    p[2] ---> Multipicative offset
    p[3] ---> Additive offset
    p[4] ---> Width of slit


    The fitting function ussed by "do_fit". The sum of two edge functions.

    p[0] ---> Sigma
    p[1] ---> Horizontal offset
    p[2] ---> Multipicative offset side 1
    p[3] ---> Multiplicative offset side 2
    p[4] ---> Additive offset
    p[5] ---> Width of slit


do_fit estimates parameters of fit_pair or fit_single.

    Use as follows:

    p0 = [0.5, 6, 1.1, 3, 1]
    ys = fit_single(p0, xs)
    lsf = do_fit(ys, residual_single)
    res = np.sum((lsf[0] - p0)**2)


THIS HSOULD BE REMOVED


    This routine will go through a rectification matrix and trace the scans for each slice
    of the rect. matrix.

    NOTE: in order to map the slices of the rect matrix to spaxel location,
    use LensletMapping.xlsx

    OUTPUT
    ------
    outfile - file to store the output dictionary of the fit. The dictionary
    has keys of the form 'sliceN': (tfit,sampleLoc,peakLoc,lineProfile, fitParams, spectrum)

    Saved as a numpy npy file. To load use a = np.load(outfile), then b= a.item(0) to get the
    dictionary back. Note: loading the .npy file will not work on python3 if prduced by python2.7
    HISTORY
    -------
    2017-03-25 - T. Do


    This routine will go through a rectification matrix and trace the scans for each slice
    of the rect. matrix.

    NOTE: in order to map the slices of the rect matrix to spaxel location,
    use LensletMapping.xlsx

    OUTPUT
    ------
    outfile - file to store the output dictionary of the fit. The dictionary
    has keys of the form 'sliceN': (tfit,sampleLoc,peakLoc,lineProfile, fitParams, spectrum)

    Saved as a numpy npy file. To load use a = np.load(outfile), then b= a.items(0) to get the
    dictionary back
    HISTORY
    -------
    2017-03-25 - T. Do


    Get the wavelengths corresponding to each pixel for a rectified MOSFIRE spectrum

    INPUT: fileName - fits file of the spectrum that is rectified by
    the pipeline, or the file with the wavelength solution if the y
    value is given.

    y - optional input to return the wavelength solution at a given y
    value.

    OUTPUT: array corresponding to the wavelength for each x value


 Collapse the spectrum so that we can compute spatial profile
    as a function of wavelength. The steps are as follows

    Starting from a given position along the spatial dimension,
    extract the closests few pixels, controlled by the 'width'
    keyword.

    Then, nomalize the light along the pixels along the spatial dimension

    Fit for the fraction of light in each pixel as a function of
    wavelength.

    Iteratively remove cosmic rays/bad pixels

    NOTE: right now, this routine does not use a variance image, which
    will be necessary to implement the 'optimal extraction' routine
    from Horne 1986

    INPUTS: inputArr - can be a string with a fits file, or an numpy
                       array with the spectrum image [y, x]
            startloc - location along the spatial direction (Y) to
                       center the extraction.
            wavefile - the fits file containing the wavelength solution
                       for the different locations in the detector. If
                       this is set, instead of returning fitParams, it
                       will return the weighted wavelength corresponding
                       to the input spectrum

    OPTIONAL INPUTS:
            threshold - threshold for the variance in which to clip
                        bad points

    KEYWORDS: extractMax - extract around the maximum index collapsed
    in the wavelength direction. Will ignore the 'startloc' input
    parameter in this case, replacing it with the max index

    OUTPUT:
          lineProfile - lineProfile with the fraction of light in each pixel
          fitParams - the fit parameters per wavelength channel (or wavelength
          corresponding to the input spectrum if 'wavefile' is used)
          spec - the final extracted spectrum

    HISTORY: 2013-08-27 - T. Do


 used by fitSpatialProfile to fit a polynomial to each spatial
    location for the detector.


    Assume the input array only has a single line and do the trace
    with a Gaussian fit.


 Traces a spectrum across the detector and determine the best
    fit y values as a function of x.

    INPUTS: inputArr - either a numpy array or a FITS filename
            startloc - the y index to center the extraction for the slit

    KEYWORDS:
    threshold - a threshold for the flux. If no points are above or
         equal to the threshold, then do not fit that slice. (default: None)

    OUTPUT: (coefficients for polyfit, x position, y peak locations)


 returns the clipped mean

    Does an interative sigma clipping. Clipping is done about the
    median, but the mean is returned. Based on the idl routine
    MEANCLIP.pro


    Removes the continuum an normalize a spectrum by fitting a
    polynomial and dividing the spectrum by it.

    2014-02-20 - T. Do


Main function for consume queue.


Download the reference file.


    Make a rect mat with a given slice, maxslice, and weight limit value.  Save the rect mat into a sub-directory of the reduce_dir (reduce_dir is hard-coded above).  This sub-directory is named with the weightlimit, slice, and maxslice values followed by an optional dir_suffix.

    To make rect mat: updates the given rect mat xml file (named "xml_filename") with new output dir and the appropriate drp files with new maxslice, slice, and weight limit values.  Prompts the user to close the OSIRIS DRP so it can be reopened with the new drp parameter values.  Recompiles the c code in drp modules/source/ directory.

    Also updates the given test filename (named "xml_test_filename") with the new data directory


Open file, extract good and bad spectra and compute std for comparison.


Compares two data cubes.


Prepare the DRFs in a queue directory for testing


Run the DRP until it has consumed a single queue directory.

    The DRP is run by IDL in a subprocess using the python subprocess module.

    :param str queue_directory: The path to the queue directory with DRFs which should be consumed.
    :param str test_directory: Optionally, set the root directory for test code. By default, it will be set from the relevant OSIRIS environment variable, ``OSIRIS_ROOT``.


Fixture for preparing the queue.


Assert that two OSIRIS fits files are close.


Check that the log directory exists.


A list of input data files.


A list of input calibration files.


    Apply a bad pixel mask to the third extension of a file

    Inputs
    ------
    infile - input file name of raw
    maskfile - mask file name (9 = good, 0 = bad)
    deadpixelfile - file with dead pixels (1 = good, 0 = bad)
    outfile - output file name, can be same as input (will
    overwrite)


URL progress bar.


Update a progress bar.


Download a file.


Ask for a value


docstring for validate_yes_no


Validate a path which must exist.


Validate a path.


Download all the tools files.


Download the DRS


Validate that a given directory contains 'idl_export.h


Validate a path as being a valid CFITSIO path.


Extract a zipfile with a common prefix.


Install the pipeline.


docstring for xml_replace_paramvalue


Download a single osiris tools file.


Install pipeline tools


Write an executable script to disk.


Run 'make' and capture output.


Display the finished information.


        Find all subsets of observations (groupings) that have an orbit passing within self.tol of them.

        Parameters
        ----------
        xys: np.array of all detections of shape (?,2)
        ts:  np.array of all detections times

        Returns
        -------
        array of tuples
            indices of detections that have an orbit passing within self.tol of them


        Check whether one specific grouping g can be fitted with an orbit within specified tolerance

        Parameters
        ----------
        xys: np.array of all detections of shape (?,2)
        ts:  np.array of all detections times
        g:   the grouping - indices of observations to be checked

        Returns
        -------
        boolean
            True if at least one orbit can be fitted within self.tol


    Uniformly sample orbital elements of planets.
    The inclination of the system-plane is sampled first, and then the inclunation of each planet around that plane

    Parameters
    ----------
    n_planets:  number of planets
    min_a:      lower bound on semi-major axes
    max_a:      upper bound on semi-major axes
    max_e:      upper bound on eccentricities
    sep_a:      minimum seperation between adjacent semi-major axes
    min_i:      lower bound on inclination of the plane of the system
    max_i:      upper bound on inclination of the plane of the system
    spread_i_O: spread of inclinations and ascending nodes around the plane of the system

    Returns
    -------
    np.array of semi-major axes
    np.array of eccentricities
    np.array of inclinations
    np.array of arguments of periapsis
    np.array of arguments of ascending nodes
    np.array of mean anomalies


    Iterator over all possible partitions (with repetitions) of numbers that sum up to a target sum (larger numbers appear first).
    Used by get_ranked_set_partitions.
    (note that in the contect of planet matching, 1 is always in ranked_numbers - representing a single observation of a planet)

    Parameters
    ----------
    ranked_numbers : list of ints
        list of numbers to be summed (ranked in increasing order)
    sum_ : int
        target sum

    Returns
    -------
    an iterator over
        tuple of ints
            partitions from ranked_numbers in decreasing lexical order


    Iterator over all possible partitions of disjoint subsets with specified lengths
    Used by get_ranked_set_partitions.

    Parameters
    ----------
    sets : list of python sets ranked by length (in decreasing order)
        sets to choose from
    specific_lengths : list of ints
        the lenghts that returned subsets should be of

    Returns
    -------
    an iterator over
        tuple sets
            disjoint subsets (same number of elements as specific_lengths)


    Checks if all the sets in one list are subsets of one set in another list.
    Used by get_ranked_trajectory_partitions

    Parameters
    ----------
    sets : list of python sets
        partition to check
    other_sets : list of python sets
        partition to check against

    Returns
    -------
    bool
        whether all sets are included in other_sets


        Fits an orbit image-plane points xys at times self.ts + self.ts_mean.
        This is done by axshaustive search over a 3D space of orbital elements (a, ex, ey).
        The 3 remaining elements corresponding to a linear transormation which is fitted.
        Least-squares fiting the linear transormation, however, gives 4 degrees of freedom.
        One of the DOF is the first singular value which is adjusted to match the semi-major axis, a.

        Because of numerical noise, this process breaks down at low inclinations.
        For this reason, a 0 inclination orbit is fitted separately.

        Parameters
        ----------
        xys:        detections in image plane; np.array of shape (?,2)
        only_error: whether to only return fit error

        Returns
        -------
        float
            fit error

        tuple of 6 floats (optional)
            orbital parameters of best fit (a, e, i, o, O, M0)


        Numerically estimates the maximum sensitivity of orbit fitting error to (a, ex, ey).
        This is done by numerically differentiating the positions of the outer points in the orbit plane.

        Parameters
        ----------
        a: semi-major axis

        Returns
        -------
        tuple of 3 floats
            the sensitivities of the error to a, ex, ey


        Fits an orbit image-plane points xys at times self.ts.
        Iterates over all relevant grids and invokes OrbitGridSearch.fit

        Parameters
        ----------
        xys:        detections in image plane; np.array of shape (?,2)
        only_error: whether to only return fit error

        Returns
        -------
        iterator over:
            float
                fit error

            tuple of 6 floats (optional)
                orbital parameters of best fit (a, e, i, o, O, M0)


    Solves Kepler's equation in terms of the eccentrcity vector (ex,ey instead of just e).
    Instead of the mean anomaly, the difference of the mean anomaly fromt t=0 is given.
    By definition, at t=0: x>0 and y=0.

    Parameters
    ----------
    dM:       difference in mean anomaly dM = M - M(t=0)
    ex:       x componenet of the eccentricity vector
    ey:       y componenet of the eccentricity vector
    max_iter: maximum number of iterations of Newton's method
    tol:      tolerance of eccentric anomaly (convergence condition)

    Returns
    -------
    np.array of floats
        x corrdinates of points in orbital plane (with a = 1)

    np.array of floats
        y corrdinates of points in orbital plane (with a = 1)


    Find quick bounds on max/min semi-major axes that gives an orbit that fits data within tol.

    Parameters
    ----------
    xys:   detections in image plane; np.array of shape (?,2)
    ts:    times at which detections will be given
    mu:    gravitational parameter (units consistent with xys and ts)
    max_e: upper bound on the eccentricity of orbits
    tol:   astrometry error tollerance (RMS across all detections in the same units of xys)

    Returns
    -------
    float
        lower bound on semi-major axis

    float
        upper bound on semi-major axis


r"""
        Get BBN helium nucleon fraction.
        # Parthenope fits, as in Planck 2015 papers

        :param ombh2: :math:`\Omega_b h^2`
        :param delta_neff:  additional N_eff relative to standard value (of 3.046)
        :param tau_neutron: neutron lifetime
        :return:  :math:`Y_p^{\rm BBN}` helium nucleon fraction predicted by BBN


r"""
        Get angular diameter distance between two redshifts
        :math:`\frac{r}{1+z_2}\text{sin}_K\left(\frac{\chi(z_2) - \chi(z_1)}{r}\right)`
        where :math:`r` is curvature radius and :math:`\chi` is the comoving radial distance.

        Must have called :meth:`calc_background`, :meth:`calc_background_no_thermo` or calculated transfer
        functions or power spectra.

        :param z1: redshift 1
        :param z2: redshift 2
        :return: result


        Convert conformal time array to redshift array.
        Note that this function requires the transfers or background to have been calculated with no_thermo=False
        (the default).

        :param eta: conformal time from bing bang (in Mpc), scalar or array
        :return: redshift at eta, scalar or array


        Get physical time between two scalar factors in Gigayears

        Must have called :meth:`calc_background`, :meth:`calc_background_no_thermo` or calculated transfer functions
        or power spectra.

        :param a1: scale factor 1
        :param a2: scale factor 2
        :return: (age(a2)-age(a1))/Gigayear


        Get physical time from hot big bang to redshift z in Gigayears.

        :param z:  redshift
        :return: t(z)/Gigayear


        Get conformal time between two scale factors (=comoving radial distance travelled by light on light cone)

        :param a1: scale factor 1
        :param a2: scale factor 2
        :return: eta(a2)-eta(a1) = chi(a1)-chi(a2) in Megaparsec


    Get a :class:`.model.CAMBparams` instance using parameter specified in a .ini parameter file.

    :param ini_filename: path of the .ini file to read
    :param no_validate: do not pre-validate the ini file (faster, but may crash kernel if error)
    :return: :class:`.model.CAMBparams` instance


r"""
    Utility function to return array of Legendre and :math:`d_{mn}` functions for all :math:`\ell` up to lmax.
    Note that :math:`d_{mn}` arrays start at :math:`\ell_{\rm min} = \max(m,n)`, so returned arrays are different sizes

    :param lmax: maximum :math:`\ell`
    :param x: scalar value of :math:`\cos(\theta)` at which to evaluate
    :param m: m values to calculate :math:`d_{m,n}`, etc as relevant
    :param lfacs: optional pre-computed :math:`\ell(\ell+1)` float array
    :param lfacs2: optional pre-computed :math:`(\ell+2)*(\ell-1)` float array
    :param lrootfacs: optional pre-computed sqrt(lfacs*lfacs2) array
    :return: :math:`(P,P'),(d_{11},d_{-1,1}), (d_{20}, d_{22}, d_{2,-2})` as requested, where P starts
             at :math:`\ell=0`, but spin functions start at :math:`\ell=\ell_{\rm min}`


r"""
    Get the :math:`\sigma^2(x)` and :math:`C_{{\rm gl},2}(x)` functions from the lensing power spectrum

    :param clpp: array of :math:`[L(L+1)]^2 C_L^{\phi\phi}/2\pi` lensing potential power spectrum (zero based)
    :param xvals: array of :math:`\cos(\theta)` values at which to calculate correlation function.
    :param lmax: optional maximum L to use from the clpp array
    :return: array of :math:`\sigma^2(x)`, array of :math:`C_{{\rm gl},2}(x)`


        Make independent copy.

         :return: copy of self


        Do some quick tests for sanity

        :return: True if OK


:return: Effective number of degrees of freedom in relativistic species at early times.


r"""
    Utility function to return array of Legendre and :math:`d_{mn}` functions for all :math:`\ell` up to lmax.
    Note that :math:`d_{mn}` arrays start at :math:`\ell_{\rm min} = \max(m,n)`, so returned arrays are different sizes

    :param lmax: maximum :math:`\ell`
    :param x: scalar value of :math:`\cos(\theta)` at which to evaluate
    :param m: m values to calculate :math:`d_{m,n}`, etc as relevant
    :param lfacs: optional pre-computed :math:`\ell(\ell+1)` float array
    :param lfacs2: optional pre-computed :math:`(\ell+2)*(\ell-1)` float array
    :param lrootfacs: optional pre-computed sqrt(lfacs*lfacs2) array
    :return: :math:`(P,P'),(d_{11},d_{-1,1}), (d_{20}, d_{22}, d_{2,-2})` as requested, where P starts at :math:`\ell=0`, but spin functions start at :math:`\ell=\ell_{\rm min}`


r"""
    Get the correlation function from the power spectra, evaluated at points cos(theta) = xvals.
    Use roots of Legendre polynomials (np.polynomial.legendre.leggauss) for accurate back integration with corr2cl.
    Note currently does not work at xvals=1 (can easily calculate that as special case!).

    :param cls: 2D array cls(L,ix), with L (:math:`\equiv \ell`) starting at zero and ix-0,1,2,3 in order TT, EE, BB, TE.
        cls should include :math:`\ell(\ell+1)/2\pi` factors.
    :param xvals: array of :math:`\cos(\theta)` values at which to calculate correlation function.
    :param lmax: optional maximum L to use from the cls arrays
    :return: 2D array of corrs[i, ix], where ix=0,1,2,3 are T, Q+U, Q-U and cross


r"""
    Transform power specturm cls into correlation functions evaluated at the
    roots of the Legendre polynomials for Gauss-Legendre quadrature. Returns correlation function array,
    evaluation points and weights.
    Result can be passed to corr2cl for accurate back transform.

    :param cls: 2D array cls(L,ix), with L (:math:`\equiv \ell`) starting at zero and ix=0,1,2,3 in order TT, EE, BB, TE.
     Should include :math:`\ell(\ell+1)/2\pi` factors.
    :param lmax: optional maximum L to use
    :param sampling_factor: uses Gauss-Legendre with degree lmax*sampling_factor+1
    :return: corrs, xvals, weights; corrs[i, ix] is 2D array where ix=0,1,2,3 are T, Q+U, Q-U and cross


r"""
    Get :math:`R \equiv \frac{1}{2} \langle |\nabla \phi|^2\rangle`

    :param clpp: array of :math:`[L(L+1)]^2 C_L^{\phi\phi}/2\pi` lensing potential power spectrum
    :param lmax: optional maximum L to use from the cls arrays
    :return: R


r"""
    Get the lensed correlation function from the unlensed power spectra, evaluated at points :math:`\cos(\theta)` = xvals.
    Use roots of Legendre polynomials (np.polynomial.legendre.leggauss) for accurate back integration with corr2cl.
    Note currently does not work at xvals=1 (can easily calculate that as special case!).

    To get the lensed cls efficiently, set weights to the integral weights for each x value, then function returns
    lensed correlations and lensed cls.

    Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of
    `astro-ph/0601594 <http://arxiv.org/abs/astro-ph/0601594>`_, to second order in :math:`C_{{\rm gl},2}`

    :param cls: 2D array of unlensed cls(L,ix), with L (:math:`\equiv\ell`) starting at zero and ix=0,1,2,3 in order TT, EE, BB, TE.
        cls should include :math:`\ell(\ell+1)/2\pi` factors.
    :param clpp: array of :math:`[L(L+1)]^2 C_L^{\phi\phi}/2\pi` lensing potential power spectrum (zero based)
    :param xvals: array of :math:`\cos(\theta)` values at which to calculate correlation function.
    :param weights: if given also return lensed :math:`C_\ell`, otherwise just lensed correlations
    :param lmax: optional maximum L to use from the cls arrays
    :param delta: if true, calculate the difference between lensed and unlensed (default False)
    :param theta_max: maximum angle (in radians) to keep in the correlation functions
    :param apodize_point_width: smoothing scale for apodization at truncation of correlation function
    :return: 2D array of corrs[i, ix], where ix=0,1,2,3 are T, Q+U, Q-U and cross;
        if weights is not None, then return corrs, lensed_cls


r"""
    Get the lensed power spectra from the unlensed power spectra and the lensing potential power.
    Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of
    `astro-ph/0601594 <http://arxiv.org/abs/astro-ph/0601594>`_, to second order in :math:`C_{{\rm gl},2}`.

    Correlations are calculated for Gauss-Legendre integration if leggaus=True; this slows it by several seconds,
    but will be must faster on subsequent calls with the same lmax*sampling_factor.
    If Gauss-Legendre is not used, sampling_factor needs to be about 2 times larger for same accuracy.

    For a reference implementation with the full integral range and no apodization set theta_max=None.

    Note that this function does not pad high :math:`\ell` with a smooth fit (like CAMB's main functions); for accurate results
    should be called with lmax high enough that input cls are effectively band limited
    (lmax >= 2500, or higher for accurate BB to small scales).
    Usually lmax truncation errors are far larger than other numerical errors for lmax<4000.

    :param cls: 2D array of unlensed cls(L,ix), with L starting at zero and ix=0,1,2,3 in order TT, EE, BB, TE.
        cls should include :math:`\ell(\ell+1)/2\pi` factors.
    :param clpp: array of :math:`[L(L+1)]^2 C_L^{\phi\phi}/2\pi` lensing potential power spectrum (zero based)
    :param lmax: optional maximum L to use from the cls arrays
    :param lmax_lensed: optional maximum L for the returned cl array (lmax_lensed <= lmax)
    :param sampling_factor: npoints = int(sampling_factor*lmax)+1
    :param delta_cls: if true, return the difference between lensed and unlensed (optional, default False)
    :param theta_max: maximum angle (in radians) to keep in the correlation functions; default: pi/32
    :param apodize_point_width: if theta_max is set, apodize around the cut using half Gaussian of approx
        width apodize_point_width/lmax*pi
    :param leggaus: whether to use Gauss-Legendre integration (default True)
    :param cache: if leggaus = True, set cache to save the x values and weights between calls (most of the time)
    :return: 2D array of cls[L, ix], with L starting at zero and ix=0,1,2,3 in order TT, EE, BB, TE.
        cls include :math:`\ell(\ell+1)/2\pi` factors.


r"""
    Get derivative dcl of lensed :math:`D_\ell\equiv \ell(\ell+1)C_\ell/2\pi` with respect to :math:`\log(C^{\phi}_L)`.
    To leading order (and hence not actually accurate), the lensed correction to power spectrum ix
    is given by dcl[ix,:,:].dot(np.ones(clpp.shape)).

    Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of
    `astro-ph/0601594 <http://arxiv.org/abs/astro-ph/0601594>`_, to second order in :math:`C_{{\rm gl},2}`

    :param cls: 2D array of unlensed cls(L,ix), with L starting at zero and ix=0,1,2,3 in order TT, EE, BB, TE.
        cls should include :math:`\ell(\ell+1)/2\pi` factors.
    :param clpp: array of :math:`[L(L+1)]^2 C_L^{\phi\phi}/2\pi` lensing potential power spectrum (zero based)
    :param lmax: optional maximum L to use from the cls arrays
    :param theta_max: maximum angle (in radians) to keep in the correlation functions
    :param apodize_point_width: if theta_max is set, apodize around the cut using half Gaussian of approx
        width apodize_point_width/lmax*pi
    :param sampling_factor: npoints = int(sampling_factor*lmax)+1
    :return: array dCL[ix, ell, L], where ix=0,1,2,3 are T, EE, BB, TE and result is :math:`d[D^{\rm ix}_\ell]/ d (\log C^{\phi}_L)`


r"""
    Get derivative dcl of lensed minus unlensed power :math:`D_\ell \equiv \ell(\ell+1)\Delta C_\ell/2\pi` with respect
    to :math:`\ell(\ell+1)C^{\rm unlens}_\ell/2\pi`

    The difference in power in the lensed spectrum is given by dCL[ix, :, :].dot(cl),
    where cl is the appropriate :math:`\ell(\ell+1)C^{\rm unlens}_\ell/2\pi`.

    Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of
    `astro-ph/0601594 <http://arxiv.org/abs/astro-ph/0601594>`_, to second order in :math:`C_{{\rm gl},2}`

    :param clpp: array of :math:`[L(L+1)]^2 C_L^{\phi\phi}/2\pi` lensing potential power spectrum (zero based)
    :param lmax: optional maximum L to use from the clpp array
    :param theta_max: maximum angle (in radians) to keep in the correlation functions
    :param apodize_point_width: if theta_max is set, apodize around the cut using half Gaussian of approx
        width apodize_point_width/lmax*pi
    :param sampling_factor: npoints = int(sampling_factor*lmax)+1
    :return: array dCL[ix, ell, L], where ix=0,1,2,3 are TT, EE, BB, TE and result is
         :math:`d\left(\Delta D^{\rm ix}_\ell\right) / d D^{{\rm unlens},j}_L` where j[ix] are TT, EE, EE, TE


        Get transfer function (function of q, for each q in self.q_trans) by name for given redshift index

        :param name:  parameter name
        :param z_index: which redshift
        :return: array of transfer function values for each calculated k


        Calculate the background evolution without calculating thermal history.
        e.g. call this if you want to just use :meth:`angular_diameter_distance` and similar background functions

        :param params:  :class:`.model.CAMBparams` instance to use


        Calculate the background evolution and thermal history.
        e.g. call this if you want to get derived parameters and call background functions
        :param params:  :class:`.model.CAMBparams` instance to use


        Calculate the transfer functions (for CMB and matter power, as determined by params.WantCls, params.WantTransfer)

        :param params: :class:`.model.CAMBparams` instance with parameters to use
        :param only_transfers: only calculate transfer functions, no power spectra
        :return: non-zero if error, zero if OK


        Calculates transfer functions and power spectra.

        :param params: optional :class:`.model.CAMBparams` instance with parameters to use


        Assuming :meth:`calc_transfers` or :meth:`calc_power_spectra` have already been used, re-calculate the power spectra
        using a new set of initial power spectrum parameters with otherwise the same cosmology.
        This is typically much faster that re-calculating everything, as the transfer functions can be re-used.

        :param initial_power_params: :class:`.initialpower.InitialPowerParams` instance with new primordial power spectrum parameters


r"""
        Save CMB power to a plain text file. Output is lensed total :math:`\ell(\ell+1)C_\ell/2\pi` then lensing potential and cross: L TT EE BB TE PP PT PE.

        :param filename: filename to save
        :param lmax: lmax to save
        :param CMB_unit: scale results from dimensionless. Use 'muK' for :math:`\mu K^2` units for CMB :math:`C_\ell` and :math:`\mu K` units for lensing cross.


        Get (non-comoving) angular diameter distance to redshift z.

        Must have called :meth:`calc_background`, :meth:`calc_background_no_thermo` or calculated transfer functions or power spectra.

        :param z: redshift or array of redshifts
        :return: angular diameter distances, matching rank of z


r"""
        Get angular diameter distance between two redshifts
        :math:`\frac{r}{1+z_2}\text{sin}_K\left(\frac{\chi(z_2) - \chi(z_1)}{r}\right)`
        where :math:`r` is curvature radius and :math:`\chi` is the comoving radial distance.

        Must have called :meth:`calc_background`, :meth:`calc_background_no_thermo` or calculated transfer functions or power spectra.

        :param z1: redshift 1
        :param z2: redshift 2
        :return: result


        Get comoving radial distance from us to redshift z in Mpc. This is efficient for arrays.

        Must have called :meth:`calc_background`, :meth:`calc_background_no_thermo` or calculated transfer functions or power spectra.

        :param z: redshift
        :return: comoving radial distance (Mpc)


        Convert comoving radial distance array to redshift array.
        This is not calculated directly, but fit from a spline to a forward calculation of chi from z.
        This is a utility routine, not optimized to be fast (though it can work on a large vector efficiently)

        :param chi: comoving radial distance (in Mpc), scalar or array
        :param nz_step: number of redshifts calculated internally for solving grid
        :param zmax: maximum redshift in internal solving grid
        :return: redshift at chi, scalar or array


        Get luminosity distance from to redshift z.

        Must have called :meth:`calc_background`, :meth:`calc_background_no_thermo` or calculated transfer functions or power spectra.

        :param z: redshift or array of redshifts
        :return: luminosity distance (matches rank of z)


r"""
        Get Hubble rate at redshift z, in :math:`{\rm Mpc}^{-1}` units, scalar or array

        Must have called :meth:`calc_background`, :meth:`calc_background_no_thermo` or calculated transfer functions or power spectra.

        Use hubble_parameter instead if you want in [km/s/Mpc] units.

        :param z: redshift
        :return: H(z)


        Get Hubble rate at redshift z, in km/s/Mpc units. Scalar or array.

        Must have called :meth:`calc_background`, :meth:`calc_background_no_thermo` or calculated transfer functions or power spectra.

        :param z: redshift
        :return: H(z)/[km/s/Mpc]


        Get physical time between two scalar factors in Gigayears

        Must have called :meth:`calc_background`, :meth:`calc_background_no_thermo` or calculated transfer functions or power spectra.

        :param a1: scale factor 1
        :param a2: scale factor 2
        :return: (age(a2)-age(a1))/Gigayear


        Conformal time from hot big bang to redshift z in Megaparsec.
        Use comoving_radial_distance for faster result for arrays.

        :param z: redshift or array of redshifts
        :return: eta(z)/Mpc


r"""
        Get :math:`\theta_{\rm MC}`, an approximation of the ratio of the sound horizon to the angular diameter distance at recombination.

        :return: :math:`\theta_{\rm MC}`


        Do these settings have non-zero tensors?

        :return: True of non-zero tensor amplitude


    Compute |o - n| / |o| < tol
    :param o: The old value
    :param n: The new value
    :param tol: toleranace
    :return: True when |o - n| / |o| < tol, false else


    Return true when want_CMB is set in the ini file and l_max_scalar is >= 2000.
    :param ini: The dictionary all inifile settings.
    :return: True, when want_CMB and l_max_scalar >= 2000, false else.


    Return true when want_CMB is set.
    :param ini: The dictionary all inifile settings.
    :return: True, when want_CMB is set.


    Check whether two files are numerically unequal for the given compare function.
    :param filename: The base name of the files to check.
    :param cmpFcn: The default comparison function. Can be overriden by the filetolmatrix.
    :return: True, when the files do not match, false else.


    Need to implement our own split, because for exponents of three digits
    the 'E' marking the exponent is dropped, which is not supported by python.
    :param s: The string to split.
    :return: An array containing the mantissa and the exponent, or the value, when no split was possible.


    Do a textual comparison for numbers whose exponent is zero or greater.
    The fortran code writes floating point values, with 5 significant digits
    after the comma and an exponent. I.e., for numbers with a positive
    exponent the usual comparison against a delta fails.
    :param o: The old value.
    :param n: The new value.
    :param tolerance: The allowed tolerance.
    :return: True, when |o - n| is greater then the tolerance allows, false else.


Stream all model parameters to rank 0 on the CPU, then pass all
    other given arguments to `torch.save` to save the model, but only on
    the root process.


Forward pass for the encoder.

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

        Returns:
            Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: Encoded tensors from each layer.


Forward pass for the decoder, concatenating the encoder outputs with the bottleneck.

        Args:
            enc1, enc2, enc3, enc4 (torch.Tensor): Encoder outputs.
            bottleneck (torch.Tensor): Bottleneck tensor from the transformer.

        Returns:
            torch.Tensor: Final output tensor.


Forward pass of the model.

        Args:
            batch (dict[str, torch.Tensor]): Dictionary containing input data, lead time, and static inputs.

        Returns:
            torch.Tensor: The final output of the model.


Perform a validation step.

        Args:
            batch (dict[str, torch.Tensor]): Input batch for validation.
            batch_idx (int, optional): Batch index.

        Returns:
            torch.Tensor: Validation loss.


Returns a DataLoader for the training data.


Returns a DataLoader for the validation data.


Returns a DataLoader for the prediction data.


Count the total number of parameters in a model that are used in the forward pass
    and have `requires_grad=True`.

    Args:
        model (torch.nn.Module): The PyTorch model.

    Returns:
        int: The total number of parameters used in the forward pass.


Train the model using the specified configuration and rank.

    Args:
        cfg: The configuration object containing hyperparameters and paths.
        rank: The rank of the process in distributed training.


    Loads all objects needed to interpolate and analyze the isochrones.
    All inputs are listed in the input file to make things easier and
    because they are referenced elsewhere.

    Returns
    -------
    isobundle : tuple
        (magobs, magerr, maglam, magname, interps, limits, fehs,
         ages, maxmasses, wdmagfunc)


    Return initial error estimates in each parameter.
    Used to start the MCMC chains in a small ball near an estimated solution.

    Input
    -----
    p : ndarray
        Model parameters. See light_curve_model for the order.

    Returns
    -------
    errs : ndarray
        The standard deviation to use in each parameter
        for MCMC walker initialization.


    Interpolate the isochrones to predict the desired observables
    (listed in the variable magname) at a particular mass, age, and
    Fe/H. We find the bounding 4 combinations of Fe/H and age in the
    isochrone grid, and predict the observables at these 4 (Fe/H,age)
    combinations at the input mass using the mass interpolation
    [e.g. interps[Fe/H,age](Mass)]. We then perform a bilinear
    interpolation of these 4 (Fe/H,age) locations to get to the
    predicted observables at the input Fe/H and age.

    Input
    -----
    M : float
        Input mass (solar)
    FeH : float
        Input metallicity [Fe/H]
    age : float
        Input age (log10(yr))
    isobundle : tuple
        Contains everything needed for the isochrones
    testvalid : bool, optional
        If True, returns a boolean indicating whether this combination of
        inputs is within the bounds of the isochrones.

    Returns
    -------
    result : ndarray
        Interpolated values of all parameters listed in magname.


    Return the liftime of a star of mass M and metallicity FeH based
    on the isochrones in the isobundle.

    Returns
    Input
    -----
    M : float
        Input mass (solar)
    FeH : float
        Input metallicity [Fe/H]
    isobundle : tuple
        Contains everything needed for the isochrones

    Returns
    -------
    finalage : float
        log10(lifetime [years]) of the star


    Simple Kepler solver.
    Iterative solution via Newton's method. Could likely be sped up,
    but this works for now; it's not the major roadblock in the code.

    Input
    -----
    M : ndarray
    e : float or ndarray of same size as M

    Returns
    -------
    E : ndarray


    Given the orbital parameters in p, compute a model light curve at times
    t, sampling at the rate of npert.

    Input
    -----
    t : ndarray
        Times to return the model light curve.
    p : ndarray
        Orbital parameters. Currently must contain:
        period, time of center of transit, ecos(omega), esin(omega),
        impact parameter, initial mass of star 2, current mass of star 2,
        mass of star 1, metallicity of star 1, log age of the system,
        distance, systematic magnitude errors, dust scale height,
        and the total extinction A_lambda.
        Can also add optional 2 parameters for quadratic limb
        darkening of star 1.
    isobundle : tuple
        (magobs, magerr, maglam, magname, interps, limits, fehs, ages,
         maxmasses, wdmagfunc)
        Contains everything needed for the isochrones
    npert : int, optional
        Sampling rate per cadence. Final light curve will average each
        cadence over this many samples.

    Returns
    -------
    fluxes : ndarray
        Light curve corresponding to the times in t.


    Priors on the input parameters.

    Input
    -----
    p : ndarray
        Orbital parameters. See light_curve_model for the order.
    isobundle : tuple
        Contains everything needed for the isochrones

    Returns
    -------
    prior : float
        Log likelihood of this set of input parameters based on the
        priors.


    Compute the log likelihood of a microlensing signal with these orbital
    parameters given the data. By default returns this value, but can
    optionally return the full model light curve or just the polynomial
    portion of the light curve instead.

    Input
    -----
    p : ndarray
        Orbital parameters. See light_curve_model for the order.
    t, f, ferr : ndarray
        times, fluxes, and flux errors of the data.
    cuts : ndarray
        Same length as t. Says which group each cadence belongs to,
        starting with 0. E.g. all cadences with cuts == 0 will be
        assumed to be one event. Each event must be equal length.
    isobundle : tuple
        Contains everything needed for the isochrones
    crowding : ndarray
        Must be an array of len(cuts)-1
        indicating what fraction of the light is due to the binary system.
        1 - crowding is the contamination from outside sources.
        If purely light from the system in question, should be just
        np.ones(len(cuts)-1)
    minimize : boolean, optional
        If True, we are trying to minimize the chi-square rather than
        maximize the likelihood. Default False.
    retmodel : boolean, optional
        If True, return the model fluxes instead of the log likelihood.
        Default False.
    retpoly : boolean, optional
        If True, return the polynomial portion of the model fluxes
        instead of the log likelihood. Default False.
    indchi : boolean, optional
        If True, return the chi-square of each individual event.
        Default False.

    Returns
    ------
    likeli : float
        Log likelihood that the model fits the data.


    Get the log probability of the data given the priors and the model.
    See loglikeli for the input parameters.

    Also requires npert (the number of subsamples to divide a cadence into).

    Returns
    -------
    prob : float
        Log likelihood of the model given the data and priors, up to a
        constant.


    Adaptation of the Mandel & Agol transit light curve for quadratic limb
    darkening.

    Parameters
    ----------
    z : ndarray
        Impact parameters at which to evaluate the flux.
    u1 : float
        Linear limb darkening term
    u2 : float
        Quadratic limb darkening term
    p0 : float
        Radius ratio of the transiting object to the occulted object

    Returns
    -------
    fdark : ndarray
        Limb darkened flux at all points in z
    fflat : ndarray
        Flux without any limb darkening.


    Load Kepler light curves.

    Parameters
    ----------
    files : list of strings
        The locations of the light curves to load together.
    usepdc : bool, optional
        Set to True to load the PDC light curves instead of the
        default SAP.

    Returns
    -------
    time : ndarray
        Kepler times of center of exposure
    flux : ndarray
        Kepler normalized fluxes
    fluxerr : ndarray
        Kepler flux errors
    cadence : ndarray
        Kepler cadence number
    quarter : ndarray
        Kepler quarter
    quality : ndarray
        Kepler quality flag


    Load Kepler light curves, then process them for analysis.

    Parameters
    ----------
    KIC : int
        The Kepler ID for the system to look at
    dataloc : string, optional
        Directory point to the location of the Kepler light curves.
        Default can be changed in the module initialization.
    fill : boolean, optional
        Should we fill in all missing cadences? If true, will
        interpolate times to all missing cadences and assign them
        flux with np.inf errors. Necessary for QATS requiring
        continuous data. Default True.
    badflags : tuple, optional
        Flags that can be set by Kepler that we should take seriously
        and ignore.
        Set all cadences with these flags to have infinite errors.
        Default 128 and 2048.
    ignorelist : string, optional
        File containing regions of time to ignore. File contents should
        be 2 columns, with start and end times (in times already
        adjusted by inp.timeoffset). Defaults to the file listed in the
        module.

    Returns
    -------
    time : ndarray
        Kepler times of center of exposure
    flux : ndarray
        Kepler normalized fluxes
    fluxerr : ndarray
        Kepler flux errors
    cadence : ndarray
        Cadence number, starting at 0
    quarter : ndarray
        Kepler quarter
    quality : ndarray
        Kepler quality flag


ts in days


Makes the Nmatrix used in the fstatistic


        Computes the Fe-statistic (see Ellis, Siemens, Creighton 2012).

        :param log10_F: log10 GW frequency
        :param gw_skyloc: 2x{number of sky locations} array containing [theta, phi] for each queried sky location,
                          where theta=pi/2-DEC, phi=RA,
                          for singlge sky location use gw_skyloc= np.array([[theta,],[phi,]])
        :param brave: Skip sanity checks in linalg for speedup if True.
        :param maximized_parameters: Calculate maximized extrinsic parameters if True.

        :returns:
            fstat: value of the Fe-statistic
        :if maximized_parameters=True also returns:
            inc_max: Maximized value of inclination
            psi_max: Maximized value of polarization angle
            phase0_max: Maximized value of initial fhase
            h_max: Maximized value of amplitude


r"""
    Compute inner product using rank-reduced
    approximations for red noise/jitter
    Compute: x^T N^{-1} y - x^T N^{-1} T \Sigma^{-1} T^T N^{-1} y

    :param x: vector timeseries 1
    :param y: vector timeseries 2
    :param Nmat: white noise matrix
    :param Tmat: Modified design matrix including red noise/jitter
    :param Sigma: Sigma matrix (\varphi^{-1} + T^T N^{-1} T)
    :param TNx: T^T N^{-1} x precomputed
    :param TNy: T^T N^{-1} y precomputed
    :return: inner product (x|y)


    ======================================================================================================================
    PARAM       DESCRIPTION                             UNIT        EXPRESSION              COMMENTS
    ======================================================================================================================
    toas        are Pulsar TOAs                         in s                                (Taken from the Pulsar object)

    theta       is  Polar angle of pulsar               in rad      = pi/2 - DEC_psr        (Taken from the Pulsar object)
    phi         is  Azimuthal angle of pulsar           in rad      = RA_psr                (Taken from the Pulsar object)
    pdist       is  distance to pulsar (value,error)    in kpc                              (Taken from the Pulsar object)

    p_dist      is  Pulsar distance prior               in kpc                              (Parametrizes the departure from the measured pulsar distance given in pdist.)

    cos_gwtheta is  Cos of Polar angle of GW source     in rad      = cos(pi/2 - DEC_GW)
    gwphi       is  Azimithal angle of GW source        in rad      = RA_GW

    psi         is  Polarization angle                  in rad
    cos_inc     is  Cos of Inclination of GW source     in rad      = cos(i)

    log10_M     is  log10 Total Mass of GW src          in MSun     = log10(M)              (Not to be confused with the chirp mass.)
    q           is  Mass ratio of GW source                         = m1/m2

    log10_F     is  log10 GW frequency at t=tref        in Hz       = log10(2/Pb0)
    e0          is  Eccentricity at t=tref
    gamma0      is  Periastron angle at t=tref          in rad
    l0          is  Mean anomaly at t=tref              in rad                              (Should be set to zero if tref is a free parameter.)
    tref        is  Reference time                      in s                                (Should be set to a fixed epoch if l0 is a free parameter.)

    log10_zc    is  log10 cosmological redshift
    zp          is  Peculiar redshift

    psrTerm     is  [boolean] Whether to add pulsar term

    evolve      is  [boolean] Whether to evolve phase exactly                               Not implemented (Always True)

    ======================================================================================================================

    Returns:
            TOA delays due to GWs from eccentric binary sources (in s)


    ======================================================================================================================
    PARAM       DESCRIPTION                             UNIT        EXPRESSION              COMMENTS
    ======================================================================================================================
    toas        are Pulsar TOAs                         in s                                (Taken from the Pulsar object)

    theta       is  Polar angle of pulsar               in rad      = pi/2 - DEC_psr        (Taken from the Pulsar object)
    phi         is  Azimuthal angle of pulsar           in rad      = RA_psr                (Taken from the Pulsar object)
    pdist       is  distance to pulsar (value,error)    in kpc                              (Taken from the Pulsar object)

    p_dist      is  Pulsar distance prior               in kpc                              (Parametrizes the departure from the measured pulsar distance given in pdist.)

    cos_gwtheta is  Cos of Polar angle of GW source     in rad      = cos(pi/2 - DEC_GW)
    gwphi       is  Azimithal angle of GW source        in rad      = RA_GW

    log10_dist  is  log10 distance to GW source         in Mpc      = log10(D_GW)           (One and only one of log10_dist and log10_h should be used.)

    log10_h     is  log10 GW amplitude at tref                      = log10(H0)             (One and only one of log10_dist and log10_h should be used.)

    psi         is  Polarization angle                  in rad
    cos_inc     is  Cos of Inclination of GW source     in rad      = cos(i)

    log10_M     is  log10 Total Mass of GW src          in MSun     = log10(M)              (Not to be confused with the chirp mass.)
    q           is  Mass ratio of GW source                         = m1/m2

    log10_F     is  log10 GW frequency at t=tref        in Hz       = log10(2/Pb0)
    e0          is  Eccentricity at t=tref
    gamma0      is  Periastron angle at t=tref          in rad
    l0          is  Mean anomaly at t=tref              in rad                              (Should be set to zero if tref is a free parameter.)
    tref        is  Reference time                      in s                                (Should be set to a fixed epoch if l0 is a free parameter.)

    log10_zc    is  log10 cosmological redshift
    zp          is  Peculiar redshift

    psrTerm     is  [boolean] Whether to add pulsar term

    evolve      is  [boolean] Whether to evolve phase exactly                               Not implemented (Always True)

    ======================================================================================================================

    Returns:
            TOA delays due to GWs from eccentric binary sources (in s)


enterprise_extensios-style convinience function for creating a Signal for GWecc


    ======================================================================================================================
    PARAM       DESCRIPTION                             UNIT        EXPRESSION              COMMENTS
    ======================================================================================================================
    toas        are Pulsar TOAs                         in s                                (Taken from the Pulsar object)

    theta       is  Polar angle of pulsar               in rad      = pi/2 - DEC_psr        (Taken from the Pulsar object)
    phi         is  Azimuthal angle of pulsar           in rad      = RA_psr                (Taken from the Pulsar object)
    pdist       is  distance to pulsar (value,error)    in kpc                              (Taken from the Pulsar object)

    p_dist      is  Pulsar distance prior               in kpc                              (Parametrizes the departure from the measured pulsar distance given in pdist.)

    cos_gwtheta is  Cos of Polar angle of GW source     in rad      = cos(pi/2 - DEC_GW)
    gwphi       is  Azimithal angle of GW source        in rad      = RA_GW

    log10_dist  is  log10 distance to GW source         in Mpc      = log10(D_GW)           (One and only one of log10_dist and log10_h should be used.)

    log10_h     is  log10 GW amplitude at tref                      = log10(H0)             (One and only one of log10_dist and log10_h should be used.)

    psi         is  Polarization angle                  in rad
    cos_inc     is  Cos of Inclination of GW source     in rad      = cos(i)

    log10_M     is  log10 Total Mass of GW src          in MSun     = log10(M)              (Not to be confused with the chirp mass.)
    q           is  Mass ratio of GW source                         = m1/m2

    log10_F     is  log10 GW frequency at t=tref        in Hz       = log10(2/Pb0)
    e0          is  Eccentricity at t=tref
    gamma0      is  Periastron angle at t=tref          in rad
    l0          is  Mean anomaly at t=tref              in rad                              (Should be set to zero if tref is a free parameter.)
    tref        is  Reference time                      in s                                (Should be set to a fixed epoch if l0 is a free parameter.)

    z           is  redshift

    psrTerm     is  [boolean] Whether to add pulsar term

    evolve      is  [boolean] Whether to evolve phase exactly                               Not implemented (Always True)

    ======================================================================================================================

    Returns:
            TOA delays due to GWs from eccentric binary sources (in s)


Values of the data to compute the Genus statistics at.


Cramer distance between `cube1` and `cube2`.


Return tuple of more generic types.

    Allows for more flexible type checking in the case when a Parameter's value
    changes precision or to/from a numpy dtype but still is the desired generic type.
    If a generic type cannot be found, the expected_type is returned

    Parameters
    ----------
    expected_type : Type or string or list of types or strings
        The expected type of a Parameter object or a string of the name of a type. Lists
        are only for recarray parameters and in that case the input expected_type is
        returned exactly.
    strict_type_check : bool
        If True, the input expected_type is returned exactly.

    Returns
    -------
    Tuple of types based on input expected_type


    Test if dicts are equal for parameter equality.

    Helper function pulled out to allow recursion for nested dicts


        Get the expected shape of the value based on the form.

        Parameters
        ----------
        uvbase : object
            Object with this UVParameter as an attribute. Needed
            because the form can refer to other UVParameters on this object.

        Returns
        -------
        tuple
            The expected shape of the value.


Check that values are acceptable.


        Compare UVParameter value to a supplied value.

        Parameters
        ----------
        value
            The value to compare against that stored in the UVParameter object. Must
            be the same type.

        Returns
        -------
        same : bool
            True if the values are equivalent (or within specified tolerances),
            otherwise false.


Get value in degrees.


Detect if this location is on the moon.


Get the frame.


Get the ellipsoid.


Get the body centric coordinates in meters.


Get value in (latitude, longitude, altitude) tuple in radians.


Get value in (latitude, longitude, altitude) tuple in degrees.


Check that value is an allowed object type.


    Improve the printing of user warnings.

    Parameters
    ----------
    msg : str
        Input warning message.
    a
        postional parameters not used by this formatting method.
    kwargs
        named parameters not used by this formatting method.

    Returns
    -------
    str
        Input warning message with new line character appended to improve warning
        formatting.


Set up parameter objects to be able to be referenced by their names.


        Getter method for UVParameter properties.

        Parameters
        ----------
        param_name : str
            Property name to get, corresponds the the UVParameter.name.

        Returns
        -------
        fget
            getter method to use for the property definition.


        Setter method for UVParameter properties.

        Parameters
        ----------
        param_name : str
            Property name to set, corresponds the the UVParameter.name.

        Returns
        -------
        fset
            setter method to use for the property definition.


        Degree getter method for AngleParameter properties.

        Parameters
        ----------
        param_name : str
            Property name to get, corresponds the the UVParameter.name with "_degrees"
            appended.

        Returns
        -------
        fget
            getter method to use for the property definition.


        Degree setter method for AngleParameter properties.

        Parameters
        ----------
        param_name : str
            Property name to set, corresponds the the UVParameter.name with "_degrees"
            appended.

        Returns
        -------
        fset
            setter method to use for the property definition.


        Lat/lon/alt getter method for LocationParameter properties.

        Parameters
        ----------
        param_name : str
            Property name to get, corresponds the the UVParameter.name with
            "_lat_lon_alt" appended.

        Returns
        -------
        fget
            getter method to use for the property definition.


        Lat/lon/alt setter method for LocationParameter properties.

        Parameters
        ----------
        param_name : str
            Property name to set, corresponds the the UVParameter.name with
            "_lat_lon_alt" appended.

        Returns
        -------
        fset
            setter method to use for the property definition.


        Lat/lon/alt degree getter method for LocationParameter properties.

        Parameters
        ----------
        param_name : str
            Property name to get, corresponds the the UVParameter.name with
            "_lat_lon_alt_degrees" appended.

        Returns
        -------
        fget
            getter method to use for the property definition.


        Lat/lon/alt degree setter method for LocationParameter properties.

        Parameters
        ----------
        param_name : str
            Property name to set, corresponds the the UVParameter.name with
            "_lat_lon_alt_degrees" appended.

        Returns
        -------
        fset
            setter method to use for the property definition.


        Iterate over all required UVParameter attributes.

        Yields
        ------
        UVParameter
            required UVParameters on this object.


        Iterate over all non-required UVParameter attributes.

        Yields
        ------
        UVParameter
            optional (non-required) UVParameters on this object.


        Check that required parameters exist and have the correct shapes.

        Optionally, check that the values are acceptable.

        Parameters
        ----------
        check_extra : bool
            If true, check shapes and values on all parameters,
            otherwise only check required parameters.
        run_check_acceptability : bool
            Option to check if values in parameters are acceptable.
        ignore_requirements : bool
            Do not error if a required parameter isn't set.
            This allows the user to run the shape/acceptability checks
            on parameters in a partially-defined UVData object.

        Returns
        -------
        bool
            True if the checks pass.

        Raises
        ------
        ValueError
            If required UVParameter values have not been set or if set UVParameters
            values do not have the expected names, shapes, types or values.


        Make and return a copy of the object.

        Returns
        -------
        UVBase
            A deep copy of this object.


        Downselect values along a parameterized axis.

        This method should not be called directly by users; instead, it is called by
        various selection-related functions for selecting a subset of values along
        a given axis, whose expected shape is given (at least in part) by a named
        parameter within the object (e.g., "Nblts", "Ntimes", "Nants"). Additionally,
        this method will recalculate the value for the named parameter given the input
        indexing array.

        Parameters
        ----------
        param_dict : dict
            Dictionary which maps axes to index arrays, with keys that are matched
            against entries within UVParameter.form, and values which demark which
            indices should be selected (must be 1D). Values can also be given as None,
            in which case no selection is performed along that axis.


Combine docstrings from multiple sources programmatically.

    The guts of this function are taken from the `docstring_parser` package.
    What it does differently is that it notices if a kwargs item is present in
    the signature, and writes parameters in the subdocs to Other Parameters.

    A function decorator that parses the docstrings from `others`,
    programmatically combines them with the parsed docstring of the decorated
    function, and replaces the docstring of the decorated function with the
    composed result. Only parameters that are part of the decorated functions
    signature are included in the combined docstring. When multiple sources for
    a parameter or docstring metadata exists then the decorator will first
    default to the wrapped function's value (when available) and otherwise use
    the rightmost definition from ``others``.


Copy the long description and parameters section(s) from another docstring.


Globally ignore update warnings for a given telescope.

    This affects the :meth:`Telescope.update_params_from_known_telescopes` method,
    which updates unspecified telescope information with known information from
    a KNOWN_TELESCOPE. In some cases, you will know that many files have
    unspecified information and that it is OK to supply this information from the
    known info in pyuvdata. Ignoring warnings can be achieved by setting `warn=False`
    in that method, but this is sometimes difficult because it is called further
    up in the stack. This simple convenience method allows all such warnings for a
    given telescope to be ignored.


Globally un-ignore update warnings for a given telescope.

    See :func:`ignore_telescope_param_update_warnings`


    Get list of known telescopes.

    Returns
    -------
    list of str
        List of known telescope names.


    Get the location for a known telescope.

    Parameters
    ----------
    name : str
        Name of the telescope
    return_citation : bool
        Option to return the citation.
    location : EarthLocation or MoonLocation
        Location of the telescope, can be used to overwrite or supplement information in
        the KNOWN_TELESCOPES dictionary.
    citation : str
        Source of location information, can be used to overwrite or supplement
        information in the KNOWN_TELESCOPES dictionary.

    Returns
    -------
    location : EarthLocation
        Telescope location as an EarthLocation object.
    citation : str, optional
        Citation string.


        Add some extra checks on top of checks on UVBase class.

        Check that required parameters exist. Check that parameters have
        appropriate shapes and optionally that the values are acceptable.

        Parameters
        ----------
        check_extra : bool
            If true, check all parameters, otherwise only check required parameters.
        run_check_acceptability : bool
            Option to check if values in parameters are acceptable.

        Returns
        -------
        bool
            True if check passes

        Raises
        ------
        ValueError
            if parameter shapes or types are wrong or do not have acceptable
            values (if run_check_acceptability is True)


        Update the parameters based on telescope in known_telescopes.

        This fills in any missing parameters (or to overwrite parameters that
        have inaccurate values) on self that are available for a telescope from
        either Astropy sites and/or from the KNOWN_TELESCOPES dict. This is
        primarily used on UVData, UVCal and UVFlag to fill in information that
        is missing, especially in older files.

        Parameters
        ----------
        overwrite : bool
            If set, overwrite parameters with information from Astropy sites
            and/or from the KNOWN_TELESCOPES dict. Defaults to False.
        warn : bool
            Option to issue a warning listing all modified parameters.
            Defaults to True.
        run_check : bool
            Option to check for the existence and proper shapes of parameters
            after updating.
        check_extra : bool
            Option to check optional parameters as well as required ones.
        run_check_acceptability : bool
            Option to check acceptable range of the values of parameters after
            updating.
        override_known_params : bool
            Normally, when passing arguments for individual parameters for the Telescope
            object, they will be used over what is present in the KNOWN_TELESCOPES dict.
            However, if set to False, the information in the KNOWN_TELESCOPES dict is
            used if/when present, even if supplied as an argument when calling this
            method. Default is True.
        x_orientation : str
            String describing how the x-orientation is oriented. Must be either "north"/
            "n"/"ns" (x-polarization of antenna has a position angle of 0 degrees with
            respect to zenith/north) or "east"/"e"/"ew" (x-polarization of antenna has a
            position angle of 90 degrees with respect to zenith/north). Ignored if
            "x_orientation" is relevant entry for the KNOWN_TELESCOPES dict, or if
            feed_array and feed_angle supplied (either by passing an argument or in the
            KNOWN_TELESCOPES dict).
        feeds : list of str or None
            List of strings denoting feed orientations/polarizations. Must be one of
            "x", "y", "l", "r" (the former two for linearly polarized feeds, the latter
            for circularly polarized feeds). Default assumes a pair of linearly
            polarized feeds (["x", "y"]).
        polarization_array : array-like of int or None
            Array listing the polarization codes present, based on the UVFITS numbering
            scheme. See utils.POL_NUM2STR_DICT for a mapping between codes and
            polarization types. Used with `utils.pol.get_feeds_from_pols` to determine
            feeds present if not supplied, ignored if flex_polarization_array is set
            to anything but None.
        flex_polarization_array : array-like of int or None
            Array listing the polarization codes present per spectral window (used with
            certain "flexible-polarization" objects), based on the UVFITS numbering
            scheme. See utils.POL_NUM2STR_DICT for a mapping between codes and
            polarization types. Used with `utils.pol.get_feeds_from_pols` to determine
            feeds present if not supplied.
        location : EarthLocation or MoonLocation
            Location of the telescope (phase reference position).
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        citation : str
            Source of telescope information.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        antenna_positions_file : str
            Path to a csv-formatted file containing a total of five columns, which
            describe (on a per-antenna basis) the name, number, and x/y/z location
            (relative to the phase center, units of meters) of each antenna.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        Nants : int
            Number of antennas present in the telescope.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        antenna_numbers : array-like of int
            Antenna numbers that correspond to entries in antenna_names, array-like
            of shape (Nants,), dtype int.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        antenna_names : array-like of str
            Names of the antennas present in the telescope object, array-like of shape
            (Nants,), dtype str.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        antenna_positions : array of float
            Coordinates of antennas relative to the telescope location, shape
            (Nants, 3), dtype float, units meters.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        mount_type : str or array-like of str
            Antenna mount type, which describes the optics for each antenna. Can either
            be supplied on a per-antenna basis, in which case an array of shape (Nants,)
            with dtype str is expected, or if all antennas share the same optics type, a
            single string can be provided (see supported types in the documentation for
            `Telescope.mount_type`).
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        feed_array : array-like of str
            Feed types present within each telescope in terms of polarization response,
            must be one of "r", "l", "x", or "y". Can be supplied on a per-antenna
            basis, in which case an array of shape (Nants, Nfeeds) is expected, or if
            the same for all antennas, an array of shape (Nfeeds,) can be provided (
            note that Nfeeds cannot be greater than 2).
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        feed_angle : array-like of float
            Relative receptor angle for each feed (see more information about his in the
            documentation for `Telescope.feed_angle`). Can be supplied on a per-antenna
            basis, in which case an array of shape (Nants, Nfeeds) is expected, or if
            the same for all antennas, an array of shape (Nfeeds,) can be provided (
            note that Nfeeds cannot be greater than 2). Expected dtype is float.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        antenna_diameters : float or array-like of float
            Diameter of the antennas within the telescope, dtype float, units of meters.
            Can be supplied on a per-antenna basis, in which case an array of shape
            (Nants,) is expected, or if the same for all antennas, a single float can
            be provided.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.

        Raises
        ------
        ValueError
            If self.name is not set or if ((location is missing or overwrite is
            set) and self.name is not found either astropy sites our our
            known_telescopes dict)


        Create a new Telescope object using information from known_telescopes.

        Parameters
        ----------
        name : str
            Name of the telescope.
        run_check : bool
            Option to check for the existence and proper shapes of parameters.
        check_extra : bool
            Option to check optional parameters as well as required ones.
        run_check_acceptability : bool
            Option to check acceptable range of the values of parameters.
        x_orientation : str
            String describing how the x-orientation is oriented. Must be either "north"/
            "n"/"ns" (x-polarization of antenna has a position angle of 0 degrees with
            respect to zenith/north) or "east"/"e"/"ew" (x-polarization of antenna has a
            position angle of 90 degrees with respect to zenith/north). Ignored if
            "x_orientation" is relevant entry for the KNOWN_TELESCOPES dict, or if
            feed_array and feed_angle supplied (either by passing an argument or in the
            KNOWN_TELESCOPES dict).
        feeds : list of str or None
            List of strings denoting feed orientations/polarizations. Must be one of
            "x", "y", "l", "r" (the former two for linearly polarized feeds, the latter
            for circularly polarized feeds). Default assumes a pair of linearly
            polarized feeds (["x", "y"]).
        polarization_array : array-like of int or None
            Array listing the polarization codes present, based on the UVFITS numbering
            scheme. See utils.POL_NUM2STR_DICT for a mapping between codes and
            polarization types. Used with `utils.pol.get_feeds_from_pols` to determine
            feeds present if not supplied, ignored if flex_polarization_array is set
            to anything but None.
        flex_polarization_array : array-like of int or None
            Array listing the polarization codes present per spectral window (used with
            certain "flexible-polarization" objects), based on the UVFITS numbering
            scheme. See utils.POL_NUM2STR_DICT for a mapping between codes and
            polarization types. Used with `utils.pol.get_feeds_from_pols` to determine
            feeds present if not supplied.
        override_known_params : bool
            Normally, when passing arguments for individual parameters for the Telescope
            object, they will be used over what is present in the KNOWN_TELESCOPES dict.
            However, if set to False, the information in the KNOWN_TELESCOPES dict is
            used if/when present, even if supplied as an argument when calling this
            method.
        location : EarthLocation or MoonLocation
            Location of the telescope (phase reference position).
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        citation : str
            Source of telescope information.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        antenna_positions_file : str
            Path to a csv-formatted file containing a total of five columns, which
            describe (on a per-antenna basis) the name, number, and x/y/z location
            (relative to the phase center, units of meters) of each antenna.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        Nants : int
            Number of antennas present in the telescope.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        antenna_numbers : array-like of int
            Antenna numbers that correspond to entries in antenna_names, array-like
            of shape (Nants,), dtype int.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        antenna_names : array-like of str
            Names of the antennas present in the telescope object, array-like of shape
            (Nants,), dtype str.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        antenna_positions : array of float
            Coordinates of antennas relative to the telescope location, shape
            (Nants, 3), dtype float, units meters.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        mount_type : str or array-like of str
            Antenna mount type, which describes the optics for each antenna. Can either
            be supplied on a per-antenna basis, in which case an array of shape (Nants,)
            with dtype str is expected, or if all antennas share the same optics type, a
            single string can be provided (see supported types in the documentation for
            `Telescope.mount_type`).
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        feed_array : array-like of str
            Feed types present within each telescope in terms of polarization response,
            must be one of "r", "l", "x", or "y". Can be supplied on a per-antenna
            basis, in which case an array of shape (Nants, Nfeeds) is expected, or if
            the same for all antennas, an array of shape (Nfeeds,) can be provided (
            note that Nfeeds cannot be greater than 2).
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        feed_angle : array-like of float
            Relative receptor angle for each feed (see more information about his in the
            documentation for `Telescope.feed_angle`). Can be supplied on a per-antenna
            basis, in which case an array of shape (Nants, Nfeeds) is expected, or if
            the same for all antennas, an array of shape (Nfeeds,) can be provided (
            note that Nfeeds cannot be greater than 2). Expected dtype is float.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.
        antenna_diameters : float or array-like of float
            Diameter of the antennas within the telescope, dtype float, units of meters.
            Can be supplied on a per-antenna basis, in which case an array of shape
            (Nants,) is expected, or if the same for all antennas, a single float can
            be provided.
            Ignored if information is present in KNOWN_TELESCOPES dict and
            override_known_params=False.

        Returns
        -------
        Telescope
            A new Telescope object populated with information from
            known_telescopes.


        Initialize a new Telescope object from keyword arguments.

        Parameters
        ----------
        name : str
            Telescope name.
        location : EarthLocation or MoonLocation object
            Telescope location as an astropy EarthLocation object or MoonLocation
            object.
        antenna_positions : ndarray of float or dict of ndarray of float
            Array of antenna positions in ECEF coordinates in meters.
            If a dict, keys can either be antenna numbers or antenna names, and
            values are position arrays. Keys are interpreted as antenna numbers
            if they are integers, otherwise they are interpreted as antenna names
            if strings. You cannot provide a mix of different types of keys.
        antenna_names : list or np.ndarray of str, optional
            List or array of antenna names. Not used if antenna_positions is a
            dict with string keys. Otherwise, if not provided, antenna numbers
            will be used to form the antenna_names, according to the antname_format.
        antenna_numbers : list or np.ndarray of int, optional
            List or array of antenna numbers. Not used if antenna_positions is a
            dict with integer keys. Otherwise, if not provided, antenna names
            will be used to form the antenna_numbers, but in this case the
            antenna_names must be strings that can be converted to integers.
        antname_format : str, optional
            Format string for antenna names. Default is '{0:03d}'.
        instrument : str, optional
            Instrument name.
        x_orientation : str
            Orientation of the x-axis. Options are 'east', 'north', 'e', 'n',
            'ew', 'ns'. Ignored if feed_array and feed_angle are provided.
        antenna_diameters :  list or np.ndarray of float, optional
            List or array of antenna diameters.
        feeds : list of str or None:
            List of feeds present in the Telescope, which must be one of "x", "y", "l",
            "r". Length of the list must be either 1 or 2. Used to populate feed_array
            and feed_angle parameters if only supplying x_orientation, default is
            ["x", "y"].
        feed_array : array-like of str or None
            List of feeds for each antenna in the Telescope object, must be one of
            "x", "y", "l", "r". Shape (Nants, Nfeeds), dtype str. Can also be shape
            (Nfeeds,), in which case the same values for feed_array are used for
            all antennas in the object.
        feed_angle : array-like of float or None
            Orientation of the feed with respect to zenith (or with respect to north if
            pointed at zenith). Units is in rads, x-polarization is nominally pi / 2,
            and x-polarization (as well as r- and l-polarizations) is nominally pi / 2.
            Shape (Nants, Nfeeds), dtype float.  Can also be shape (Nfeeds,), in which
            case the same values for feed_angle are used for all antennas in the object.
        mount_type : str or array-like of str
            Antenna mount type, which describes the optics of the antenna in question.
            Supported options include: "alt-az" (primary rotates in azimuth and
            elevation), "equatorial" (primary rotates in hour angle and declination)
            "orbiting" (antenna is in motion, and its orientation depends on orbital
            parameters), "x-y" (primary rotates first in the plane connecting east,
            west, and zenith, and then perpendicular to that plane),
            "alt-az+nasmyth-r" ("alt-az" mount with a right-handed 90-degree tertiary
            mirror), "alt-az+nasmyth-l" ("alt-az" mount with a left-handed 90-degree
            tertiary mirror), "phased" (antenna is "electronically steered" by
            summing the voltages of multiple elements, e.g. MWA), "fixed" (antenna
            beam pattern is fixed in azimuth and elevation, e.g., HERA), and "other"
            (also referred to in some formats as "bizarre"). See the "Conventions"
            page of the documentation for further details. Shape (Nants,), dtype str.
            Can also provide a single string, in which case the same mount_type is
            used for all antennas in the object.
        update_from_known : bool
            If set to True and the telescope name is found in the KNOWN_TELESCOPES
            dictionary, then any missing parameters will be filled in using the
            information from said dictionary if available. Otherwise if set to False,
            any missing parameters are left set to None. Default is True.

        Returns
        -------
        Telescope object
            A Telescope object with the specified metadata.


        Initialize a new Telescope object from an HDF5 file.

        The file must have a Header dataset that has the appropriate header
        items. UVH5, CalH5 and UVFlag HDF5 files have these.

        Parameters
        ----------
        path : str or Path or subclass of hdf5_utils.HDF5Meta
            The filename to read from.