    Combine NRS1 and NRS2 spectra into one Spec1D object.

    Parameters
    ----------
    sp1 : Spec1D object
       NRS1 spectrum.
    sp2 : Spec1D object
       NRS2 spectrum.

    Returns
    -------
    sp : Spec1D object
       Final combined Spec1D spectrum.

    Examples
    --------

    sp = joinspec(sp1,sp2)


    Stack multiple spectra of the same source.

    Parameters
    ----------
    splist : list
       List of Spec1D spectra of the same object.
    wdict : dict
       Dictionary with final wavelength parameters:
        "coef" with the coefficients, "npix" with the
        number of pixels, and "log" of True or False.

    Returns
    -------
    comb : Spec1D spectrum
       Combined spectrum.
    stack : Spec1D spectrum
       Resampled individual spectra.

    Examples
    --------

    comb,stack = stackspec(splist)


    Process multiple rate files using JWST calwebb_spec2 pipeline.
    This is the first step of running the SPyderwebb pipeline and
    starts with the rate files.

    Parameters
    ----------
    fileinput : list
       Glob command for the rate files.  For example,
         "jw02609006001_03101_0000?_nrs?/*_rate.fits".
    msadir : str, optional
       Directory of all the msa.fits files.  By default, they are
         assumed to be in the same directory as the rate.fits files.
    outdir : str, optional
       Main output directory.  Default is "./".
    clobber : bool, optional
       Overwrite any existing files.
    applywavecorr : bool, optional
       Apply the JWST cal pipeline wavecorr correction.  Default is True.
       NOTE, the wavelength used in extract.extract_slit() uses the WCS
       and *NOT* the wavelength array/extension which applywavecorr affects.
       The applyslitcorr parameter in extract.py controls the slit correction.

    Returns
    ------
    Nothing is returned.  Reduced files are written to disk.

    Examples
    --------

    process('jw02609006001_03101_0000?_nrs?/*_rate.fits',outdir='red')


    Process exposure image through the JWST calwebb_spec2 pipeline.

    Process multiple rate files using JWST calwebb_spec2 pipeline.
    This is the first step of running the SPyderwebb pipeline and
    starts with the rate files.

    Parameters
    ----------
    filename : str
       Name of the a single rate file.
    msadir : str, optional
       Directory of all the msa.fits files.  By default, they are
         assumed to be in the same directory as the rate.fits files.
    outdir : str, optional
       Main output directory.  Default is "./".
    clobber : bool, optional
       Overwrite any existing files.
    applywavecorr : bool, optional
       Apply the JWST cal pipeline wavecorr correction.  Default is True.

    Returns
    ------
    result :
       Output from the Spec2 pipeline.
    Reduced files are written to disk.

    Examples
    --------

    result = process_exp('jw02609006001_03101_00002_nrs1/jw02609006001_03101_00002_nrs1_rate.fits')


    Extract spectra from the JWST NIRSpec MSA data.
    This is step two in the SPyderWebb data reduction process.

    Parameters
    ----------
    obsname : str
       Observation name, i.e. 'jw02609007001_03101'.
    wdict : dict
       Dictionary with final wavelength parameters:
        "coef" with the coefficients, and "npix" with the
        number of pixels:
    outdir : str, optional
       Output directory name.  Default is the current directory.
    logger : logging object, optional
       Logging object.
    clobber : bool, optional
       Overwrite any existing files.
    redtag : str, optional
       Reduction tag to add at the end of files.  Default is "red".
    noback : bool, optional
       No background subtraction.  Default is False.
    fluxcorrfile : str, optional
       Flux correction file.  Default is no flux correction.
    applyslitcorr : bool, optional
       Apply slit corrections to the wavelengths.  Default is True.

    Returns
    -------
    Reduced data are written to files.  Nothing is returned.

    Examples
    --------

    reduce.reduce('jw02609007001_03101',clobber=True,noback=True)


    This performs 1D-extraction of the spectra in one exposure.

    Parameters
    ----------
    expname : str
       Exposure name, e.g. 'jw02609009001_04103_00001'.
    backexpname : str, optional
       Exposure name for the "background", i.e. the dithered position.
          This is optional since background subtraction is performed
          during extraction to 1D.
    logger : logger, optional
       Logging object.
    outdir : str, optional
       Output directory.  Default is "./".
    clobber : bool, optional
       Overwrite any existing data.  Default is False.
    redtag : str, optional
       Reduction output file "tag" to use.  This is added at the end of the
         output FITS filenames, e.g. _red.fits.  Default is "red".
    fluxcorr : str, optional
       Name of the flux correction file.  By default, no flux correction
         is applied.
    applyslitcorr : bool, optional
       Apply the SPyderWebb slit correction to the wavelengths.  Default is True.

    Returns
    -------
    speclist : list
       List of final Spec1D objects.

    Examples
    --------

    speclist = extract('jw02609009001_04103_00001',outdir='G140H-F100LP-M31-FINAL-LONG',
                       redtag='red',clobber=True)


Get slit quadrant/row/column information for in put ra/dec coordinates.


Change the reference coordinates.


Return the state of the requested shutters shutters


Get gwa2slit transformation for a single slit.


        The transform from ``slit_frame`` to ``msa_frame``.

        Parameters
        ----------
        open_slits : list
           A list of slit IDs for all open shutters/slitlets.
        msafile : str
          The name of the msa reference file.

        Returns
        -------
        model : `~stdatamodels.jwst.transforms.Slit2Msa` model.
           Transform from ``slit_frame`` to ``msa_frame``.


Get MSA positions for all of the slits/shutters


Convert xmsa/ymsa to slit quadrant/row/column


Initialize a NIRSpec MSA data model


    Input coordinates and figure out where they will fall on the MSA shutter array
    and where in the respective shutters


    Input coordinates and figure out where they fall on the detector and their
    full traces.


Simulate a star in the shutter


 Generates a plot of Longterm averaged monthly observed hydrometeorological variables Precipitation,
     Streamflow and Air temperature.

     Parammeters
     -------------
     MonthlyAverage - dataframe with containg longterm monthly averages.
     Area - catchment area in square ft.

    Returns
    ------------
    A time series plot of Precipitation, Streamflow and Air temperature.


plots day of the year averages along with its bounds for a given flux/store variable.

    Parameters
    ----------
    Df1Av - data frame contaning the day of the year averages of model 1.
    Df1Max - data frame contaning the day of the year maximums of model 1.
    Df1Min - data frame contaning the day of the year minimums of model 1.

    Df2Av - data frame contaning the day of the year averages of model 2.
    Df2Max - data frame contaning the day of the year maximums of model 2.
    Df2Min - data frame contaning the day of the year minimums of model 2.

    VarName - the name of the flux or stor variable in Df1 and Df2 dataframes
    ylabel - plotting name for yaxis
    label1 - name of model 1
    label2 - name of model 2

    Returns
    --------
    A filled plot showing max, min and average across the day of a year.


Computes the information flow metrics and plots source to sink information flow test statistics e.g., TE along with its statistical significance level at each lag.

    .. ref::
   Ruddell et al., 2019 WRR

    Parameters
    ----------
    optsHJ : a dictionary that defines the plotting options such as file names, number of bins. Please refer to the main Notebook for the complete list of options.

    popts : an output dictionary containing the information theoretic metrics.
        model simulated time series.

    Log_factor : float, optional
        offset for log transformed computation of the metrics. default is 0.1.

    Returns
    -------
    1. a pickle file saved in the results folder containing information theoretic metrics including:
    1.1 H - entopy of each varible, and joint entropy of the combination of each variables
    1.2 MI - mutual information between each of the two variables
    1.3 TE - transfer entropy from to each variable
    1.4 their statistical significance
    2. a plot of source to sink information flow values.
    2.1 bar plot of each source to any sink
    2.2 line plot of lag vs the test statistics for the indicated source and sink variables.
    3. the options defined by the input optsHJ.


Returns any metric among the calculated information theoretic metrics. Name of the test statistics is defined by the parameter testStat.

    .. ref::

    Parameters
    ----------
    x  : a dictionary containing the information theoretic metrics.
    toVar : the name of the sink variable.
    testStat : the name of the test statistics to be extracted
    SigThr : the statistical significance level

    Returns
    ---------
    the information theoretic metric defined by testStat.


Returns a dictionary of the information theoretic metrics.

    .. ref::

    Parameters
    ----------
    modelVersion  : user defined model name e.g., calibrated or uncalibrated.
    R : a pickle file with the information theoretic metrics.

    Returns
    ---------
    Store : a dictionary containing the information theoretic metrics.


Returns the plot of the tradeoff between functional (transfer entropy) and predictive (mutual entropy) performances.

    .. ref:: Ruddell et al., 2019 WRR

    Parameters
    ----------
    lag  : lag time for computing transfer entropy and mutual enformation.
    RCalib : the information theoretic metrics repository
    modelVersion : model version e.g. calibrated, uncalibrated
    WatershedName : watershed name
    SourceVar : the name of the source variable
    SinkVariable : the name of the sink variable

    Returns
    ---------
    plots tranfer entropy vs mutual information.


Returns a dataframe of the plot of the tradeoff between functional (transfer entropy) and predictive (mutual entropy) performances.

    .. ref:: Ruddell et al., 2019 WRR

    Parameters
    ----------
    lag  : lag time for computing transfer entropy and mutual enformation.
    RCalib : the information theoretic metrics repository
    modelVersion : model version e.g. calibrated, uncalibrated
    WatershedName : watershed name
    SourceVar : the name of the source variable
    SinkVariable : the name of the sink variable

    Returns
    ---------
    plots tranfer entropy vs mutual information.


Returns Kling-Gupta efficiency measure.

    .. ref::

    Parameters
    ----------
    observed_Q  : observed timeseries.
    model_Q : model simulated timeseries.

    Returns
    ---------
    kge : Kling-Gupta efficiency measure .


Returns an interactive plot of untransformed and logarithm transformed predictive performance measures including:
     1. Nash-Sutcliffe coefficent (NSE),
     2. Kling-gupta efficiency (KGE)
     3. Percent Bias (PBIAS)
     4. Pearson correleation coefficient (r)
     5. Hydrograph plot ( a time series plot of streamflow and precipitation.

    .. ref::
    Klign and Gupta 2009, title' Hydrological Sciences Journal.

    Parameters
    ----------
    ModelVersion : a sting indicating the name of the model version. Options are calibrated an Uncalibrated.
    PerformanceMetrics : flag indicating which predictive performance metrics to print out.
    MetricTransformation : flag indicating a logarithmic transform or untransformed. Options are  'Untransformed', 'Logarithmic'
    nameFCalib : name of the calibrated model file.
    nameFunCalib : name of the uncalibrated model file.
    obsQCol : column number of observed streamflow.
    modQCol : column number of model simulated streamflow.

    Returns
    -------
    An interactive plot of untransformed and transformed predictive performance metrics along with a hydrograph.


Returns untransformed and logarithm transformed predictive performance measures including:
     1. Nash-Sutcliffe coefficent (NSE),
     2. Kling-gupta efficiency (KGE)
     3. Percent Bias (PBIAS)
     4. Pearson correleation coefficient (r)

    .. ref::
    Klign and Gupta 2009, title' Hydrological Sciences Journal.

    Parameters
    ----------
    observed_Q : numpy array
        observed time series
    model_Q : numpy array
        model simulated time series
    Log_factor : float, optional
        offset for log transformed computation of the metrics. default is 0.1.

    Returns
    -------
    Pandas data frame containig both logarithm transformed and untransformed metrics.


Returns a plot of Flow Duration Curve (FDC) that relates streamflow and its exceedance probability.

    .. ref::

    Parameters
    ----------
    Q : numpy array
        Streamflow time series
    SlopeInterval : percentage exceedance levels to compute FDC slopes e.g., [25, 45]
    title : label associated with the streamflow data.

    colrShape : string indicating plot markers
    unit : unit associated with the streamflow data e.g., cfs

    Returns
    -------
    A plot of flow duration curve.
    Slope of the flow duration for a given exceedance interval.


Returns a plot of Recession curve that relates mean streamflow and its time derivative in the absence of precipitation.

    .. ref::

    Parameters
    ----------
    ppt : numpy array containing precipitation time series.

    Q : a numpy array containg streamflow data with corresponding to the precipitation data.

    dateTime : a date time timestamp for both precipitation streamflow.
    title : title for the plotted recession curve.
    labelP : label of the streamflow timeseries.
    labeltxt: plotting marker color and shape.
    season: which season recession curve to plot. The options are:
    1. Summer - covering the months of April to September.
    2. Winter - covering the months of October to March.
    3. All - covers the entire year
    alpha : transparecy for the plotted marker.

    Returns
    -------
    A plot of recession curve.
    z : the slope and intercept of the recession curve in the log-space


Returns annual runoff coefficient.

    .. ref::

    Parameters
    ----------
    table : numpy array containg precipitation, observed streamflow and model simulated streamflow.

    StrtHydroYear : Starting month of the hydrological year. Default is October.
    EndHydroYear : Ending month of the hydrological year. Default is September.
    PrecipName : name of the precipitation data.
    RunoffName : name of the streamflow data.

    Returns
    -------
    Annual Runoff Coefficient for both observed and model data.


Returns bin edges based on equal area binnin.

    .. ref::

    Parameters
    ----------
    x : numpy array
    nbin : number of bins.

    Returns
    ---------
    a numpy array of the bin edges .


Returns bin edges based on equal depth binning.

    .. ref::

    Parameters
    ----------
    x : numpy array
    nbin : number of bins.

    Returns
    ---------
    a numpy array of the bin edges .


Returns bin edges based on equal width binning.

    .. ref::

    Parameters
    ----------
    x : numpy array
    nbin : number of bins.

    Returns
    ---------
    bns : a numpy array of the bin edges .


Returns bin id of a given time series.

    .. ref::

    Parameters
    ----------
    obs : observed timeseries data
    model : simulated timeseries data
    binSize : number of bins for Time linked FDC
    Flag : Flag indicating binning methods
        Flag = 1 : Equal Width
        Flag = 2 : Equal Area
        Flag = 3 : Equal depth (i.e. Frequency)

    Returns
    ---------
    clsObs : bin id of the observed timeseries
    clsMod : bin id of the model timeseries based on the observed bin classes/id
    bns : bin edges


Returns a square matrix of a time series of bin ids.

    .. ref::

    Parameters
    ----------
    df_confusion : a time series of bin ids
    binSize : number of bins.

    Returns
    ---------
    SquaMat: a square matrix with counts of model bin id that in the same bin class as observed data.


Returns a heatmap plot of the square matrix that relates the counts of simulated and observed binnin based on the function squareConfusionMatix().

    .. ref::

    Parameters
    ----------
    df_confusion : a square matrix with counts of model bin id that in the same bin class as observed data
    bns : bin edges.
    ticks : markers for the heatmap color bar

    Returns
    ---------
    a heatmap plot of time linked flow duration curve .


Returns a histogram plot of the square matrix that relates the counts of simulated and observed binnin based on the function squareConfusionMatix().

    .. ref::

    Parameters
    ----------
    df_confusion : a square matrix with counts of model bin id that in the same bin class as observed data
    bns : bin edges.
    sz : figure size
    title : figure title

    Returns
    ---------
    a histogram plot of the time linked flow duration curve.


Returns a plot of the time linked flow duration curve.
    and the fraction of modeled data in the diagonal

    .. ref::

    Parameters
    ----------
    obs : numpy array containg observed streamflow.
    mod : numpy array containg model simulated streamflow
    binSize : number of bins to construct a histogram.
    Flag : Which binning method to use the ptions are:
    a. Flag = 1 :  Equal width based binning
    b. Flag = 2 : Equal area based binning
    c. Flag = 3 : Equal depth/frequency based binning
    FigSize1 : figure dimension for the heatmap plot
    FigSize2 : figure dimension for the histogram plot.
    NameObserved : Label of the observed streamflow
    NameModel : label for the model simulated streamflow
    ticks : color bar ticks

    Returns
    -------
    Returns a plot of the time linked flow duration curve.
    Fraction of data in the diagonal.


Generates square matrix for chord plots.

    parameters
    -----------
    R - A dictionary/Pickle Contating the information-theory (IT) outputs.
    optLag - The lag time of interaction.
    optsHJ - The variable/parameter description of R (the IT outpus)
    modelVersion - the name of the model being processed

    Returns
    ---------
    A dataframe that is ready to be used in chord plots.


 A helper function that compute the bin edges using fractions of the min and max.

    Returns
    -------
    bin edges and the min and max of the bins.


 A helper function that finds the bin edges for a given bin count and max and min timeseries values.

    Returns
    --------
    the bin edges plus min and max of bin edges.


A helper function that classifies a timeseries into different bin classes (bin ids) following the binEdges and number of bins.


 A helper function that computes Marginal and Joint Shannon Entropies in terms of bits (log 2), given probability matrices.

    # Takes the 3D counts and convert it to marginal and joint probabilities to generate entropy, MI and T.

    Returns
    -------
    a list of marginal and joint entropies


 A helper function that intializes the information theoretic metrics to be computed.
    Returns
    -------
    a list of the initialized variables.


 A helper function that intializes the information theoretic metrics to be computed.
    Returns
    -------
    a dictionary of the initialized variables.


 A helper function that creates a shuffled version of the time series to compute statistical significance of the information theoretic metrics.

    parameters
    -----------
    opts : the input specification for the information theoretic metrics.
    Data : the time series data to be shuffled.
    nsur : the number of shuffles to be generated.

    Returns
    --------
    the surrugate time series i.e., the sguffled time series.


 A preprocessing function that computes the annomaly time series.

    Paramters
    ---------

    signalMat : an n-column matrix where n variables are represented as a
    timeseries- columns are variables, rows are timeseries records

    period : the length of the repeating pattern in the data- if using
    FluxNet data with 30 min resolution, the period is 48 or one day

    sliderWidth : the number of periods to base the anomaly on - for a five
    day moving anomaly, set sliderWidth to 5.

    NoDataCode : a data value that will be ignored.

    Returns
    -------
    The anomaly time series i.e, a time series where the mean is deducted.


 A helper function that intends to perform wavelet transforms as preprocessing.
    Not implemented. Placeholder.


A helper function that declares variables.


A helper function that adds and subtraccts metrics.


 A helper function that normalizes the information theoretic metrics.
    Two types of normalizations are reported:
    1. relative normalization i.e., normalization by the sink variables entropy e.g., TE/H for transfer entropy
    2. absolute normalization - normalizes the test statistics by log2 (number of bins).


A helper function that computes an adjacency matrix.


The main information theoretic function that returns a dictionary of the information theoretic metrics.

    .. ref::

    Parameters
    ----------
    opts  : a dicctionary containig the input data, number of bins, statistical thresholds.
            For a full list refer the main notebook with the example

    Returns
    ---------
    R : a dictionary containing the information theoretic metrics that includes:
    1. Transfer entropy
    2. Mutual information
    3. 1D entropy of source and sink
    3. 2D entropies of each variable

    opts : the input specifications defined in the input argument.


 Plots the information theoretic statistics (TE) from source to sink variable.
    The source and sink are defined in the popts while R contains the inofrmation theoretic statistics.

    Parameters
    ----------
    R : a dictionary containing the information theoretic metrics
    popts : a dictionary defining the elements in R

    Returns
    ----------
    A line plot of source to sink information theoretic metric along with its statistical significance.


 Plots the information theoretic statistics (Transfer Entropy - TE) from source to sink variable.
    The source and sink are defined in the popts while R contains the inofrmation theoretic statistics.

    Parameters
    ----------
    R : a dictionary containing the information theoretic metrics
    popts : a dictionary defining the elements in R

    Returns
    ----------
    A bar plot of source to sink information theoretic metric (TE) along with its statistical significance.


Chunk a dataset such that chunks have a certain data size


Every Variable Need to be np.ndarry. np.matrix will cause fatal error


A decorator to limit the execution time of a function


Matplotlib default parameters


Dirty hack to overcome problem of simultaneous cache folder creation for astropy


Averaging stacked objects

        Due to sky cells overlapping we can have multiple rows per a single
        object


Add photometry and time properties to observations, it mutates input


Adds 'folded_time' and 'phase' to observations, it mutates input


Add top-level key to observations as "oid", it mutates input


Function run by each process. Will process blocks placed in the block_queue until the 'STOP' command is reached.


    Run a random forest classification.
    Input:
        input_image: preprocessed image data (preprocess.py)
        watershed_image: Image objects created with the segmentation
            algorithm. (segment.py)
        training_dataset: Tuple of training data in the form:
            (label_vector, attribute_matrix)
        meta_data: [im_type, im_date]
    Returns:
        Raster of classified data.


Wrapper function that handles all of the processing to create watersheds


    Runs a watershed transform on the main dataset
        1. Create a gradient image using the sobel algorithm
        2. Adjust the gradient image based on given threshold and amplification.
        3. Find the local minimum gradient values and place a marker
        4. Construct watersheds on top of the gradient image starting at the
            markers.


Rescale and image data from range [bottom,top] to uint8 ([0,255])


    Finds the appropriate block size for an input image of a given dimensions.
    Method returns the first factor of the input dimension that is greater than
        the desired size.


    Calculates a quality score of an input image by determining the number of
    high frequency peaks in the fourier transformed image relative to the
    image size.
    QA Score < 0.025          poor
    0.25 < QA Score < 0.035   medium
    QA Score > 0.035          fine


    Parse image metadata information to find date.
    If image date cannot be found, return mean date of melt season (June1).
    This is likely to have to least impact on decision tree outcomes, as there
        will be less bias towards no melt vs lots of melt, but this should be tested.
        If 0 were to be used, then the decision tree would see that as very early
        season, since date is a numeric feature, and not a categorical one.


    Finds the three strongest peaks in a given band.
    Criteria for each peak:
        Distance to the nearest neighboring peak is greater than one third the approx. dynamic range of the input image
        Has a minimum number of pixels in that peak, loosely based on image size
        Is greater than the directly adjacent bins, and the bins +/- 5 away


    Finds the upper and lower threshold for histogram stretching.
    Using the indices of the highest and lowest peak (by intensity, not # of pixels), this searches for an upper
    threshold that is both greater than the highest peak and has fewer than 15% the number of pixels, and a lower
    threshold that is both less than the lowest peak and has fewer than 50% the number of pixels.
    10% and 50% picked empirically to give good results.


Write a rgb color image (as png) of the raw image data to disk.


    'Downsample' an image by the given factor. Every pixel in the resulting image
        is the result of an average of the NxN kernel centered at that pixel,
        where N is factor.


    INPUT:
        input_directory of .h5 training data
        file_name of .h5 training data
        list_name of label vector contained within file_name
    RETURNS:
        tds = [label_vector, training_feature_matrix]


    INPUT:
        path: location where the output will write
        image_name: name of the image that was classified
        pixel_clounts: number of pixels in each classification category

    Saves a csv with the input information. Appends to existing csv if one already exists

    NOTES:
        Only works with 5 classification categories:
            [white ice, gray ice, melt ponds, open water, shadow]


    INPUT:
        db_name: filename of the database
        path: location where the database is stored
        pixel_clounts: number of pixels in each classification category
            [snow, gray, melt, water, shadow]

    Writes the classification pixel counts to the database at the image_id entry
    NOTES:
        For now, this overwrites existing data.
    FUTURE:
        Develop method that checks for existing data and appends the current
            data to that, record which parts contributed to the total.


    INPUT:
        image_files: list of the image splits for recombination
    RETURN:
        full_classification: full image stitched back together

    NOTES:
        Currently only implemented to recombine classified images, but the
        method could work with any image data.
        There are two levels of recombination. Recompiling the subimages (see
        method below) and recompiling the splits (this method)


    Compiles the subimages (i.e. blocks) of a split into one raster
    INPUT:
        subimage_list: the list of subimages, in left to right top to bottom order
        num_x_subimages: number of subimages in the x dimension
        num_y_subimages: number of subimages in the y dimension
        bands: number of spectral bands of the input image
    RETURNS:
        compiled_image: single [x,y,b] image


    INPUTS:
        image: The image you want to save
        save_name: full name and filepath where you want the image to go
        custom_colormap: matplotlib colormap if you want to use your own
            defaults to nwright's 5 class colormap

    Saves a .png of the input image with desired colormap


    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.


    Displays a histogram of the given band's data.
    Ignores zero values.


    Generates sections of yml code from template.

    Parameters
    ----------
    ecosystem : str
        Package manager to use

    directory : str
        Location of package manifests

    exclude_list: str, optional
        List of packages that should be excluded from dependabot version update tracking.
    Returns
    -------
    yml_content : list
        List of code lines to add to output list.


    Generates the dependabot.yml file.

    Parameters
    ----------
    exclude_filename: str, optional.
        Text file containing names of specific requirements.txt files and lists of packages that should be
        skipped from dependabot version updating, one requirements.txt file and package list per line.
        File syntax: <path of requirements.txt file from repository root>: <package1>, ..., <packageN>,
        Example: skip depdendabot updates for packages "package1" and "package2" in file
        notebooks/foo/requirements.txt and package "package3" in file notebooks/bar/requirements.txt:
        notebooks/foo/requirements.txt: package1, package2
        notebooks/bar/requirements.txt: package3
        NOTE: unless explicitly specified, it is assumed that there is no file, and that all packages in all
        requirements.txt files should be included in dependabot version tracking.
    req_file_search_string : str, optional.
        Search pattern used to locate notebook-level requirements.txt files. The path in the search string is
        assumed to start from the repository root. If not explicitly specified by the user, the default value
        is "notebooks/**/requirements.txt", which will enable a fully recursive search.

    Returns
    -------
    Nothing!


reads through json file produced by a11ywatch API and displays the results.

    Parameters
    ----------
    json_filename : str
        name of the json file to process
    total_combined_limit : int
        The maximum total allowed number of HTML accessibility errors and warnings. To skip this testing
        requirement, enter the value "-1". If not explicitly specified, the default value is "0".
    total_error_limit : int
        The maximum total allowed number of HTML accessibility errors. To skip this testing requirement,
        enter the value "-1". If not explicitly specified, the default value is "0".
    total_error_limit : int
        The maximum total allowed number of HTML accessibility warnings. To skip this testing requirement,
        enter the value "-1". If not explicitly specified, the default value is "0".

    Returns
    -------
    rv : int
        if a11ywatch didn't find any issues, rv will be integer value '0'. However, if a11ywatch did find
        issues, rv will be integer value '99'.


Removes temp files created to perform pep8 style check

    Parameters
    ----------
    warn_file : str
        name of the temp file containing the resulting pep8 warnings

    Returns
    -------
    Nothing!


Use flake8 to perform a PEP8 style check on python scripts

    Parameters
    ----------
    py_file : str
        Name of the python script to check

    Returns
    -------
    Returns integer value '0' if no errors are found and integer value '99' if one or more PEP8 style
    issue(s) are found.


Use flake8 to perform a PEP8 style check on the python code embedded in a user-specified jupyter
    notebook

    Parameters
    ----------
    nb_file : str
        Name of the Jupyter notebook to check

    Returns
    -------
    Returns integer value '0' if no errors are found and integer value '99' if one or more PEP8 style
    issue(s) are found.


Display command-line arguments parsed by a function (
    e.g. `initialise`) as a dictionary.

    Parameters
    ----------
    logger : :class:`logging.Logger` *or None, optional*
        If not `None` (default), print to logger.
    comm : :class:`mpi4py.Comm` *or None*, optional
        MPI communicator.


Ensure a given directoy path exists.

    Parameters
    ----------
    dir_path : str or :class:`pathlib.Path`
        Directory path.

    Returns
    -------
    bool
        `True` if `dir_path` exists or has been created.


Inspect and modify overwrite permission.

    The function may ask for permission from the user to overwrite the
    file output path at runtime.

    Parameters
    ----------
    output_path : str or :class:`pathlib.Path`
        Output file path.

    Returns
    -------
    bool
        Write permission.


Validate full-sky spherical modelling against baseline power
    spectrum model.

    Parameters
    ----------
    b_1, f_nl, nbar, contrast : float, optional
        Cosmological and model parameters to pass to the model.  Defaults
        are 2.3415, 100., 2.5e-4 and 10. respectively.
    use_shortcut : bool, optional
        If `True` (default), short cuts (Kronecker delta reduction in the
        absence of couplings and diagonalisation of correlator matrix)
        are used.


Validate generic spherical correlator predictions against estimates
    from large sample sets.

    Parameters
    ----------
    b_1, f_nl, nbar, contrast : float, optional
        Cosmological and model parameters to pass to the model.  Defaults
        are 1., 0., 2.5e-4 and 10. respectively.


Extract mode power from spherical maps.

    Returns
    -------
    list, list, :class:`harmonia.algorithms.disscretisation.DiscreteSpectrum`
        Lists of mode power and spherical map coefficients from the serial
        maps and the discrete spectrum.


Predict the power spectrum from spherical modelling.


Compare map mode power, spherical model mode power and the
    Cartesian power spectrum.

    Returns
    -------
    fig : :class:`matplotlib.figure.Figure`
        Comparison plot.


Collate Cartesian map data.

    Returns
    -------
    float :class:`numpy.ndarray`
        Wavenumber of Cartesian map multipoles.
    dict{int: float :class:`numpy.ndarray`}
        Power multipoles of different Legendre orders at `wavenumbers`.


Compare the map data with Cartesian model predictions.

    Parameters
    ----------
    wavenumbers : float :class:`numpy.ndarray`
        Wavenumbers.
    multipole_data : dict{int: float :class:`numpy.ndarray`}
        Measured multipoles from map data.

    Returns
    -------
    dict{int: float :class:`numpy.ndarray`}
        Ratio of the measured multipoles to model predictions.


Initialise the program parameters passed from ``stdin``.

    Returns
    -------
    parsed_args : :class:`argparse.Namespace`
        Parsed parameter namespace.


Measure catalogue power spectrum at binned wavenumbers.

    Parameters
    ----------
    kmin : float or None, optional
        Minimum wavenumber (default is `None`).
    kmax : float or None, optional
        Maximum wavenumber (default is `None`).

    Returns
    -------
    dict
        Power spectrum measured at binned wavenumbers.


Evaluate the Gaussianised log-likelihood at a given bias.

    Parameters
    ----------
    b_1 : float
        Model scale-independent linear bias.

    Returns
    -------
    float
        Gaussnianised log-likelihood value.


Plot likelihood evaluation results on a parameter grid.

    Parameters
    ----------
    *args : (sequence of) :class:`numpy.ndarray`
        Log-posterior values at sample points.
    sample_points_x : (sequence of) :class:`numpy.ndarray`
        First parameter values (default is `None` but must be overriden).
        If a sequence is passed, its length must be the same as that of
        `args`.
    sample_points_y : (sequence of) :class:`numpy.ndarray` *or None, optional*
        Second parameter values (default is `None` but must be overriden
        if likelihood values are evaluated on a 2-d grid).  If a sequence
        is passed, its length must be the same as that of `args`.
    range_x : tuple, optional
        Renormalisation range for the first parameter (default is ()).
    range_y : tuple, optional
        Renormalisation range for the second parameter (default is ()).
    precision_x : int or None, optional
        Precision for the first parameter estimate (default is `None`).
    precision_y : int or None, optional
        Precision for the second parameter estimate (default is `None`).
    label_x : str, optional
        *x*-axis parameter name as a TeX string (default is '').
    label_y : str, optional
        *y*-axis parameter name as a TeX string (default is '').
    truth_x : float or None, optional
        Truth value for the first parameter (default is `None`).
    truth_y : float or None, optional
        Truth value for the second parameter (default is `None`).
    estimate : {'maximum', 'median', None}, optional
        Parameter estimate type (default is 'median').
    scatter_plot : bool, optional
        Plot individual log-likelihood evaluations on parameter grids
        (default is `False`).
    fig : :class:`matplotlib.figure.Figure` *or None, optional*
        Any existing figures to plot on (default is `None`).
    aggregate : bool, optional
        Whether to aggregate likelihood evaluations by summing logarithmic
        likelihood values (default is `False`).
    label : (sequence of) str or None, optional
        Label for the likelihood result (default is `None`).  If a
        sequence is passed, its length must be the same as that of `args`.
    colour : (sequence of) str or None, optional
        Colour for sampled likelihood (default is `None`).  If a sequence
        is passed, its length must be the same as that of `args`.
    cmap : (sequence of) :class:`matplotlib.ScalarMappable` or None, optional
        Colour map for sampled likelihood contours (default is `None`).
        If a sequence is passed, its length must be the same as that
        of `args`.
    alpha : (sequence of) float or None, optional
        Transparency value for sampled likelihood contours (default is
        `None`).  If a sequence is passed, its length must be the same as
        that of `args`.

    Returns
    -------
    fig : :class:`matplotlib.figure.Figure`
        Any existing figures to plot on.
    x_estimate, y_estimate : list of tuple
        Parameter estimate, lower uncertainty and upper uncertainty of
        for each likelihood value sets.


Aggregate likelihood results.

    Parameters
    ----------
    constituent : {'all', 'spherical', 'cartesian'}, optional
        Likelihood constituent (default is 'all').
    load : bool, optional
        If `True` (default is `False`), load aggregated results.
    export : bool, optional
        If `True` (default is `False`), save aggregated results.
    x_name, y_name : str or None, optional
        Name of the parameter (default is `None`).
    x_grid, y_grid : :class:`numpy.ndarray` *or None, optional*
        Parameter 1-d grid to interpolate the likelihood results.

    Returns
    -------
    likelihood_grids, x_coords, y_coords : float :class:`numpy.ndarray`
        Likelihood and coordinate grids.


Plot 1-d constraints.

    Parameters
    ----------
    posteriors : float, array_like
        (Sequence of) logarithmic posterior evaluations.
    x : float, array_like
        Parameter coordinates.
    fig : :class:`matplotlib.figure.Figure` *or None, optional*
        Existing figure object to plot on (default is `None`).
    label : str, optional
        Constraint label (default is '').
    colour : str or None, optional
        Principal colour (default is `None`).
    x_label : str or None
        Parameter label (default is `None`).
    x_range : sequence or None
        Parameter range as a sequence of length 2 (default is `None`).
    aggregation : {'average', 'combine'}, optional
        How to aggregate posterior evaluations, either by averaging
        or combining (default is 'average').
    estimation : {'median', 'maximum', None}, optional
        Parameter estimate type, if any (default is `None`).
    precision : int or None, optional
        Parameter precision as a number of decimal places (default is
        `None`).
    scatter_plot : bool, optional
        If `True`, Plot individual posteriors evaluations (default is
        `False`).

    Returns
    -------
    fig : :class:`matplotlib.figure.Figure`
        Plotted figure object.
    estimate : tuple of float
        Parameter estimate with low and upper uncertainties.


Plot 2-d constraints.

    Parameters
    ----------
    posteriors : float, array_like
        (Sequence of) logarithmic posterior evaluations.
    x, y : float, array_like
        Parameter coordinates.
    fig : :class:`matplotlib.figure.Figure` *or None*, optional
        Existing figure object to plot on (default is `None`).
    cmap : str or None, optional
        Principal colour map (default is `None`).
    alpha : str or None, optional
        Principal alpha transparency (default is `None`).
    x_label, y_label : str or None
        Parameter label (default is `None`).
    x_range, y_range : sequence or None
        Parameter range as a sequence of length 2 (default is `None`).
    aggregation : {'average', 'combine'}, optional
        How to aggregate posterior evaluations, either by averaging
        or combining (default is 'average').
    estimation : {'median', 'maximum', None}, optional
        Parameter estimate type, if any (default is `None`).
    x_precision, y_precision : int or None, optional
        Parameter precision as a number of decimal places (default is
        `None`).
    scatter_plot : bool, optional
        If `True`, plot individual posteriors evaluations (default is
        `False`).
    line_style : str, optional
        Line style for the contours (default is '-').

    Returns
    -------
    fig : :class:`matplotlib.figure.Figure`
        Plotted figure object.
    x_estimate, y_estimate : tuple of float
        Parameter estimates with low and upper uncertainties.
    patch : :class:`matplotlib.patches.Rectangle`
        A colour patch to be used in the legend.


Load spherical map data used for likelihood evaluation.

    Parameters
    ----------
    map_serial_num : int
        The serial number of the map to use.

    Returns
    -------
    :class:`harmonia.algorithms.arrays.SphericalArray`
        Spherical map data.


Evaluate the map likelihood on a 9-grid.

    Parameters
    ----------
    bias, png : list of float
        Bias and PNG parameters.
    map_data : :class:`harmonia.algorithms.arrays.SphericalArray`
        Spherical map data.
    map_model : :class:`harmonia.reader.models.SphericalCorrelator`
        Spherical correlator model.
    discard : int or None, optional
        If not `None`, the least informative `discard` number of modes
        are discarded by data compression.

    Returns
    -------
    likelihood : float :class:`numpy.ndarray`
        Log-likelihood evaluated on a grid.


Evaluate the log-likelihood function.

    Returns
    -------
    :class:`collections.defaultdict`
        Log-likelihood evaluated at sample points.


Write output file tags.

    Returns
    -------
    mask_info, selection_info, order_info : str
        Mask, selection, multipole order information strings.


Synthesise the window and mask multipoles from a high-density
    random catalogue.

    Returns
    -------
    |CartesianArray| and :class:`numpy.ndarray`
        Window and mask multipoles.

    .. |CartesianArray| replace::

        :class:`harmonia.algorithms.arrays.CartesianArray`


Export and visualise window/mask multipoles from the
    synthetic catalogue.


Write output file tags.

    Returns
    -------
    mask_info, selection_info : str
        Mask and selection information strings.


Synthesise spherical couplings from baseline cosmology and
    survey specifications.

    Returns
    -------
    :class:`harmonia.reader.couplings.Couplings`
        Spherical couplings.


Synthesise random maps.


Write output file tags.

    Returns
    -------
    mask_info, selection_info, order_info, pivot_info : str
        Mask, selection, multipole order and pivot information strings.


Load and process random map data for covariance estimation.

    Returns
    -------
    list, list
        Spherical and Cartesian map data.


Export and visualise statistical properties of random maps.


Load and hybridise map data.

    Returns
    -------
    hybrid_map_data_array : list of :class:`numpy.ndarray`
        Hybrid map data array.


Export and visualise statistical properties of hybrid map data.

    Parameters
    ----------
    hybrid_map_data : list of :class:`numpy.ndarray`
        List of hybrid map data vectors.
    thredshold : float, optional
        Absolute value threshold for plotting correlation matrix elements.


Transform input catalogues to maps.

    Returns
    -------
    |CartesianMap| or |SphericalMap|
        Catalogue map.

    .. |CartesianMap| replace::

        :class:`harmonia.mapper.map_transform.CartesianMap`

    .. |SphericalMap| replace::

        :class:`harmonia.mapper.map_transform.SphericalMap`


Visualise processed catalogues.


Define survey selection functionfrom a random catalogue.

    Parameters
    ----------
    random_catalogue_file : *str or* :class:`pathlib.Path`
        Random catalogue source file.

    Returns
    -------
    selection_function : float :class:`numpy.ndarray`
        Selection function samples at discrete radii.
    sky_fraction : float
        Sky fractional coverage.


Export and visualise the survey selection function.

    Parameters
    ----------
    sampled_selection : tuple of float :class:`numpy.ndarray`
        Selection samples and corresponding coordinates.
    sky_fraction : float
        Sky fraction covered.


Process a random catalogue file into a `healpy` sky map.

    Parameters
    ----------
    random_catalogue_file : *str or* :class:`pathlib.Path`
        Random catalogue source file.

    Returns
    -------
    sky_map : float :class:`numpy.ndarray`
        Pixelated sky map for a veto mask.


Export and visualise a pixelated sky mask map.

    Parameters
    ----------
    sky_map : :class:`numpy.ndarray`


Report the current position in the tasks.

        Parameters
        ----------
        current_position : int
            Index of the current position in the tasks (starting from 0).


Modify the default logging record by adding elapsed time in
        hours, minutes and seconds.

        Parameters
        ----------
        record : :class:`Logging.LogRecord`
            Default logging record object.

        Returns
        -------
        str
            Modified record message with elapsed time.


Emit captured warnings.

    Parameters
    ----------
    captured_warnings : *list of* :class:`warnings.WarningMessage`
        List of recorded warnings as returned by
        ``warnings.catch_warnings(record=True)``.


Allocate tasks to processes for parallel computation.

    If `total_proc` processes share `total_task` tasks, then this decides
    the numbers of tasks, `tasks`, different processes receive: the
    rank-``i`` process receives ``tasks[i]`` many tasks.

    Parameters
    ----------
    total_task : int
        Total number of tasks.
    total_proc : int
        Total number of processes.

    Returns
    -------
    tasks : list of int
        Number of tasks for each process.


Allocate segments of tasks to each process by the number of tasks it
    receives and its rank.

    For instance, if the rank-``i`` process receives ``tasks[i]`` tasks
    (e.g. assigned by :func:`_allocate_tasks`), then this function assigns
    a slice of the indexed tasks it should receive, with the indices in
    ascending order in correspondence with ranks of the processes.

    Parameters
    ----------
    tasks : list of int or None, optional
        Number of tasks each process receives.  Cannot be `None` if either
        `total_task` or `total_proc` is `None`.  If not `None`,
        `total_task` and `total_proc` are both ignored.
    total_task : int or None, optional
        Total number of tasks.  Ignored if `tasks` is not `None`, otherwise
        cannot be `None`.
    total_proc : int or None, optional
        Total number of processes.  Ignored if `tasks` is not `None`,
        otherwise cannot be `None`.

    Returns
    -------
    segments : list of slice
        Index slice of the segment of tasks that each process should
        receive.


Multiprocess mapping of data with optional progress bar.

    For each map to be applied, the input data array is scattered over the
    first axis for computation on difference process, and the computed
    results are gathered in the exact structure of the input data array on
    the root process.

    Parameters
    ----------
    data_array : array_like
        Data array.
    mapping : callable
        Mapping to be applied.
    comm : :class:`mpi4py.MPI.Comm` *or None, optional*
        MPI communicator.  If `None`, no multiprocessing is performed.
    root : int, optional
        Rank of the process taken as the root process (default is 0).
    process_name : str or None
        If `None` (default), no progress bar is displayed; else this is
        the process name to be displayed.
    update_rate : int or None, optional
        If not `None` (default), this is the progress bar update rate
        (in inverse seconds).  Has no effect if `process_name` is
        not provided.

    Returns
    -------
    output_array : array_like or None
        Output data processed from `mapping`.  Returns `None` for process
        ranks other than `root`.


Return a constant function with arbitrary arguments.

    Parameters
    ----------
    const : float
        Constant value.

    Returns
    -------
    callable
        Constant function.


Normalise vector(s).

    Parameters
    ----------
    vector_array : float, array_like
        An array of row vectors.

    Returns
    -------
    float :class:`numpy.ndarray`
        Normalise vector array.


Scan an interval from the lower end to detect sign changes.

    Parameters
    ----------
    func : callable
        Function whose sign-change interval is to be found.
    a, b: float
        Initial interval end points, ``a < b``.
    dx : float
        Increment from the interval lower end, ``dx > 0``.

    Returns
    -------
    x_low, x_high : float or None
        End points for a sign-change interval, ``x_low < x_high``.
        `None` if the result is null.


Bisection method for root finding.

    Parameters
    ----------
    func : callable
        Function whose zero bracket is to be found.
    x_low, x_high: float
        Initial interval end points.
    convergence : float, optional
        Convergence precision for setting maximum iteration number
        (default is 1.e-9).

    Returns
    -------
    float or None
        Single possible root.


Binary seach for all zeros of a function in a real interval.

    Parameters
    ----------
    func : callable
        Function whose zeros are to be found.
    a, b : float
        Interval end points, ``a < b``.
    maxnum : int or None, optional
        Maximum number of zeros needed from below (default is `None`).
    precision : float, optional
        Desired absolute precision of the zeros (default is 1.e-8).

    Returns
    -------
    roots : float :class:`numpy.ndarray` or None
        Possible roots.

    Raises
    ------
    ValueError
        If the initial interval covers only one point (``a == b``).


Convert a covariance matrix to its correlation matrix.

    Parameters
    ----------
    covar : complex, array_like
        Covariance matrix.

    Returns
    -------
    corr : :class:`numpy.ndarray`
        Correlation matrix.


Calculate logarithm of the determinant of a matrix.

    Parameters
    ----------
    matrix : float or complex, array_like
        Matrix.

    Returns
    -------
    log_det : float
        Logarithm of the matrix determinant.


Check the positive definiteness of a square matrix by attempting a
    Cholesky decomposition.

    Parameters
    ----------
    matrix : float or complex, array_like
        Matrix.

    Returns
    -------
    bool
        Positive definiteness.


r"""Return the scale-dependence modification kernel :math:`A(k,z)` for
    a given cosmological model.

    Parameters
    ----------
    cosmo : :class:`nbodykit.cosmology.cosmology.Cosmology`
        Cosmological model.
    redshift : float
        Redshift at which quantities are evaluated.

    Returns
    -------
    callable
        Scale-dependence modification kernel as a function of wavenumber
        (in :math:`h`/Mpc).


r"""Return the scale-dependent bias modulated by local primordial
    non-Gaussianity.

    Parameters
    ----------
    b_1 : float
        Scale-independent linear bias at input redshift.
    f_nl : float
        Local primordial on-Gaussianity.
    cosmo : :class:`nbodykit.cosmology.cosmology.Cosmology`
        Cosmological model.
    redshift : float, optional
        Redshift at which quantities are evaluated (default is 0.).
    tracer_p : float, optional
        Tracer-dependent parameter :math:`p` (default is 1.).

    Returns
    -------
    callable
        Scale-dependent bias as a function of wavenumber (in
        :math:`h`/Mpc).


r"""Return the tracer power spectrum modified by primordial
    non-Gaussianity.

    Parameters
    ----------
    b_1 : float
        Scale-independent linear bias at input redshift.
    f_nl : float
        Local primordial non-Gaussianity.
    cosmo : :class:`nbodykit.cosmology.cosmology.Cosmology`
        Cosmological model.
    redshift : float, optional
        Redshift at which quantities are evaluated (default is 0.).
    tracer_p : float, optional
        Tracer-dependent parameter :math:`p` (default is 1.).
    nbar : float or None, optional
        If not `None` (default), add ``1/nbar`` as shot noise to the
        resulting power spectrum.
    contrast : float or None, optional
        If not `None` (default), add additional ``1/(contrast*nbar)``
        as shot noise to the resulting power spectrum.

    Returns
    -------
    callable
        Tracer power spectrum modified by primordial non-Gaussianity as a
        function of wavenumber (in :math:`h`/Mpc).


Invert redshift-to-distance relationship of a cosmological model
    to redshift-from-distance.

    Notes
    -----
    This is useful when the Alcock--Paczynski effect needs to be included
    in modelling.  Only valid for redshift between 1.e-3 and 100.

    Parameters
    ----------
    cosmo : :class:`nbodykit.cosmology.cosmology.Cosmology`
        Cosmological model.
    lg_num_sample : float, optional
        Base-10 logarithm of the number of redshift points to sample
        the comoving distance as a function of redshift (default
        is 5, i.e. 100000 samle points).

    Returns
    -------
    callable
        Redshift-from-distance function.


Compute the differential Alcock--Paczynski distortion between a
    fiducial and a cosmological redshift-to-distance conversion as a
    fuction of redshift.

    Parameters
    ----------
    fiducial_z_to_r : callable
        Fiducial redshift-to-distance conversion.
    variable_z_to_r : callable
        Variable redshift-to-distance conversion.
    max_redshift : float, optional
        Maximum redshift to sample for interpolation (default is 10).
    lg_num_sample : float, optional
        Base-10 logarithm of the number of redshift points to sample
        the differential distortion as a function of redshift (default
        is 5, i.e. 100000 samle points).

    Returns
    -------
    callable
        Differential distortion as a fuction of redshift.


r"""Evaluate the angular coupling kernel.

    Parameters
    ----------
    theta, phi : float, array_like
        Angular coordinates :math:`\theta`, :math:`\phi`.
    mu, nu : tuple(int, int, int)
        Coefficient triplet index.
    mask : callable or None, optional
        Mask as a function of angular coordinates (default is `None`).

    Returns
    -------
    kernel : complex :class:`numpy.ndarray`
        Angular coupling kernel value.


Evaluate the radial coupling kernel.

    Parameters
    ----------
    r : float, array_like
        Radial coordinate.
    mu, nu : tuple(int, int, int)
        Coefficient triplet index.
    k_mu, k_nu : float
        Discrete wave number corresponding to index `mu` or `nu`.
    selection, weight : callable or None, optional
        Selection or weight as a function of the radial coordinate
        (default is `None`).
    bias_evolution, clustering_evolution : callable or None, optional
        Bias and clustering evolution as a function of redshift
        normalised to unity at the current epoch (default is `None`).
    z_from_r : callable or None, optional
        Comoving distance-to-redshift conversion in a variable
        cosmological model (default is `None`).
    chi_of_z : callable or None, optional
        Comoving redshift-to-distance conversion in a fiducial
        cosmological model (default is `None`).

    Returns
    -------
    kernel : float :class:`numpy.ndarray`
        Radial coupling kernel value.

    Raises
    ------
    TypeError
        If `z_from_r` is not callable when any of `bias_evolution`,
        `clustering_evolution` and `chi_of_z` is.


Evaluate the RSD coupling kernel.

    Parameters
    ----------
    r : float, array_like
        Radial coordinate.
    mu, nu : tuple(int, int, int)
        Coefficient triplet index.
    k_mu, k_nu : float
        Discrete wave number corresponding to index `mu` or `nu`.
    selection, weight, weight_derivative : callable or None, optional
        Selection, weight or weight derivative as a function of the
        radial coordinate (default is `None`).
    growth_evolution, clustering_evolution : callable or None, optional
        Growth rate evolution or clustering evolution as a function of
        redshift normalised to unity at the current epoch (default is
        `None`).
    z_from_r : callable or None, optional
        Cosmological comoving distance-to-redshift conversion (default
        is `None`).
    chi_of_z : callable or None, optional
        Fiducial comoving redshift-to-distance conversion (default is
        `None`).
    differential_AP_distortion : callable or None, optional
        Differential AP distortion as a function of redshift (default
        is `None`).

    Returns
    -------
    kernel : float, array_like
        RSD coupling kernel value.

    Raises
    ------
    TypeError
        If `z_from_r` is not callable when any of `growth_evolution`,
        `clustering_evolution` and `chi_of_z` is.
    TypeError
        If `weight` and `weight_derivative` are not both None or callable.
    TypeError
        If `chi_of_z` and `AP_distortion` are not both None or callable.


Evalaute the two-point correlator shot noise kernel.

    Parameters
    ----------
    r : float, array_like
        Radial coordinate.
    mu, nu : tuple(int, int, int)
        Coefficient triplet index.
    k_mu, k_nu : float
        Discrete wave number corresponding to index `mu` or `nu`.
    selection, weight : callable or None, optional
        Selection or weight as a function of the radial coordinate
        (default is `None`).

    Returns
    -------
    kernel : float, array_like
        Two-point correlator shot noise kernel value.


Compute the convolved power spectrum multipoles.

        Parameters
        ----------
        orders : list of int
            Orders of the power spectrum multipoles.  Values only allowed
            from the set {0, 2, 4}.
        b_1 : float or None, optional
            Scale-independent linear bias at input redshift.  If `None`
            (default), no tracer bias is assumed relative to the matter
            power spectrum.
        f_nl : float or None, optional
            Local primordial non-Gaussianity (default is `None`).
        nbar : float or None, optional
            Mean particle number density (in cubic :math:`h`/Mpc).  If
            `None` (default), shot noise is neglected.
        contrast : float or None, optional
            If not `None` (default), this adds additional shot noise
            ``1 / (contrast * nbar)`` from a FKP-style random catalogue.
        tracer_p : float, optional
            Tracer-dependent parameter for bias modulation by `f_nl`
            (default is 1.).
        update_model_kwargs : dict or None, optional
            Parameters `cosmo`, `power_spectrum` and `growth_rate` passed
            as keyword arguments to update the baseline cosmological model.

        Returns
        -------
        convolved_power : :class:`~.algorithms.arrays.CartesianArray`
            Convolved power spectrum multipoles.


Return the standard Kaiser power spectrum multipole as a
        multipole of the matter power spectrum.

        Notes
        -----
        Linear bias `b` and growth rate `f` must be specified at the
        same redshift.

        Parameters
        ----------
        ell : int
            Order of the multipole in {0, 2, 4}.
        b : float, array_like
            Linear bias of the tracer particles.
        f : float or None
            Linear growth rate.

        Returns
        -------
        float, array_like
            Standard Kaiser factor to multiply by the matter power
            spectrum.


Compute two-point correlator for given triplet indices.

        Parameters
        ----------
        mu, nu : tuple(int, int, int)
            Coefficient triplet index.
        b_1 : float
            Scale-independent linear bias at input redshift.
        f_nl : float or None, optional
            Local primordial non-Gaussianity (default is `None`).
        nbar : float or None, optional
            Mean particle number density (in cubic :math:`h`/Mpc).  If
            `None` (default), shot noise is neglected.
        contrast : float or None, optional
            If not `None` (default), this adds additional shot noise
            ``1 / (contrast * nbar)`` from a FKP-style random catalogue.
        tracer_p : float, optional
            Tracer-dependent parameter for bias modulation by `f_nl`
            (default is 1.).
        update_model_kwargs : dict or None, optional
            Parameters `cosmo`, `power_spectrum`, `growth_rate` and
            `cosmo_specs` passed as keyword arguments to update the
            baseline cosmological model.  If `cosmo_specs` is passed
            (including `None` values), radial and RSD couplings will be
            updated.

        Returns
        -------
        complex
            Spherical Fourier 2-point function value for given triplet
            indices.  If `cosmo_specs` is passed, radial and RSD couplings
            will be updated.


Compute two-point correlator matrix for some vetorisation of all
        spectrum modes.

        Parameters
        ----------
        pivot : {'natural', 'spectral'}
            Pivot order for vectorisation.
        b_1 : float
            Scale-independent linear bias at input redshift.
        f_nl : float or None, optional
            Local primordial non-Gaussianity (default is `None`).
        nbar : float or None, optional
            Mean particle number density (in cubic :math:`h`/Mpc).  If
            `None` (default), shot noise is neglected.
        contrast : float or None, optional
            If not `None` (default), this adds additional shot noise
            ``1 / (contrast * nbar)`` from a FKP-style random catalogue.
        tracer_p : float, optional
            Tracer-dependent parameter for bias modulation by `f_nl`
            (default is 1.).
        diagonal : bool, optional
            If `True` (default is `False`), return only the diagonal
            matrix part.
        shot_noise_only : bool, optional
            If `True` (default is `False`), return only the shot noise
            correlator matrix.
        update_model_kwargs : dict or None, optional
            Parameters `cosmo`, `power_spectrum`, `growth_rate` and
            `cosmo_specs` passed as keyword arguments to update the
            baseline cosmological model.  If `cosmo_specs` is passed
            (including `None` values), radial and RSD couplings will be
            updated.
        report_progress : bool, optional
            If `True` (default is `False`), progress status will be
            reported.

        Returns
        -------
        complex :class:`numpy.ndarray`
            Two-point correlator matrix vectorised by the given pivot.

        See Also
        --------
        :class:`~harmonia.algorithms.arrays.SphericalArray`


Compute the radialised spherical mode power.

        Notes
        -----
        This relies on :meth:`~.correlator_matrix` with ``diagonal=True``.
        Results are only meaningful in the radialisation limit when
        all coupling coefficients are trivial (i.e. Kronecker deltas) so
        that spherical modes are mutually independent [3]_.  Mode power is
        averaged over equivalent spherical orders and suitably normalised
        so that it matches the Cartesian power spectrum for a full-sky
        statistically isotripoc map.

        Parameters
        ----------
        b_1 : float
            Scale-independent linear bias at input redshift.
        f_nl : float or None, optional
            Local primordial non-Gaussianity (default is `None`).
        nbar : float or None, optional
            Mean particle number density (in cubic :math:`h`/Mpc).  If
            `None` (default), shot noise is neglected.
        contrast : float or None, optional
            If not `None` (default), this adds additional shot noise
            ``1 / (contrast * nbar)`` from a FKP-style random catalogue.
        tracer_p : float, optional
            Tracer-dependent parameter for bias modulation by `f_nl`
            (default is 1.).
        shot_noise_only : bool, optional
            If `True` (default is `False`), return only the shot noise
            power.

        Returns
        -------
        dict
            Radialised spherical mode powers at wavenumbers with mode
            indices.

        See Also
        --------
        :attr:`~harmonia.mapper.map_transform.SphericalMap.mode_power`

        .. [3] Rassat A. & Refregier A., 2012. A&A 540, A115.
           [arXiv: `1112.3100 <https://arxiv.org/abs/1112.3100>`_]


(Re-)set baseline model.

        Parameters
        ----------
        **kwargs
            Parameters `cosmo`, `power_spectrum`, `growth_rate`,
            `cosmo_specs` and `update_couplings` to be set or reset.


Calculate chi-square from zero-centred data vector and its
    covariance matrix.

    Parameters
    ----------
    data_vector : complex, array_like
        Zero-centred data vector.
    covariance_matrix : complex, array_like
        Covariance matrix.

    Returns
    -------
    chi_sq : float :class:`numpy.ndarray`
        Chi-square value.


Compute the complex normal probability density function or its
    natural logarithm given the zero-centred data vector and its
    covariance matrix.

    Parameters
    ----------
    data_vector : complex, array_like
        Zero-centred data vector.
    covariance_matrix : complex, array_like
        Covariance matrix.
    ret_log : bool, optional
        If `True` (default), return logarithmic probability density.
    downscale : float or None, optional
        If not `None` (default), the data vector and covariance matrix are
        simultaneous downscaled to avoid numerical issue.

    Returns
    -------
    float, array_like
        (Logarithmic) probability density.


Compute the multivariate normal probability density function or its
    natural logarithm given the data vector, its mean vector and covariance
    matrix.

    Parameters
    ----------
    data_vector : float, array_like
        Data vector.
    expectation_vector : float, array_like
        Mean vector.
    covariance_matrix : float, array_like
        Covariance matrix.
    ret_log : bool, optional
        If `True` (default), return logarithmic probability density.

    Returns
    -------
    density : float, array_like
        Logarithmic probability density value.


Compute the multivariate modified Student probability density
    function or its natural logarithm given the data vector, its mean
    vector and covariance matrix.

    Parameters
    ----------
    data_vector : float, array_like
        Data vector.
    expectation_vector : float, array_like
        Mean vector.
    covariance_matrix : float, array_like
        Covariance matrix.
    degree : int
        The degree number.  This could be the number of empirical
        covariance matrices used to obtain the estimated
        `covariance_matrix`.
    ret_log : bool, optional
        If `True` (default), return logarithmic probability density.

    Returns
    -------
    float, array_like
        (Logarithmic) probability density value.


r"""Compute the parametrised covariance matrix of spherical Fourier
    coefficients.

    Parameters
    ----------
    pivot : {'natural', 'spectral'}
        Pivot order for vectorisation.
    spherical_model : :class:`~harmonia.reader.models.SphericalCorrelator`
        Spherical correlator base model.
    **kwargs
        Parameters (other than `pivot`) to be passed to |correlator_matrix|
        of `spherical_correlator`.

    Returns
    -------
    covariance_matrix : complex :class:`numpy.ndarray`
        Covariance matrix.

    See Also
    --------
    :class:`~harmonia.reader.models.SphericalCorrelator`


Compute the parametrised mean and covariance of Cartesian
    power spectrum multipoles.

    Parameters
    ----------
    pivot : {'order', 'wavenumber'}
        Pivot order for vectorisation.
    orders : list of int
        Orders of the power spectrum multipoles.
    cartesian_model : :class:`~.models.CartesianMultipoles`
        Cartesian power multipoles base model.
    covariance_estimator : :class:`~.CovarianceEstimator` *or None, optional*
        Cartesian power multipole covariance estimator.  Its
        :attr:`wavenumbers` must match wavenumbers associated
        with `cartesian_model`.  If `None`, no correlation between power
        spectrum multipoles is assumed but `mode_counts` must be provided
        for calculating the power spectrum variance.
    mode_counts : int, array_like or None, optional
        Number of independent modes for each power spectrum measurement
        (default is `None`) used to calculate the power spectrum variance.
        Ignored if `covariance_estimator` is provided.
    **kwargs
        Parameters (other than `orders`) to be passed to
        |convolved_power_multipoles| of `cartesian_model`.

    Returns
    -------
    expectation : float :class:`numpy.ndarray`
        Power spectrum expectation at the specified wavenumbers.
    covariance : float :class:`numpy.ndarray`
        Power spectrum variance at the specified wavenumbers.


Evaluate the spherical map logarithmic likelihood.

        Parameters
        ----------
        b_1 : float
            Scale-independent linear bias.
        f_nl : float or None
            Local primordial non-Gaussianity.
        exclude_degrees : tuple of int, optional
            If not empty (default), modes whose spherical degree
            match one of its elements are removed from the likelihood.
        compression_matrix : :class:`numpy.ndarray` *or None*, optional
            If not `None` (default), both the data vector and the model
            covariance matrix are processed for data compression.  This
            must be compatible with `exclude_degrees`, i.e. it accounts
            for elements removed from the data vector and covariance
            matrix by `exclude_degrees`.
        **kwargs
            Additional parameters to be passed to |correlator_matrix| of
            :attr:`base_spherical_model`.

        Returns
        -------
        log_likelihood : float
            Logarithmic likelihood.

        See Also
        --------
        :class:`~harmonia.surveyor.synthesis.generate_compression_matrix`

        :class:`~harmonia.reader.likelihoods.spherical_covariance`

        |correlator_matrix|


Load pre-computed angular coupling coefficients which are
        independent of the cosmological model.

        Parameters
        ----------
        angular_couplings : dict{tuple(tuple, tuple): complex}
            Pre-compute angular couplings.

        Raises
        ------
        ValueError
            If the number of entries in `angular_couplings` do not match
            the class instance.


Compile all coupling coefficients.

        Parameters
        ----------
        pixelate : int or None, optional
            If not `None` (default), this sets the 'NSIDE' parameter of
            `healpy` pixelation for angular coupling integration.


r"""Compute coupling coefficients for given triplet indices.

        Parameters
        ----------
        mu, nu : tuple(int, int) or tuple(int, int, int)
            Coefficient triplet or reduced doublet index.
        coupling_type : {'angular', 'radial', 'RSD'}
            Coupling type.
        pixelate : int or None, optional
            If not `None` (default), this sets the 'NSIDE' parameter of
            `healpy` pixelation for computing angular coupling
            coefficients.

        Returns
        -------
        cofficient : float or complex :class:`numpy.ndarray`
            Coupling coefficient of the specified type.


Save compiled couplings as a .npz file.

        Parameters
        ----------
        output_file : *str or* :class:`pathlib.Path`
            Output file path.


Load compiled couplings from a .npz file.

        Parameters
        ----------
        input_file : *str or* :class:`pathlib.Path`
            Input file path.


Change a directory of couplings from nested dictionaries to a
    dictionary of arrays for mass access to raidial and RSD coupling
    coefficients of adjacent indices.

    Parameters
    ----------
    couplings : :class:`~.reader.couplings.Couplings`
        Couplings object (default is `None`).

    Returns
    -------
    grouped_couplings : dict{tuple: list}
        Radial and RSD couplings grouped for mass access.


Spherical Fourier coefficients for the density contrast between
        data and random catalogues.

        Notes
        -----
        When the spherical map is initialsed upon creation or this
        is directly or indirectly accessed without initialising the
        spherical map upon creation, discrete spherical Fourier transform
        is performed by direct summation over all selected objects in the
        paired catalogues.

        Calling this method stores the transformed number densities of
        data and random catalogues internally for further processing,
        e.g. for :meth:`mode_power`.  Computational redundancy is reduced
        by employing parity relations between spherical harmonics of the
        same degree but opposite orders.

        Returns
        -------
        :class:`~harmonia.algorithms.arrays.SphericalArray`
            Density contrast coefficients of the spherical map.


Spherical Fourier mode power suitably normalised.

        In the simplest case of a full-sky statistically isotropic map
        without any mode coupling, this is equivalent to the Cartesian
        power spectrum at the same wavenumbers.

        Returns
        -------
        dict
            Spherical mode power at discrete mode wavenumbers with mode
            counts and indices.


Indicate whether an object lies within the a spherical domain
    centred at the origin.

    Parameters
    ----------
    cartesian_position : float, array_like
        Object position in Cartesian coordinates.
    bounding_radius : float
        Bounding radius of the spherical domain.

    Returns
    -------
    bool :class:`numpy.ndarray`
        `True` if the objection position lies within the spherical domain.


Print strings to be used as Mathematica/WolframAlpha queries.


Compute the spherical Fourier density contrast coefficients of
        the synthetic catalogue.

        Parameters
        ----------
        disc : :class:`~.algorithms.discretisation.DiscreteSpectrum`
            Discrete spectrum.

        Returns
        -------
        :class:`~harmonia.algorithms.arrays.SphericalArray`
            Density contrast coefficients.

        See Also
        --------
        :class:`~harmonia.mapper.map_transform.SphericalMap`


Compute the power spectrum multipoles of the synthetic
        catalogue.

        Parameters
        ----------
        orders : sequence of int
            Orders of the power spectrum multipoles.
        kmin : float, optional
            Minimum wavenumber of the map (in :math:`h`/Mpc)
            (default is 1.e-4).
        kmax : float or None, optional
            Maximum wavenumber of the map (in :math:`h`/Mpc)
            (default is `None`).  If `None`, `kmax` is the Nyquist
            wavenumber determined from `num_mesh`.
        dk : float or None, optional
            Wavenumber bin width (in :math:`h`/Mpc) (default is `None`).
        num_mesh : int, optional
            Mesh number per dimension for interpolating the discrete
            catalogues on a grid.
        resampler : {'cic', 'tsc', 'pcs'}, optional
            Grid assignment scheme (default is ``'tsc'``) for catalogue
            interpolation.
        interlaced : bool, optional
            If `True` (default), use interlacing for aliasing mitigation.

        Returns
        -------
        :class:`~harmonia.algorithms.arrays.CartesianArray`
            Power spectrum multipoles binned in wavenumbers.

        See Also
        --------
        :class:`~harmonia.mapper.map_transform.CartesianMap`


Compute the Fourier-space window function multipoles from the
        synthetic catalogue.

        Parameters
        ----------
        orders : sequence of int
            Orders of the power spectrum multipoles.
        kmin : float, optional
            Minimum wavenumber (in :math:`h`/Mpc) (default is 1.e-6).
        **kwargs
            Any other parameters to be passed to :meth:`~.compute_power`.

        Returns
        -------
        :class:`~harmonia.algorithms.arrays.CartesianArray`
            Window function multipoles binned in logarithmic wavenumbers.

        See Also
        --------
        :meth:`~.compute_power`


Compute the configuration-space mask function multipoles from
        the synthetic catalogue by Hankel transform of the window function
        multipoles.

        Parameters
        ----------
        orders : sequence of int
            Orders of the mask function multipoles.
        *args, **kwargs
            Any other position and keyword parameters to be passed to
            :meth:`~.compute_window`.  Only required when
            :attr:`window_multipoles` is not available.

        Returns
        -------
        :class:`numpy.ndarray`
            Mask function multipoles binned in logarithmic separations.
            This is a NumPy structured array similar to
            :attr:`array` of :class:`~.algorithms.arrays.CartesianArray`.

        See Also
        --------
        :class:`~.algorithms.arrays.CartesianArray`


Save the estimator with its attributes as a .npz file.

        Parameters
        ----------
        output_file : *str or* :class:`pathlib.Path`
            Output file path.


Load the estimator with its attributes from a .npz file.

        Parameters
        ----------
        input_file : *str or* :class:`pathlib.Path`
            Input file path.


r"""Generate a compression matrix for spherical modes.

    Notes
    -----
    Compression is achieved by discarding non-positive eigenvalue modes
    that are at least :math:`10^{-8}` times smaller than the largest and
    in addition any of the following means:

        * `discard` is passed to discard a number of low-eigenvalue modes;
        * `extremal_model_kwargs` is passed and eigenvalues of the
          resulting model covariance are compared with those from
          `fiducial_covariance`.  Modes corresponding to low, insensitive
          (i.e. relative difference less than `sensitivity_threshold`)
          are discarded.
        * A combination of the above if the appropriate parameters
          are passed.

    Parameters
    ----------
    fiducial_model_kwargs : dict
        Fiducial model parameters to be passed to
        :func:`~.reader.likelihoods.spherical_covariance`.
    extremal_model_kwargs : dict or None, optional
        Extremal model parameters to be passed to
        :func:`~.reader.likelihoods.spherical_covariance`.
    sensitivity_threshold: float, optional
        Sensitivity threshold for modes deemed discardable
        (default is 0.01).
    discard : int or None, optional
        Number of low-eigenvalue modes to discard from all modes
        (default is `None`).

    Returns
    -------
    compression_matrix : :class:`numpy.ndarray`
        Compression matrix.


Generate mask function given the sky fraction corresponding to a
    spherical cap (rather than a wedge).

    Parameters
    ----------
    coord_system : {'cartesian', 'spherical', 'sky'}
        Coordinate system of the generated mask function.  If 'sky', the
        returned function can accept either 2-d or 3-d coordinates.
    sky_fraction : float, optional
        Sky coverage, ``0 < sky_fraction <= 1``.
    box_shift : float, array_like or None, optional
        Passed as `box_centre` to :func:`~.coordinates.to_box_coords` so
        that the resulting mask function accepts Cartesian coordinates
        with origin at a box corner.  Ignored unless `coord_system` is
        'cartesian'.

    Returns
    -------
    mask_function : callable
        A mask function accepting `coord_system` as its coordinate system
        and returning boolean values.


Generate mask function from a veto mask map.

    Parameters
    ----------
    coord_system : {'cartesian', 'spherical', 'sky'}
        Coordinate system of the generated mask function.  If 'sky', the
        returned function can accept either 2-d or 3-d coordinates.
    mask_map : :class:`numpy.ndarray` or None, optional
        A veto array corresponding to pixels in a `healpy` mask map with
        parameter `nside` (default is `None`).  Ignored if
        a `healpy`-generated .fits file for the mask map is provided.
    nside : int or None, optional
        'NSIDE' parameter of the `healpy` mask map (default is `None`).
        Ignored if  a `healpy`-generated .fits file for the
        mask map is provided.
    mask_map_file : *str or* :class:`pathlib.Path`
        `healpy`-generated .fits file for the mask map.  Must contain
        the 'NSIDE' parameter in its header.
    box_shift : float, array_like or None, optional
        Passed as `box_centre` to :func:`~.coordinates.to_box_coords` so
        that the resulting mask function accepts Cartesian coordinates
        with origin at a box corner.  Ignored unless `coord_system` is
        'cartesian'.
    ret_nside : bool, optional
        If `True` (default is `False`), return the `nside` parameter
        from `mask_map` read in.

    Returns
    -------
    mask_function : callable
        A mask function accepting `coord_system` as its coordinate system
        and returning boolean values.


Generate selection function based on a probability distribution
    suitably rescale horizontally and vectically.

    Notes
    -----
    If the generated selection function detects 3-d input coordinate
    arrays, it would assume the coordinates are the Cartesian; otherwise
    it assumes the coordinates are the radial coordinate.

    Parameters
    ----------
    coord_scale : float
        Coordinate scale of the selection function, e.g. the maximum
        comoving radius of a catalogue.
    peak : float
        Peak value of the selection function used for renormalising
        the probability density function by its maximum value.
    distribution : {'gaussian', 'gamma'}
        Distribution to use, either 'gaussian' or 'gamma'.
    scale, location, shape : float or None, optional
        Scale, location and shape parameter of the distribution.  For
        a normal distribution, `scale` is the standard deviation and
        `location` is the mean in units of `coord_scale`; for a gamma
        distribution, see :class:`scipy.stats.gamma`.

    Returns
    -------
    callable
        Normalised selection function of the same coordinate as the sample
        coordinates.


Generate selection function at a constant value by a cut.

    Notes
    -----
    If the generated selection function detects 3-d input coordinate
    arrays, it would assume the coordinates are the Cartesian; otherwise
    it assumes the coordinates are the radial coordinate.

    Parameters
    ----------
    low_end, high_end : float
        Low and high end of the cut in some selection coordinate.

    Returns
    -------
    callable
        Constant cut selection function.


Generate selection function samples from redshift samples.

    The selection function is normalised by the mean number density
    inferred from the samples and the sky fraction.

    Parameters
    ----------
    selection_coordinate : {'z', 'r'}
        Coordinate of the generated selection function, either redshift
        'z' or comoving distance 'r'.
    coord_scale : float
        Coordinate scale used to rescale the selection coordinates, e.g.
        the maximum comoving radius of the catalogue to which the
        selection function is applied.
    redshift_samples : float, array_like
        Redshift samples.
    cosmo : :class:`nbodykit.cosmology.cosmology.Cosmology`
        Cosmological model providing the redshift-to-distance conversion
        and thus normalisation of the selection function by volume.
    sky_fraction : float, optional
        The sky coverage of redshift samples as a fraction used to
        normalise the selection function (default is 1.),
        ``0 < sky_fraction <= 1``.
    bins : int, str or None, optional
        Number of bins or binning scheme used to generate the selection
        function samples (see :func:`numpy.histogram_bin_edges`).
        If `None` (default), Scott's rule for binning is used.

    Returns
    -------
    samples, coords : :class:`numpy.ndarray`
        Normalised (dimensionless) selection function samples and
        corresponding coordinates.


Generate selection function interpolated from normalised selection
    function samples at sample coodinates.

    Notes
    -----
    If the generated selection function detects 3-d input coordinate
    arrays, it would assume the coordinates are the Cartesian; otherwise
    it assumes the coordinates are the radial coordinate.

    Parameters
    ----------
    sample_selections, sample_coords : float :class:`numpy.ndarray`
        Selection function samples and coordinates.

    Returns
    -------
    callable
        Normalised selection function of the same coordinate as the sample
        coordinates.


r"""Convert 3-d Cartesian coordinate arrays to spherical coordinate
    arrays.

    The coordinate transformation is given by

    .. math::

        r = \sqrt{x^2 + y^2 + z^2} \,, \quad
        \theta = \arccos(z/r) \,, \quad
        \phi = \arctan(y/x) \,,

    where the image of :math:`\arccos` is :math:`[0, \pi]`, and
    :math:`\arctan` has an extended image set :math:`[0, 2\pi]`.

    Parameters
    ----------
    cartesian_coords : float, array_like
        Cartesian coordinates.

    Returns
    -------
    spherical_coords : float :class:`numpy.ndarray`
        Spherical coordinates.


r"""Convert 3-d spherical coordinate arrays to Cartesian coordinate
    arrays.

    The coordinate transformation is given by

    .. math::

        x = r \sin\theta \cos\phi \,, \quad
        y = r \sin\theta \sin\phi \,, \quad
        z = r \cos\theta \,.

    Parameters
    ----------
    spherical_coords : float, array_like
        Spherical coordinates.

    Returns
    -------
    cartesian_coords : float :class:`numpy.ndarray`
        Cartesian coordinates.


r"""Convert 3-d (or 2-d) sky coordinate arrays (Z, DEC, RA)
    (or (DEC, RA)) to spherical coordinate arrays.

    The spherical surface coordinate transformation is given by

    .. math::

        \theta = \frac{\pi}{180} (90 - \delta) \,, \quad
        \phi = \frac{\pi}{180} \alpha \,.

    where :math:`\delta` is the declination (DEC) and :math:`\alpha`
    the right ascension (RA) both given in degrees.

    The radial coordinate transformation from redshifts is given by
    :meth:`cosmo.comoving_distance` if the input coordinates are 3-d
    and a redshift-to-distance conversion function is provided.

    Parameters
    ----------
    sky_coords : float, array_like
        Sky coordinates (2-d or 3-d).
    z_to_r : callable or None, optional
        Redshift-to-distance conversion (default is `None`).

    Returns
    -------
    spherical_coords : float :class:`numpy.ndarray`
        Spherical surface coordinates.


r"""Convert 3-d spherical coordinate arrays to sky coordinate arrays.

    The spherical surface coordinate transformation is given by

    .. math::

        \delta = 90 - \frac{180}{\pi} \theta \,, \quad
        \alpha = \frac{180}{\pi} \phi \,.

    where :math:`\delta` is the declination (DEC) and :math:`\alpha`
    the right ascension (RA) both given in degrees.

    The radial coordinate transformation is given by a
    distance-to-redshift conversion if it provided.

    Parameters
    ----------
    sky_coords : float, array_like
        Sky coordinates.
    z_from_r : callable or None, optional
        Distance-to-redshift conversion (default is `None`).

    Returns
    -------
    sky_coords : float :class:`numpy.ndarray`
        Sky coordinates.


Convert a function defined for a native 3-d curvilinear coordinate
    system to an equivalent function defined for a box in
    Cartesian coordinates.

    Parameters
    ----------
    native_coord_system : {'null', 'spherical', 'sky'}, optional
        Native coordinate system of the function.  If 'cartesian' (with
        the implicit assumption that the origin is at the box centre),
        the function is unconverted unless `box_shift` is also provided.
    box_centre : float, array_like or Nonw
        If provided, translate the box coordinates so that the (positive)
        `box_centre` is moved to(0, 0, 0).  This is needed to when the
        wrapped function needs to accept box coordinates with the origin
        placed at its corner whilst the `native_coord_system` has the
        origin at the centre of the box (e.g. 'spherical').
    conversion_kwargs : dict or None, optional
        Additional parameters to use in conversion, e.g. `z_from_r`
        if `native_coords` is 'sky' (default is `None`).

    Returns
    -------
    callable
        The original function now accepting Cartesian coordinates.


r"""Discrete mode wavenumbers :math:`k_{\ell n}`.

        Returns
        -------
        dict
            Mode wavenumbers as a dictionary accessed by
            doublet tuples :math:`(\ell, n)`.


r"""Normalisation coefficients :math:`\kappa_{\ell n}`.

        Returns
        -------
        dict
            Normalisation coefficients as a dictionary accessed by
            doublet tuples :math:`(\ell, n)`.


r"""Evaluate the angular integrand with the Jacobian factor
    :math:`\sin\theta`.

    Notes
    -----
    Angular arguments are in reverse order for outward double integration.

    Parameters
    ----------
    phi, theta: float, array_like
        Angular coordinates in radians.
    func : callable
        Angular function to be integrated.
    complex_part : {'real', 'imag'}
        Real or imaginary part.

    Returns
    -------
    float, array_like
        Real or imaginary part of the complex angular integrand value.


r"""Evaluate the radial integrand with the Jacobian factor :math:`r^2`.

    Parameters
    ----------
    r: float, array_like
        Radial coordinate.
    func : callable
        Radial function to be integrated.

    Returns
    -------
    float, array_like
        Radial integrand value.


r"""Compute the full spherical angular integral.

    Notes
    -----
    Arguments :math:`(\theta, \phi)` of `angular_func` must be in radians
    in the domain :math:`[0, \pi] \times [0, 2\pi]`.

    Parameters
    ----------
    angular_func : callable
        Angular function to be integrated.

    Returns
    -------
    complex
        Angular integral value.


Compute the radial integral up to the given maximum radius.

    Parameters
    ----------
    radial_func : callable
        Radial function to be integrated.
    rmax : float
        Upper radial limit ``rmax > 0``.

    Returns
    -------
    integral : float
        Radial integral value.


r"""Compute the full spherical angular integral with pixelation.

    Notes
    -----
    Arguments :math:`(\theta, \phi)` of `angular_func` must be in radians
    in the domain :math:`[0, \pi] \times [0, 2\pi]`.

    Parameters
    ----------
    angular_func : callable
        Angular function to be integrated.
    nside : int
        'NSIDE' parameter for `healpy` pixelation.

    Returns
    -------
    complex
        Angular integral value.


Save the structured array.

        Parameters
        ----------
        output_file : *str or* :class:`pathlib.Path`
            Output file path.
        extension : {'.pkl', '.npz'}
            Output file extension.


Load the structured array from a .npz or .pkl file.

        Parameters
        ----------
        input_file : *str or* :class:`pathlib.Path`
            Input file path.


r"""Returrn a data vector from the 'coefficient' field.

        Vectorisation is performed by *pivoting* in either of the following
        orders of precedence---

            * 'natural': ordered by :math:`(\ell, m, n)`;
            * 'spectral': ordered by :math:`(k_{\ell n}, m)`.

        Subarrays of equivalent :math:`(\ell, n)` may be further collapsed
        over spherical order :math:`m` by simple averaging or averaging in
        quadrature.

        Parameters
        ----------
        pivot : {'natural', 'spectral'}
            Pivot order for vectorisation.
        collapse : {None, 'mean', 'qaudrature'}, optional
            If not `None` (default), subarrays are collapsed over
            equivalent spherical order :math:`m` by averaging ('mean') or
            averaging in quadrature ('qaudrature').

        Returns
        -------
        vectorised_data : :class:`numpy.ndarray`
            Vectorised coefficient data.


r"""Return a data vector from the 'power' field.

        Vectorisation is performed by *pivoting* in either of the following
        orders of precedence---

            * 'order': ordered by multipole order :math:`\ell`;
            * 'wavenumber': ordered by wavenumber :math:`k`.

        Parameters
        ----------
        pivot : {'order', 'wavenumber'}
            Pivot order for vectorisation.

        Returns
        -------
        vectorised_data : :class:`numpy.ndarray`
            Vectorised power spectrum data.


r"""Evaluate the spherical harmonic function.

    This returns :math:`Y_{\ell m}(\theta, \phi)` of degree :math:`\ell
    \geqslant 0` and order :math:`\vert {m} \vert \leqslant \ell` at the
    polar angle :math:`\theta \in [0, \pi]` and the azimuthal angle
    :math:`\phi \in [0, 2\pi]`.

    Parameters
    ----------
    ell : int, array_like
        Degree of the spherical harmonic function, ``ell >= 0``.
    m : int, array_like
        Order of the spherical harmonic function, ``|m| <= ell``.
    theta : float, array_like
        Polar angle in the interval ``[0, pi]``.
    phi: float, array_like
        Azimuthal angle in the interval ``[0, 2*pi]``.
    conj : bool, optional
        If `True` (default is `False`), return the complex conjugate.

    Returns
    -------
    complex, array_like
        :math:`Y_{\ell m}` value at `theta` and `phi`.


r"""Evaluate the spherical Bessel function of the first kind or
    its derivative.

    This returns :math:`j_{\ell}(x)` or :math:`j'_{\ell}(x)` of order
    :math:`\ell \geqslant 0`.

    Parameters
    ----------
    ell : int, array_like
        Order of the spherical harmonic function, ``ell >= 0``.
    x : float, array_like
        Argument of the spherical Bessel function.
    derivative : bool, optional
        If `True` (default is `False`), evaluate the derivative instead.

    Returns
    -------
    float, array_like
        :math:`j_{\ell}` or :math:`j'_{\ell}` value at `x`.


r"""Find positive zero(s) :math:`u_{\ell n}` of the spherical Bessel
    function :math:`j_{\ell}` of the first kind of order :math:`\ell`, or
    its derivative :math:`j'_{\ell}`, up to a maximum number
    :math:`n_\textrm{max}`.

    Solving for roots of the spherical Bessel function relies on the
    identity :math:`j_\ell(x) = \sqrt{\pi/(2x)} J_{\ell + 1/2}(x)`, where
    :math:`J_\ell(x)` is the Bessel funcion of the first kind.  Solving for
    roots of the derivative function employs the interval bisection method,
    with the interval ansatz :math:`\ell + 1 \leqslant x \leqslant
    n_\textrm{max} \operatorname{max}\{4, \ell\}`.

    Parameters
    ----------
    ell : int
        Order of the spherical Bessel function, ``ell >= 0``.
    nmax : int
        Maximum number of positive zeros to be found, ``nmax >= 1``.
    only : bool, optional
        If `True` (default), return the maximal root only.
    derivative : bool, optional
        If `True` (default is `False`), compute the zero(s) of the
        derivative function instead.

    Returns
    -------
    u_ell : float, array_like
        Positive zero(s) for order `ell` (in ascending order).


        Reads from the query urls all the concept ids

        Returns:
            (list of str) Returns all the concept ids found in the `query_url` as a list


        Validates the metadata contents of all the `concept_ids` and returns the errors

        Returns:
            (list of dict) The errors found in the metadata content of all the `concept_id`s