Callback to take action when the continuum toggle is toggled


Callback to take action when normalization slider changes


Callback to take action when RV slider changes


Callback to take action when fsed slider changes


Converts a spectrum from air to vacuum

        Based on Morton, D. C. 1991, ApJS, 77, 119
        Returns
        -------
        vaccum_spectrum: TelFitSpectrum
            The spectrum in vacuum


        [TRANSFORM] Normalize flux to a given percentile.

        Parameters
        ----------
        `percentile: float`
            The percentile at which the normalized flux is to equal 1.


        [TRANSFORM] Apply simple rotational broadening to the spectrum.

        Parameters
        ----------
        `vsini: float`
            The projected rotational velocity in km/s.


        [TRANSFORM] Apply instrumental broadening to the spectrum.

        Parameters
        ----------
        `R: int`
            The resolving power of the instrument.


        [TRANSFORM] Apply a non-relativistic Doppler shift to the spectrum.

        Parameters
        ----------
        `rv: float`
            The radial velocity in km/s.


        [TRANSFORM] Resample the spectrum onto a new spectral axis.

        Parameters
        ----------
        `spectral_axis: ArrayLike`
            The new spectral axis in Angstroms.


        [VISUALIZE] Plot a quick view of the spectrum.

        Parameters
        ----------
        `**kwargs`
            Passthrough for matplotlib.pyplot.plot.


        [ACCESS] Create a blackbody spectrum at a given temperature with units of W/m^2/nm.

        Parameters
        ----------
        `spectral_axis: ArrayLike`
            The spectral axis in Angstroms.
        `T: float`
            The temperature of the blackbody in K.


[ACCESS] The path to `gollum`'s environment file.


        [SETUP] Configure `gollum`'s environment for a model grid.

        Parameters
        ----------
        `data_path: str`
            The path to the data directory.


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

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


        Get angular diameter distance between two redshifts

        [r/(1+z2)]*sin_K([chi(z_1) - chi(z_1)]/r) where r is curvature radius and chi is the comoving radial distance

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

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


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

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

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


        Get physical time between two scalar factors in Gigayears

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

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


        Conformal time from hot big bang to redshift z in Megaparsec.

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


        Get theta_MC, an approximation of the radio of the sound horizon to the angular diameter distance at recombination.

        :return: theta_MC


    Utility function to return array of Legendre and d_{mn} functions for all L up to lmax.
    Note that d_{mn} arrays start at L_min = max(m,n), so returned arrays are different sizes

    :param lmax: maximum L
    :param x: scalar value of cos(theta) at which to evaluate
    :param m: m values to calculate d_{m,n}, etc as relevant
    :param lfacs: optional pre-computed L(L+1) float array
    :param lfacs2: optional pre-computed (L+2)*(L-1) float array
    :param lrootfacs: optional pre-computed sqrt(lfacs*lfacs2) array
    :return: (P,dP),(d11,dm11), (d20, d22, d2m2) as requested, where P starts at L=0, but spin functions start at L=Lmin


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

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


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

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


    Get the sigma^2(x) and C_{gl,2}(x) functions from the lensing power spectrum

    :param clpp: array of [l(l+1)]^2 C_phi_phi/2/pi lensing potential power spectrum
    :param xvals: array of cos(theta) values at which to calculate correlation function.
    :param lmax: optional maximum L to use from the cls arrays
    :return: sigmasq, Cg2


    Get R = 1/2 <|grad phi|^2>

    :param clpp: array of [l(l+1)]^2 C_phi_phi/2/pi lensing potential power spectrum
    :param lmax: optional maximum L to use from the cls arrays
    :return: R


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

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

    Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of astro-ph/0601594, to second order in C_{gl,2}

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


    Get the lensed power spectra from the unlensed power spectra and the lensing potential power.
    Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of astro-ph/0601594, to second order in C_{gl,2}.

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

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

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

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


    Get derivative dcl of lensed ell(ell+1)C_ell/2pi with respect to log(C^phi_L).
    To leading order (and hence not actually accurate), the lensed correction to power spectrum ix
    is given by dcl[ix,:,:].dot(np.ones(clpp.shape)).

    Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of astro-ph/0601594, to second order in C_{gl,2}

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


    Get derivative dcl of lensed minus unlensed power ell(ell+1)Delta C_ell/2pi with respect to L(L+1)C^unlens_L/2pi

    The difference in power in the lensed spectrum is given by dCL[ix, :, :].dot(cl),
    where cl is the appropriate L(L+1)C^unlens_L/2pi.

    Uses the non-perturbative curved-sky results from Eqs 9.12 and 9.16-9.18 of astro-ph/0601594, to second order in C_{gl,2}

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


        Make independent copy.
         :return: copy of self


Assign a value to this node.


Manually provide data


Read light-curve(s) in csv format

    Args:
        filename (str): data file
        settings (str): model file settings

    Returns:
        df (pd.DataFrame): dataframe with lc and metadata


Reformat SNN predictions to a DataFrame

    Args:
        pred_probs (arr): probabilities array
        ids (str, list): ids

    Returns:
        df (pd.DataFrame): reformatted predictions


Tokenizes a text file.


Wraps hidden states in new Tensors, to detach them from their history.


Generate a help message for specific command options.


Display help messages for provided command


Draw SWAG sample model.

        Args:
             scale (float): The scale parameter for covariance. Default: ``0.5``. When scale = 0.0, the ``sample`` function returns a SWA model.
             cov (bool): If True, enable calculating low-rank covariance. ``True``.
             var_clamp (float): A small positive value used to clamp the computed variance to prevent numerical issues. Default: ``1.e-30``

         Returns:
             sample_model (rnn model): A sampled SWAG model


Get performance metrics
    AUC: only valid for binomial classification, input proba of highest label class.

    Args:
        df (pandas.DataFrame) (str): with columns [target, predicted_target, class1]
        (optional) sample_target (str): for SNIa sample default is target 0

    Returns:
        accuracy, auc, purity, efficiency,truepositivefraction


Get contamination contribution by each SN type in sample percentage

    Args:
        df (pandas.DataFrame) (str): with columns [target, predicted_target, SNTYPE]
        (optional) sample_target (str): for SNIa sample default is target 0

    Returns:
        df (pandas.DataFrame) (str): with columns [SNTYPE,contamination_percentage]


Change column names to format used by performance functions

    Args:
        df (pandas.DataFrame) (str): with columns [key_class*]
        keep (list) (str): list of keys to keep apart from ["target","SNTYPE","SNID","SIM_REDSHIFT_CMB"} if available

    Returns:
        df (pandas.DataFrame) (str): with columns [class*, predicted_target]


Create latex tables from summary stats selection
    Table of metric by redshift given and early classification

    Args:
        df (pandas.DataFrame) : dataframe to convert
        outname (str) : name of latex table
        (optional) metric (str): which metric to output, default is accuracy

    Returns:
        Latex table: to write


Load a FIT file and cast it to a PANDAS dataframe

    Args:
        fit_file_path (str): path to FIT file

    Returns:
        (pandas.DataFrame) load dataframe from FIT file


Match the target class (integer in {0, ..., 6} to the name
    of the class, i.e. something like "SN Ia" or "SN CC"

    Args:
        target (int): specifies the classification target
        settings (ExperimentSettings): custom class to hold hyperparameters
        simplify (Boolean): if True do not show all classes

    Returns:
        (str) the name of the class


Create classes based on a type columns

    Depending on the number of classes (2 or all), we create distinct
    target columns

    Args:
        df (pandas.DataFrame): the input dataframe
        settings (ExperimentSettings): controls experiment hyperparameters
        type_column (str): the type column in df

    Returns:
        (pandas.DataFrame) the dataframe, with new target columns


Load the FITOPT file as a pandas dataframe

    Pickle it for future use (it is faster to load as a pickled dataframe)

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters
        verbose (bool): whether to display logging message. Default: ``True``

    Returns:
        (pandas.DataFrame) dataframe with FITOPT data


Read the HEAD FIT file, add target columns and return
    in pandas DataFrame format

    Args:
        file_path (str): the  path to the header FIT file
        settings (ExperimentSettings): controls experiment hyperparameters
        columns (lsit): list of columns to keep. Default: ``None``

    Returns:
        (pandas.DataFrame) the dataframe, with new target columns


Read the HEAD csv file, add target columns and return
    in pandas DataFrame format

    Args:
        file_path (str): the  path to the header FIT file
        settings (ExperimentSettings): controls experiment hyperparameters
        columns (lsit): list of columns to keep. Default: ``None``

    Returns:
        (pandas.DataFrame) the dataframe, with new target columns


Compute the delta time between two consecutive observations

    Args:
        df (pandas.DataFrame): dataframe holding lightcurve data

    Returns:
        (pandas.DataFrame) dataframe holding lightcurve data with delta_time features


    Remove rows in the same light curve after a gap > 150 days
    Reason: If no signal has been saved in a time frame of 150 days,
    it is unlikely there is much left afterwards

    Args:
        df (pandas.DataFrame): dataframe holding lightcurve data

    Returns:
        (pandas.DataFrame) dataframe where large delta time rows have been removed


Load physical information related to the created database of lightcurves

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters

    Returns:
        (pandas.DataFrame) dataframe holding physics information about the dataset


Normalization strategy for the fluxes and fluxes error

    - Log transform the data
    - Mean and std dev normalization

    Args:
        arr (np.array): data to normalize

    Returns:
        (LogStandardized) namedtuple holding normalization data


Saved processed dataframe to HDF5

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters
        df (pandas.DataFrame): dataframe holding processed data


Configure directories where data is read from or dumped to
        during the course of an experiment


Create a unique database name based on the dataset required
        by the settings


Utility to define the features used to train NN=based models


Define the model name for all NN based classifiers


Create an array holding the data-normalization parameters
        used to normalize certain features in the NN-based classification
        pipeline


Utility to check the database has been built


Normalize array before input to RNN

    - Log transform
    - Mean and std dev normalization

    Args:
        arr (np.array) array to normalize
        settings (ExperimentSettings): controls experiment hyperparameters

    Returns:
        (np.array) the normalized array


UnNormalize array

    Args:
        arr (np.array) array to normalize
        settings (ExperimentSettings): controls experiment hyperparameters

    Returns:
        (np.array) the normalized array


Utility to create a list of data tuples used as inputs to RNN model

    The ``settings`` object specifies which feature are selected

    Args:
        idxs (np.array or list): idx of data point to select
        arr_data (np.array): features
        arr_target (np.array): target
        arr_SNID (np.array): lightcurve unique ID
        settings (ExperimentSettings): controls experiment hyperparameters
        n_features (int): total number of features in arr_data
        desc (str): message to display while loading
        test (bool): If True: add more data to the list, as it is required at test time.
            Default: ``False``

    Returns:
        (list) the list of data tuples


Load data from HDF5

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters
        test (bool): If True: load data for test. Default: ``False``

    Returns:
        list_data_test (list) test data tuples if test is True

        or

        Tuple containing
            - list_data_train (list): training data tuples
            - list_data_val (list): validation data tuples


Full training step : Forward and Backward pass

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters
        rnn (torch.nn Model): pytorch model to train
        packed_tensor (torch PackedSequence): input tensor in packed form
        target_tensor (torch Tensor): target tensor
        criterion (torch loss function): loss function to optimize
        optimizer (torch optim): the gradient descent optimizer
        batch_size (int): batch size
        num_batches (int): number of minibatches to scale KL cost in Bayesian


Eval step: Forward pass only

    Args:
        rnn (torch.nn Model): pytorch model to evaluate
        packed_tensor (torch PackedSequence): input tensor in packed form

    Returns:
        output (torch Tensor): output of rnn


Draw a sample of SwagModel and evaluate: Forward pass only

    Args:
        model (SwagModel): SwagModel
        scale (float): The scale parameter for covariance
        cov (bool): If True, enable calculating low-rank covariance
        packed_tensor (torch PackedSequence): Input tensor in packed form

    Returns:
        output (torch Tensor): Output of a sample model


Plot loss curves

    Plot training and validation logloss

    Args:
        d_train (dict of arrays): training log losses
        d_val (dict of arrays): validation log losses
        epoch (int): current epoch
        settings (ExperimentSettings): custom class to hold hyperparameters


Obtain a loss string to display training progress

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters
        d_monitor (dict): maps {metric:value}
        training_time (float): amount of time training took

    Returns:
        loss_str (str): the loss string to display


Save RandomForest model

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters
        clf (RandomForestClassifier): RandomForest model


Load RandomForest model

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters
        model_file (str): path to saved randomforest model. Default: ``None``

    Returns:
        (RandomForestClassifier) RandomForest model


Train a RandomForestClassifier and evaluate AUC, precision, accuracy
    on a validation set

    Args:
        clf (RandomForestClassifier): RandomForest model to fit and evaluate
        X_train (np.array): the training features
        y_train (np.array): the training target
        X_val (np.array): the validation features
        y_val (np.array): the validation target


Transforms seconds into a string with days, hours, minutes and seconds.


Build dataset split in the following way

    - Downsample each class so that it has the same cardinality as the lowest cardinality class
    - Randomly assign lightcurves to a 80/10/10 train test val split (except Out-of-distribution data 1/1/98)

    OOD:
        Will use the complete sample for testing, does not require settings.

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters


    Carry out preprocessing on FITS file and save results to pickle.
    Pickle is preferred to csv as it is faster to read and write.

    - Join column from header files
    - Select columns that will be useful laer on
    - Compute SNID to tag each light curve
    - Compute delta times between measures
    - Filter preprocessing
    - Removal of delimiter rows

    Args:
        file_path (str): path to ``.FITS`` file
        settings (ExperimentSettings): controls experiment hyperparameters


    Carry out preprocessing on csv file and save results to pickle.
    Pickle is preferred to csv as it is faster to read and write.

    - Compute delta times between measures
    - Filter preprocessing

    Args:
        file_path (str): path to ``.csv`` file
        settings (ExperimentSettings): controls experiment hyperparameters


Preprocess the FITS data

    - Use multiprocessing/threading to speed up data processing
    - Preprocess every FIT file in the raw data dir
    - Also save a DataFrame of Host Spe for publication plots

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters


    Carry out pivot: we will group time-wise close observations on the same row
    and each row in the dataframe will show a value for each of the flux and flux
    error column

    - All observations withing 8 hours of each other are assigned the same MJD
    - Results are cached with pickle

    Args:
        filename (str): path to a ``.pickle`` file containing pre-processed data
        settings (ExperimentSettings): controls experiment hyperparameters


    - Use multiprocessing/threading to speed up data processing
    - Pivot every file in list_files and cache the result with pickle

    Args:
        list_files (list): list of ``.pickle`` files containing pre-processed data
        settings (ExperimentSettings): controls experiment hyperparameters


Main function for data processing

    - Create the train test val splits
    - Preprocess all the FITs data, then pivot
    - Save all of the processed data to a single HDF5 database

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters


Aggregate all pre-computed METRICS files into a single dataframe
    for analysis

    Save a csv dataframe aggregating all the metrics

    Args:
        settings (ExperimentSettings): custom class to hold hyperparameters


Format data into SuperNNova-friendly format

    Args:
        df (pandas.DataFrame): dataframe with light-curves
        settings (ExperimentSettings): custom class to hold hyperparameters
    Returns:
        df (pandas.DataFrame): reformatted data


Obtain predictions for light-curves
    Args:
        df (DataFrame): light-curves to classify
        model_file (str): Path+name of model to use for predictions
        device (str): wehter to use cuda or cpu

    Returns:
        idx (list): light-curve indices after classification (they are resorted)
        preds (np.array): predictions for this model (shape= len(idx),model_nb_class)


Utility to find the index of the element of ``array`` that most closely
    matches ``value``

    Args:
        array (np.array): The array in which to search
        value (float): The value for which we are looking for a match

    Returns:
        (int) the index of of the element of ``array`` that most closely
        matches ``value``


Dispatch different batch prediction functions based on given mode.


Construct a dict to hold prediction results.


Flatten the prediction dict and convert it to pandas.DataFrame.


Get prediction results and store them in the given dict.


Train RNN models with a 1-cycle policy

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters


Save normalization used for training

    Saves a json file with the normalization used for each feature

    Arguments:
        settings (ExperimentSettings): controls experiment hyperparameters


Train RNN models

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters


Train RNN models with a decay on plateau policy

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters


Train RNN models with SWAG

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters


Resets parameter data pointer so that they can use faster code paths.


Logsumexp trick to avoid overflow in a log of sum of exponential expression

    Args:
        x (Tensor): the input on which to compute the log of sum of exponential

    Returns:
        logsum (Tensor): the computed log of sum of exponential


Load model corresponding to settings
    or (if specified) load a list of models.

    Args:
        settings: (ExperimentSettings) custom class to hold hyperparameters
        int (nb_lcs): number of light-curves to plot, default is 1


Load model corresponding to settings
    or (if specified) load a list of models.

    - Show evolution of classification for one time-step, then 2, up to all of the lightcurve
    - For Bayesian models, show uncertainty in the prediction
    - Figures are save in the figures repository

    Args:
        settings: (ExperimentSettings) custom class to hold hyperparameters
        int (nb_lcs): number of light-curves to plot, default is 1


Create GIFs for classification


Utility for gridspec of lightcruves

    Args:
        df (pandas.DataFrame): dataframe holding the data
        SNIDs (np.array or list): holds lightcurve ids
        settings (ExperimentSettings): controls experiment hyperparameters


Plot lightcurves specified by SNID_idxs from the
    preprocessed, pickled database

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters
        SNIDs (list): list of SN lightcurve IDs to plot


Plot lightcurves specified by SNID_idxs from the
    HDF5 database

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters
        SNID_idxs (list): list of SN lightcurve index to plot


Plot a random subset of lightcurves

    2 plots: one with preprocessed data and one with processed data
    The two plots should show the same data

    Args:
        settings (ExperimentSettings): controls experiment hyperparameters


From grouped prediction df create a df with sigma values


Plot accuracy vs number of SNe used for training

    Args:
        df (DataFrame): prediction dataframe
        settings (ExperimentSettings): custom class to hold hyperparameters

    Returns:
        figure (png)


Plot reliability diagram

    Args:
        settings (ExperimentSettings): custom class to hold hyperparameters

    Returns:
        figure (png)


Plot confusion matrix
    Based on sklearn tutorial

    Args:
        settings (ExperimentSettings): custom class to hold hyperparameters
        cm (np.array): confusion matrix
        classes (list): name of classes in cm
        normalize (optional): Normalization can be applied by setting `normalize=True`
        cmap (colormap)
        nameout (optional): out name for figure

    Returns:
        figure (png)


Plot data properties as violin plots.

    Far from optimized code: seaborn does not make this easy so added
    a lot of formatting using raw matplotlib commands

    Args:
        df (DataFrame): prediction dataframe
        fname (filename):
        settings (ExperimentSettings): custom class to hold hyperparameters

    Returns:
        figure (png)


Plot scatter plot

    Args:
        bin_centers (np.array): x centers
        y_dic (dict): y values
        xname (str): xlabel
        yname (str): ylabel
        label_list (list(str)): for legend
        color_sequence (list(str)): color code
        MARKER_LIST (list(str)): marker code
        nameout (str): out name of figure (.png)
        extra_line (optional): extra line on 0 and 100 (y)

    Returns:
        figure (png)


Plot accuracy matrix

    Args:
        acc_dic (dict): with np.arrays of accuracy
        n_meas_dic (dict): with n measurements required for this accuracy
        settings (ExperimentSettings): custom class to hold hyperparameters
        nameout (str): outname for plot
    Returns:
        figure (png)


Plot Hubble diagram residuals and histograms
    selects class sample and performas HD

    Args:
        df (DataFrame): predictions
        nameout (str): outname figure
        threshold_var (str): which class used for sample selection
        threshold_list (list): list of probability threshold for selecting sample
        threshold_sign (str): sign of the probability threshold (e.g. ">" )
    Returns:
        figure (png)


Seaborn friendly formatting

    Basic formatting and eliminating outliers (to avoid rejection by seaborn of pd.DataFrame)

    Args:
        df (DataFrame): predictions
        settings (ExperimentSettings): custom class to hold hyperparameters
    Returns:
        df (DataFrame): reformatted


Obtain measurements
    Args:
        df (DataFrame): predictions
        settings (ExperimentSettings): custom class to hold hyperparameters
        group_bayesian (Boolean): if BRNNs ar eused need to group predictions
    Returns:
        df (DataFrame): with measurements and necessary keys to compute accuracy


Add distance modulus
    Args:
        df (DataFrame): with SALT2 fitted features
    Returns:
        df (DataFrame): with distance modulus computed


Efficiency curve for different probabilities

    Args:
        df (DataFrame): with SALT2 fitted features
    Returns:
        mean_bins (np.array)
        efficience (np.array)


Dataset violin plots
    peak magnitudes and redshift distributions of representative and non-representative datasets

    Args:
        df (DataFrame): predictions
        settings (ExperimentSettings): custom class to hold hyperparameters


Performance: accuracy vs. size training set
        Uses only Saltfit data and Baseline and Random Forest models

    Args:
        settings (ExperimentSettings): custom class to hold hyperparameters


Purity and contamination redshift evolution

    Args:
        df (DataFrame):
        modelname (str): name of model to be used
        settings (ExperimentSettings): custom class to hold hyperparameters


Matrix with accuracy w.r. number of measurements in a band

    Correlation between accuracy and a certain number of observations required per filter

    Args:
        df (DataFrame):
        modelname (str): name of model to be used
        settings (ExperimentSettings): custom class to hold hyperparameters


Hubble residuals for classified supernovae as type Ia

    Uses SALT2 fits to compute the distance modulus, therefore list is not complete if fit failed.

    Args:
        df (DataFrame):
        modelname (str): name of model to be used
        fits (DataFrame): information from SALT2 fit
        settings (ExperimentSettings): custom class to hold hyperparameters


format and add distance modulus info
        including error bars


Get confusion matrix from predictions

    Args:
        df (DataFrame): predictions for a given model
        modelname (str): name of model to be used
        settings (ExperimentSettings): custom class to hold hyperparameters


Plot RNN inference speed benchmarks

    **N.B.** You should have run the speed benchmarks with

    .. code: python

        python run.py --speed

    - Plot speed based on device
    - Plot speed based on choice of model (BBB, Variational or Baseline)

    Args:
        dump_dir (str): Root folder where results are stored


OOD classification for a model (ppercentages of predictions by class and uncertainties)

    Args:
        df (pandas.DataFrame) : summary statistics df
        list: list with models to use
        settings (ExperimentSettings): custom class to hold hyperparameters


Attach a text label above each bar displaying its height


Plots for SuperNNova paper

    Saved in settings.figures_dir. Need to provide prediction files and linked settings

    Args:
        settings (ExperimentSettings): custom class to hold hyperparameters


Select a subsample of a pandas Dataframe
    Valid only for one to two selection criteria

    Args:
        df (Pandas.Dataframe)
        sel_criteria (list): selection criteria
        data (optional): if source_data must be override


Latex accuracy tables for paper.

    BEWARE: Selection is hardcoded

    Args:
        df (pandas.DataFrame) : summary statistics df
        settings (ExperimentSettings): custom class to hold hyperparameters


Reproduce stats and plots used for SuperNNova paper.
    BEWARE: Selection is hardcoded

    Args:
        settings (ExperimentSettings): custom class to hold hyperparameters


Stats quoted in paper which are not in the latex tables and plots

    Args:
        df (pandas.DataFrame) : summary statistics df
        settings (ExperimentSettings): custom class to hold hyperparameters
        plots (Boolean optional): make pltos or only printout stats
        debug (Boolean optional): only print tasks
    Returns:
        printout: stats as organized in paper
        figures (png) : figures for paper at settings.dump_dir/figures/
        lightcurves (png): lightcurves used on paper at settings.dump_dir/lightcurves/modelname.*png


Bayesian RNNs: BBB and Variational


Find nvcc and the CUDA installation


    Poor mans deviceQuery. Returns CUDA_VERSION information and
    CUDA device information in JSON format


inject deep into distutils to customize gcc/nvcc dispatch


Return cuda device information and nvcc/cuda setup


Download cub archive from cub_url and store it in cub_archive_name


Compute the SHA1 hash of filename


Downloads and installs cub into mb_inc_path


    Emit a list of architecture flags for each CUDA device found
    ['--gpu-architecture=sm_30', '--gpu-architecture=sm_52']


Create an extension that builds the custom tensorflow ops


    Raise any errors associated with the validator.

    Parameters
    ----------
    validator : :class:`cerberus.Validator`
        Validator

    Raises
    ------
    ValueError
        Raised if errors existed on `validator`.
        Message describing each error and information
        associated with the configuration option
        causing the error.


String of the document/schema path. `cfg["foo"]["bar"]`


Dictionary Leaf of the schema/document given the path


            Dummy rule so that '__description__' keys
            can be placed in the schema

            The rule's arguments are validated against this schema:
            {'type': 'string'}


    Produces a SolverConfiguration object, inherited from
    a simple python dict, and containing the options required
    to configure the RIME Solver.

    Keyword arguments
    -----------------
    Any keyword arguments are inserted into the
    returned dict.

    Returns
    -------
    A SolverConfiguration object.


    rime_solver(slvr_cfg)

    Returns a solver suitable for solving the RIME.

    Parameters
    ----------
    slvr_cfg : RimeSolverConfiguration
            Solver Configuration.

    Returns
    -------
    A solver


    Returns a dictionary mapping source types
    to number of sources. If the number of sources
    for the source type is supplied in the kwargs
    these will be placed in the dictionary.

    e.g. if we have 'point', 'gaussian' and 'sersic'
    source types, then

    default_sources(point=10, gaussian=20)

    will return an OrderedDict {'point': 10, 'gaussian': 20, 'sersic': 0}


    Converts a source type to number of sources mapping into
    a source numbering variable to number of sources mapping.

    If, for example, we have 'point', 'gaussian' and 'sersic'
    source types, then passing the following dict as an argument

    sources_to_nr_vars({'point':10, 'gaussian': 20})

    will return an OrderedDict

    {'npsrc': 10, 'ngsrc': 20, 'nssrc': 0 }


    Given a range of source numbers, as well as a dictionary
    containing the numbers of each source, returns a dictionary
    containing tuples of the start and end index
    for each source variable type.


    Given a range of source numbers, as well as a dictionary
    containing the numbers of each source, returns a dictionary
    containing slices for each source variable type.


    Print the versions of software relied upon by montblanc.
    Inspired by numexpr testing suite.


Generate a MeqTrees compliant beam cube


Supply point source lm coordinates to montblanc


Supply point source stokes parameters to montblanc


Supply UVW antenna coordinates to montblanc


Return a lm coordinate array to montblanc


Return a stokes parameter array to montblanc


Return a reference frequency array to montblanc


Returns a dictionary mapping strings to concrete types


        Returns a dictionary suitable for templating strings with
        properties and dimensions related to this Solver object.

        Used in templated GPU kernels.


    Computes parallactic angles per timestep for the given
    reference antenna position and field centre.

    Arguments:
        times: ndarray
            Array of unique times with shape (ntime,),
            obtained from TIME column of MS table
        antenna_positions: ndarray of shape (na, 3)
            Antenna positions, obtained from POSITION
            column of MS ANTENNA sub-table
        field_centre : ndarray of shape (2,)
            Field centre, should be obtained from MS PHASE_DIR
        offsets: ndarray of shape (ntime, na, 2) or None
            Containing time-variable offsets in ra, dec from
            pointing centre per antenna. If None is passed offsets
            of zero are assumed.

    Returns:
        An array of parallactic angles per antenna per time-step


    Parses a string, containing assign statements
    into a dictionary.

    .. code-block:: python

        h5 = katdal.open('123456789.h5')
        kwargs = parse_python_assigns("spw=3; scans=[1,2];"
                                      "targets='bpcal,radec';"
                                      "channels=slice(0,2048)")
        h5.select(**kwargs)

    Parameters
    ----------
    assign_str: str
        Assignment string. Should only contain assignment statements
        assigning python literals or builtin function calls, to variable names.
        Multiple assignment statements should be separated by semi-colons.

    Returns
    -------
    dict
        Dictionary { name: value } containing
        assignment results.


    Compute the number of baselines for the
    given number of antenna. Can specify whether
    auto-correlations should be taken into
    account


    Compute the number of antenna for the
    given number of baselines. Can specify whether
    auto-correlations should be taken into
    account


    Returns the number of blocks required, given
    N, the total number of threads, and threads_per_block


Returns a human readable string, given the number of bytes


    Returns a random array of the same shape and type as the
    supplied array argument, or the supplied shape and dtype


Return a flatten version of the nested argument


    Return the number of bytes required by an array

    Arguments
    ---------------
    ary : dict
        Dictionary representation of an array
    template : dict
        A dictionary of key-values, used to replace any
        string values in the array with concrete integral
        values

    Returns
    -----------
    The number of bytes required to represent
    the array.


    Return the number of bytes required by
    a dictionary of arrays.

    Arguments
    ---------------
    arrays : list
        A list of dictionaries defining the arrays
    template : dict
        A dictionary of key-values, used to replace any
        string values in the arrays with concrete integral
        values

    Returns
    -----------
    The number of bytes required to represent
    all the arrays.


    Returns the number of timesteps possible, given the registered arrays
    and a memory budget defined by bytes_available

    Arguments
    ----------------
    bytes_available : int
        The memory budget, or available number of bytes
        for solving the problem.
    arrays : list
        List of dictionaries describing the arrays
    template : dict
        Dictionary containing key-values that will be used
        to replace any string representations of dimensions
        and types. slvr.template_dict() will return something
        suitable.
    dim_ord : list
        list of dimension string names that the problem should be
        subdivided by. e.g. ['ntime', 'nbl', 'nchan'].
        Multple dimensions can be reduced simultaneously using
        the following syntax 'nbl&na'. This is mostly useful for
        the baseline-antenna equivalence.
    nsolvers : int
        Number of solvers to budget for. Defaults to one.

    Returns
    ----------
    A tuple (boolean, dict). The boolean is True if the problem
    can fit within the supplied budget, False otherwise.
    THe dictionary contains the reduced dimensions as key and
    the reduced size as value.
    e.g. (True, { 'time' : 1, 'nbl' : 1 })

    For a dim_ord = ['ntime', 'nbl', 'nchan'], this method will try and fit
    a ntime x nbl x nchan problem into the available number of bytes.
    If this is not possible, it will first set ntime=1, and then try fit an
    1 x nbl x nchan problem into the budget, then a 1 x 1 x nchan
    problem.

    One can specify reductions for specific dimensions.
    For e.g. ['ntime=20', 'nbl=1&na=2', 'nchan=50%']

    will reduce ntime to 20, but no lower. nbl=1&na=2 sets
    both nbl and na to 1 and 2 in the same operation respectively.
    nchan=50\% will continuously halve the nchan dimension
    until it reaches a value of 1.


    Substitutes string dtype parameters
    using a a property dictionary

    Parameters
    ----------
        sdtype :
            string defining the dtype. e.g. 'ft'
        template:
            Dictionary contain actual types, {'ft' : np.float32' }

    Returns
        sdtype if it isn't a string
        template[sdtype] otherwise


    Substitutes string values in the supplied shape parameter
    with integer variables stored in a dictionary

    Parameters
    ----------
    sshape : tuple/string composed of integers and strings.
        The strings should related to integral properties
        registered with this Solver object
    variables : dictionary
        Keys with associated integer values. Used to replace
        string values within the tuple
    ignore : list
        A list of tuple strings to ignore

    >>> print self.shape_from_str_tuple((4,'na','ntime'),ignore=['ntime'])
    (4, 3)


 Return a function defining the conversion process between two NumPy
    arrays of different shapes


    Redistribute threads from the Z dimension towards the X dimension.
    Also clamp number of threads to the problem dimension size,
    if necessary


Register the default dimensions for a RIME solver


numba implementation of antenna_uvw


Raises informative exception for an invalid decomposition


Raises an informative error for missing antenna


    Computes per-antenna UVW coordinates from baseline ``uvw``,
    ``antenna1`` and ``antenna2`` coordinates logically grouped
    into baseline chunks.

    The example below illustrates two baseline chunks
    of size 6 and 5, respectively.

    .. code-block:: python

        uvw = ...
        ant1 = np.array([0, 0, 0, 1, 1, 2, 0, 0, 0, 1, 1], dtype=np.int32)
        ant2 = np.array([1, 2, 3, 2, 3, 3, 1, 2, 3, 1, 2], dtype=np.int32)
        chunks = np.array([6, 5], dtype=np.int32)

        ant_uv = antenna_uvw(uvw, ant1, ant2, chunks, nr_of_antenna=4)

    The first antenna of the first baseline of a chunk is chosen as the origin
    of the antenna coordinate system, while the second antenna is set to the
    negative of the baseline UVW coordinate. Subsequent antenna UVW coordinates
    are iteratively derived from the first two coordinates. Thus,
    the baseline indices need not be properly ordered (within the chunk).

    If it is not possible to derive coordinates for an antenna,
    it's coordinate will be set to nan.

    Parameters
    ----------
    uvw : np.ndarray
        Baseline UVW coordinates of shape (row, 3)
    antenna1 : np.ndarray
        Baseline first antenna of shape (row,)
    antenna2 : np.ndarray
        Baseline second antenna of shape (row,)
    chunks : np.ndarray
        Number of baselines per unique timestep with shape (chunks,)
        :code:`np.sum(chunks) == row` should hold.
    nr_of_antenna : int
        Total number of antenna in the solution.
    check_missing (optional) : bool
        If ``True`` raises an exception if it was not possible
        to compute UVW coordinates for all antenna (i.e. some were nan).
        Defaults to ``False``.
    check_decomposition (optional) : bool
        If ``True``, checks that the antenna decomposition accurately
        reproduces the coordinates in ``uvw``, or that
        :code:`ant_uvw[c,ant1,:] - ant_uvw[c,ant2,:] == uvw[s:e,:]`
        where ``s`` and ``e`` are the start and end rows
        of chunk ``c`` respectively. Defaults to ``False``.
    max_err (optional) : integer
        Maximum numbers of errors when checking for missing antenna
        or innacurate decompositions. Defaults to ``100``.

    Returns
    -------
    np.ndarray
        Antenna UVW coordinates of shape (chunks, nr_of_antenna, 3)


        Iteration arguments that describe the tile sizes
        over which iteration is performed. In the following example,
        iteration is occuring in tiles of 100 Timesteps, 64 Channels
        and 50 Point Sources.

        .. code-block:: python

            context.iter_args == [("ntime", 100),
                    ("nchan", 64), ("npsrc", 50)]


        Get help associated with this context

        Args
        -----
        display_cube: bool
            Add hypercube description to the output
        Returns
        -------
            str
                A help string associated with this context


        Get help associated with this context

        Returns
        -------
            str
                A help string associated with this context


    Given a list of arrays to feed in fed_arrays, return
    a list of associated queue types, obtained from tuples
    in the data_sources dictionary


    Arguments
        name: string
            Name of the queue
        queue_size: integer
            Size of the queue
        fed_arrays: list
            array names that will be fed by this queue
        data_sources: dict
            (lambda/method, dtype) tuples, keyed on array names


        Produces a numpy array of integers which encode
        the supplied cube dimensions.


Produce a list of dictionaries for each dimension in this transcoder


Load the tensorflow library


Compute base antenna pairs


Default antenna1 values


Default antenna2 values


    Returns [[1, 0], tiled up to other dimensions
             [0, 1]]


    Returns [[1, 0], tiled up to other dimensions
             [0, 0]]


Wrap the tensorflow Session.run method


Aggregate run metadata for each run


Implementation of staging_area feeding


Call the tensorflow compute


    Create a DefaultsSourceProvider object. This provides default
    data sources for each array defined on the hypercube. The data sources
    may either by obtained from the arrays 'default' data source
    or the 'test' data source.


        Override the sources method to also handle lambdas that look like
        lambda s, c: ..., as defined in the config module


Constructs a tensorflow expression for computing the RIME


        Compute the jones terms for each antenna.

        lm, stokes and alpha are the source variables.


Accumulate visiblities for point source batch


Accumulate coherencies for gaussian source batch


Accumulate coherencies for sersic source batch


Get data from the data source, checking the return values


Supply data to the data sink


    Given a list of source_providers, apply the list of
    suggested dimension updates given in provider.updated_dimensions()
    to the supplied hypercube.

    Dimension global_sizes are always updated with the supplied sizes and
    lower_extent is always set to 0. upper_extent is set to any reductions
    (current upper_extents) existing in budget_dims, otherwise it is set
    to global_size.


Sets up the hypercube given a solver configuration


    Partition data sources into

    1. Dictionary of data sources associated with radio sources.
    2. List of data sources to feed multiple times.
    3. List of data sources to feed once.


        The array schema of the array associated
        with this data source. For instance if `model_vis` is
        registered on a hypercube as follows:

        .. code-block:: python

            # Register model_vis array_schema on hypercube
            cube.register_array("model_vis",
                ("ntime", "nbl", "nchan", "ncorr"),
                np.complex128)

            ...
            # Create a source context for model_vis data source
            context = SourceContext("model_vis", ...)
            ...
            # Obtain the array schema
            context.array_schema == ("ntime", "nbl", "nchan", "ncorr")


        The dictionary of inputs used to produce
        :py:obj:`~SinkContext.data`. For example, if one
        wished to find the antenna pair used to produce a
        particular model visibility, one could do the following:

        .. code-block:: python

            def model_vis(self, context):
                ant1 = context.input["antenna1"]
                ant2 = context.input["antenna2"]
                model_vis = context.data


        Get help associated with this context

        Parameters
        ----------
        display_cube: bool
            Add hypercube description to the output
        Returns
        -------
            str
                A help string associated with this context


model visibility data sink


    Returns a dictionary of sink methods found on this object,
    keyed on method name. Sink methods are identified by
    (self, context) arguments on this object. For example:

    def f(self, context):
        ...

    is a sink method, but

    def f(self, ctx):
        ...

    is not.


        Returns a dictionary of sink methods found on this object,
        keyed on method name. Sink methods are identified by
        (self, context) arguments on this object. For example:

        def f(self, context):
            ...

        is a sink method, but

        def f(self, ctx):
            ...

        is not.


Compute the complex phase from lm, uvw and frequency expressions


Pin operation to device


Compute antenna jones term using numpy


    Decorator for caching data source return values

    Create a key index for the proxied array in the context.
    Iterate over the array shape descriptor e.g. (ntime, nbl, 3)
    returning tuples containing the lower and upper extents
    of string dimensions. Takes (0, d) in the case of an integer
    dimensions.


Decorator returning a method that proxies a data source.


Perform any logic on solution start


Perform any logic on solution stop


Reference frequency data source


Per-antenna UVW coordinate data source


antenna1 data source


antenna2 data source


parallactic angle data source


Observed visibility data source


Flag data source


Weight data source


    Returns a dictionary of source methods found on this object,
    keyed on method name. Source methods are identified.by argspec,
    a list of argument specifiers. So for e.g. an argpsec of
    :code:`[['self', 'context'], ['s', 'c']]` would match
    methods looking like:

    .. code-block:: python

        def f(self, context):
        ...

    .. code-block:: python

        def f(s, c):
        ...

    is but not

    .. code-block:: python

        def f(self, ctx):
        ...


        Returns a dictionary of source methods found on this object,
        keyed on method name. Source methods are identified by
        (self, context) arguments on this object. For example:

        .. code-block:: python

            def f(self, context):
                    ...

        is a source method, but

        .. code-block:: python

            def f(self, ctx):
                ...

            is not.


    Returns a dictionary of beam filename pairs,
    keyed on correlation,from the cartesian product
    of correlations and real, imaginary pairs

    Given 'beam_$(corr)_$(reim).fits' returns:
    {
      'xx' : ('beam_xx_re.fits', 'beam_xx_im.fits'),
      'xy' : ('beam_xy_re.fits', 'beam_xy_im.fits'),
      ...
      'yy' : ('beam_yy_re.fits', 'beam_yy_im.fits'),
    }

    Given 'beam_$(CORR)_$(REIM).fits' returns:
    {
      'xx' : ('beam_XX_RE.fits', 'beam_XX_IM.fits'),
      'xy' : ('beam_XY_RE.fits', 'beam_XY_IM.fits'),
      ...
      'yy' : ('beam_YY_RE.fits', 'beam_YY_IM.fits'),
    }


    Given a {correlation: filename} mapping for filenames
    returns a {correlation: file handle} mapping


Create a FitsAxes object


        Initialise the object by generating appropriate filenames,
        opening associated file handles and inspecting the FITS axes
        of these files.


ebeam cube data source


    Caches constant arrays associated with an array name.

    The intent of this decorator is to avoid the cost
    of recreating and storing many arrays of constant data,
    especially data created by np.zeros or np.ones.
    Instead, a single array of the first given shape is created
    and any further requests for constant data of the same
    (or smaller) shape are served from the cache.

    Requests for larger shapes or different types are regarded
    as a cache miss and will result in replacement of the
    existing cache value.


    Caches chunks of default data.

    This decorator caches generated default data so as to
    avoid recomputing it on a subsequent queries to the
    provider.


        Override to perform decoder specific cleanup

        :returns: None


        Returns the range *vmin*, *vmax*, possibly limited to the
        domain supported by this scale.

        *minpos* should be the minimum positive value in the data.
         This is used by log scales to determine a minimum value.


Limit the domain to positive values.


    Register a new kind of scale.

    *scale_class* must be a subclass of :class:`ScaleBase`.


        Set the draggable state -- if state is

          * None : toggle the current state

          * True : turn draggable on

          * False : turn draggable off

        If draggable is on, you can drag the annotation on the canvas with
        the mouse.  The DraggableAnnotation helper instance is returned if
        draggable is on.


NOTE: This cannot be called until after this has been added
                 to an Axes, otherwise unit conversion will fail. This
                 makes it very important to call the accessor method and
                 not directly access the transformation member variable.


(classmethod) Returns an arc :class:`Spine`.


(staticmethod) Returns a circular :class:`Spine`.


Copy a docstring from another source function (if present)


release the lock


Return True if event should be ignored.

        This method (or a version of it) should be called at the beginning
        of any event callback.


Connect the major canvas events to methods.


Clean up an event

        Use prev event if there is no xdata
        Limit the xdata and ydata to the axes limits
        Set the prev event


Return (xmin, xmax, ymin, ymax).


        Sets the PolygonCollection transform to go
        from arrow width units to pixels.


Add an input to a path and return its tip and label locations.


        A path is not simply revertable by path[::-1] since the code
        specifies an action to take from the **previous** point.


        Adjust the axes and return a list of information about the Sankey
        subdiagram(s).

        Return value is a list of subdiagrams represented with the following
        fields:

          ===============   ===================================================
          Field             Description
          ===============   ===================================================
          *patch*           Sankey outline (an instance of
                            :class:`~maplotlib.patches.PathPatch`)
          *flows*           values of the flows (positive for input, negative
                            for output)
          *angles*          list of angles of the arrows [deg/90]
                            For example, if the diagram has not been rotated,
                            an input to the top side will have an angle of 3
                            (DOWN), and an output from the top side will have
                            an angle of 1 (UP).  If a flow has been skipped
                            (because its magnitude is less than *tolerance*),
                            then its angle will be *None*.
          *tips*            array in which each row is an [x, y] pair
                            indicating the positions of the tips (or "dips") of
                            the flow paths
                            If the magnitude of a flow is less the *tolerance*
                            for the instance of :class:`Sankey`, the flow is
                            skipped and its tip will be at the center of the
                            diagram.
          *text*            :class:`~matplotlib.text.Text` instance for the
                            label of the diagram
          *texts*           list of :class:`~matplotlib.text.Text` instances
                            for the labels of flows
          ===============   ===================================================

        .. seealso::

            :meth:`add`


    Set interactive mode to boolean b.

    If b is True, then draw after every plotting command, e.g., after xlabel


Add any :class:`~matplotlib.artist.Artist` to the container box


For artists in an axes, if the xaxis has units support,
        convert *x* using xaxis unit type


For artists in an axes, if the yaxis has units support,
        convert *y* using yaxis unit type


        If the artist is 'stale' and needs to be re-drawn for the output to
        match the internal state of the artist.


        Returns *True* if :class:`Artist` has a transform explicitly
        set.


Set the clip properly for the gc


        `x` and `y` sticky edge lists.

        When performing autoscaling, if a data limit coincides with a value in
        the corresponding sticky_edges list, then no margin will be added--the
        view limit "sticks" to the edge. A typical usecase is histograms,
        where one usually expects no margin on the bottom edge (0) of the
        histogram.

        This attribute cannot be assigned to; however, the `x` and `y` lists
        can be modified in place as needed.

        Examples
        --------

        >>> artist.sticky_edges.x[:] = (xmin, xmax)
        >>> artist.sticky_edges.y[:] = (ymin, ymax)


        Returns a frozen copy of this transform node.  The frozen copy
        will not update when its children change.  Useful for storing
        a previously known state of a transform where
        ``copy.deepcopy()`` might normally be used.


        (property) :attr:`x0` is the first of the pair of *x* coordinates that
        define the bounding box. :attr:`x0` is not guaranteed to be less than
        :attr:`x1`.  If you require that, use :attr:`xmin`.


        (property) :attr:`y0` is the first of the pair of *y* coordinates that
        define the bounding box. :attr:`y0` is not guaranteed to be less than
        :attr:`y1`.  If you require that, use :attr:`ymin`.


        (property) :attr:`x1` is the second of the pair of *x* coordinates that
        define the bounding box. :attr:`x1` is not guaranteed to be greater
        than :attr:`x0`.  If you require that, use :attr:`xmax`.


        (property) :attr:`y1` is the second of the pair of *y* coordinates that
        define the bounding box. :attr:`y1` is not guaranteed to be greater
        than :attr:`y0`.  If you require that, use :attr:`ymax`.


        (property) :attr:`p0` is the first pair of (*x*, *y*) coordinates that
        define the bounding box.  It is not guaranteed to be the bottom-left
        corner.  For that, use :attr:`min`.


        (property) :attr:`p1` is the second pair of (*x*, *y*) coordinates that
        define the bounding box.  It is not guaranteed to be the top-right
        corner.  For that, use :attr:`max`.


        (property) :attr:`intervalx` is the pair of *x* coordinates that define
        the bounding box. It is not guaranteed to be sorted from left to right.


        (property) :attr:`intervaly` is the pair of *y* coordinates that define
        the bounding box.  It is not guaranteed to be sorted from bottom to
        top.


Returns whether `x` is in the closed (:attr:`x0`, :attr:`x1`) interval.


Returns whether `y` is in the closed (:attr:`y0`, :attr:`y1`) interval.


Returns whether `x, y` is in the bounding box or on its edge.


Returns whether this bounding box overlaps with the other bounding box.


Returns whether `x` is in the open (:attr:`x0`, :attr:`x1`) interval.


Returns whether `y` is in the open (:attr:`y0`, :attr:`y1`) interval.


Returns whether `x, y` is in the bounding box, but not on its edge.


        Returns whether this bounding box overlaps with the other bounding box,
        not including the edges.


        Return a copy of the :class:`Bbox`, shrunk so that it is as
        large as it can be while having the desired aspect ratio,
        *box_aspect*.  If the box coordinates are relative---that
        is, fractions of a larger box such as a figure---then the
        physical aspect ratio of that figure is specified with
        *fig_aspect*, so that *box_aspect* can also be given as a
        ratio of the absolute dimensions, not the relative dimensions.


        Count the number of vertices contained in the :class:`Bbox`.
        Any vertices with a non-finite x or y value are ignored.

        *vertices* is a Nx2 Numpy array.


        Count the number of bounding boxes that overlap this one.

        bboxes is a sequence of :class:`BboxBase` objects


        Return a new :class:`Bbox` which is this :class:`Bbox`
        expanded around its center by the given factors *sw* and
        *sh*.


        Return a new bounding box that bounds a rotated version of
        this bounding box by the given radians.  The new bounding box
        is still aligned with the axes, of course.


Return a :class:`Bbox` that contains all of the given bboxes.


        Return the intersection of the two bboxes or None
        if they do not intersect.


        (staticmethod) Create a new :class:`Bbox` from *x0*, *y0*,
        *width* and *height*.

        *width* and *height* may be negative.


        Set whether the existing bounds of the box should be ignored
        by subsequent calls to :meth:`update_from_data_xy`.

        *value*:

           - When True, subsequent calls to :meth:`update_from_data_xy`
             will ignore the existing bounds of the :class:`Bbox`.

           - When False, subsequent calls to :meth:`update_from_data_xy`
             will include the existing bounds of the :class:`Bbox`.


float or None: The value used for the locked x0.


float or None: The value used for the locked y0.


float or None: The value used for the locked x1.


float or None: The value used for the locked y1.


        Returns an iterator breaking down this transform stack from left to
        right recursively. If self == ((A, N), A) then the result will be an
        iterator which yields I : ((A, N), A), followed by A : (N, A),
        followed by (A, N) : (A), but not ((A, N), A) : I.

        This is equivalent to flattening the stack then yielding
        ``flat_stack[:i], flat_stack[i:]`` where i=0..(n-1).


        Returns the number of transforms which have been chained
        together to form this Transform instance.

        .. note::

            For the special case of a Composite transform, the maximum depth
            of the two is returned.


        Return whether the given transform is a sub-tree of this transform.

        This routine uses transform equality to identify sub-trees, therefore
        in many situations it is object id which will be used.

        For the case where the given transform represents the whole
        of this transform, returns True.


        Performs only the affine part of this transformation on the
        given array of values.

        ``transform(values)`` is always equivalent to
        ``transform_affine(transform_non_affine(values))``.

        In non-affine transformations, this is generally a no-op.  In
        affine transformations, this is equivalent to
        ``transform(values)``.

        Accepts a numpy array of shape (N x :attr:`input_dims`) and
        returns a numpy array of shape (N x :attr:`output_dims`).

        Alternatively, accepts a numpy array of length :attr:`input_dims`
        and returns a numpy array of length :attr:`output_dims`.


        Performs only the non-affine part of the transformation.

        ``transform(values)`` is always equivalent to
        ``transform_affine(transform_non_affine(values))``.

        In non-affine transformations, this is generally equivalent to
        ``transform(values)``.  In affine transformations, this is
        always a no-op.

        Accepts a numpy array of shape (N x :attr:`input_dims`) and
        returns a numpy array of shape (N x :attr:`output_dims`).

        Alternatively, accepts a numpy array of length :attr:`input_dims`
        and returns a numpy array of length :attr:`output_dims`.


        Transform the given bounding box.

        Note, for smarter transforms including caching (a common
        requirement for matplotlib figures), see :class:`TransformedBbox`.


        Returns a transformed path.

        *path*: a :class:`~matplotlib.path.Path` instance.

        In some cases, this transform may insert curves into the path
        that began as line segments.


        Returns a path, transformed only by the affine part of
        this transform.

        *path*: a :class:`~matplotlib.path.Path` instance.

        ``transform_path(path)`` is equivalent to
        ``transform_path_affine(transform_path_non_affine(values))``.


        Return the corresponding inverse transformation.

        The return value of this method should be treated as
        temporary.  An update to *self* does not cause a corresponding
        update to its inverted copy.

        ``x === self.inverted().transform(self.transform(x))``


        (staticmethod) Create a new Affine2D instance from the given
        values::

          a c e
          b d f
          0 0 1

        .


        Add a rotation (in radians) around the point (x, y) in place.

        Returns *self*, so this method can easily be chained with more
        calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
        and :meth:`scale`.


        Add a rotation (in degrees) around the point (x, y) in place.

        Returns *self*, so this method can easily be chained with more
        calls to :meth:`rotate`, :meth:`rotate_deg`, :meth:`translate`
        and :meth:`scale`.


    Create a new composite transform that is the result of applying
    transform a then transform b.

    Shortcut versions of the blended transform are provided for the
    case where both child transforms are affine, or one or the other
    is the identity transform.

    Composite transforms may also be created using the '+' operator,
    e.g.::

      c = a + b


    Check, excluding endpoints, whether an interval includes a given value.

    Parameters
    ----------
    interval : sequence of scalar
        A 2-length sequence, endpoints that define the interval.
    val : scalar
        Value to check is within interval.

    Returns
    -------
    bool
        Returns true if given val is within the interval.


Shrink font size until text fits.


        Called when this tool gets used

        This method is called by
        `matplotlib.backend_managers.ToolManager.trigger_tool`

        Parameters
        ----------
        event: `Event`
            The Canvas event that caused this tool to be called
        sender: object
            Object that requested the tool to be triggered
        data: object
            Extra data


Calls `enable` or `disable` based on `toggled` value


        Enable the toggle tool

        `trigger` calls this method when `toggled` is False


        Disable the toggle tool

        `trigger` call this method when `toggled` is True.

        This can happen in different circumstances

        * Click on the toolbar tool button
        * Call to `matplotlib.backend_managers.ToolManager.trigger_tool`
        * Another `ToolToggleBase` derived tool is triggered
          (from the same `ToolManager`)


        Draw rubberband

        This method must get implemented per backend


        Remove rubberband

        This method should get implemented per backend


Reset the axes stack


Push the current view limits and position onto their respective stacks


        Return the original and modified positions for the specified axes

        Parameters
        ----------
        ax : (matplotlib.axes.AxesSubplot)
        The axes to get the positions for

        Returns
        -------
        limits : (tuple)
        A tuple of the original and modified positions


        Make sure that self.home_views has an entry for all axes present in the
        figure


the drag callback in zoom mode


    Add multiple tools to the container.

    Parameters
    ----------
    container: Container
        `backend_bases.ToolContainerBase` object that will get the tools added
    tools : list, optional
        List in the form
        [[group1, [tool1, tool2 ...]], [group2, [...]]]
        Where the tools given by tool1, and tool2 will display in group1.
        See `add_tool` for details.


        Grab the image information from the figure and save as a movie frame.

        All keyword arguments in savefig_kwargs are passed on to the `savefig`
        command that saves the figure.


        Format (png, jpeg, etc.) to use for saving the frames, which can be
        decided by the individual subclasses.


        Handler for getting events. By default, gets the next frame in the
        sequence and hands the data off to be drawn.


Convert axis data interval to datetime objects.


Converts the view interval to datetime objects.


        Return how many days a unit of the locator is; used for
        intelligent autoscaling.


Return the number of units for each tick.


        Derived should override this method. The arguments are the same
        as :meth:`matplotlib.backend_bases.RendererBase.draw_path`
        except the first argument is a renderer.


create and return a SuplotSpec instance.


    Return a kern pairs dictionary; keys are (*char1*, *char2*) tuples and
    values are the kern pair value.  For example, a kern pairs line like
    ``KPX A y -50``

    will be represented as::

      d[ ('A', 'y') ] = -50


add one or more events at the specified positions


        switch the orientation of the event line, either from vertical to
        horizontal or vice versus


        Returns *True* if the given point is inside the path
        (transformed with its transform attribute).


            The transmute method is the very core of the ArrowStyle
            class and must be overridden in the subclasses. It receives
            the path object along which the arrow will be drawn, and
            the mutation_size, with which the arrow head etc.
            will be scaled. The linewidth may be used to adjust
            the path so that it does not pass beyond the given
            points. It returns a tuple of a Path instance and a
            boolean. The boolean value indicate whether the path can
            be filled or not. The return value can also be a list of paths
            and list of booleans of a same length.


Defaults to removing last label, but any index can be supplied


Return (lowers,uppers) for filled contours.


    Register a backend for saving to a given file format.

    Parameters
    ----------
    format : str
        File extension

    backend : module string or canvas class
        Backend for handling file output

    description : str, optional
        Description of the file type.  Defaults to an empty string


Create a new figure manager instance.


        Open a grouping element with label *s*. If *gid* is given, use
        *gid* as the id of the group. Is only currently used by
        :mod:`~matplotlib.backends.backend_svg`.


        Close a grouping element with label *s*
        Is only currently used by :mod:`~matplotlib.backends.backend_svg`


        Draws a marker at each of the vertices in path.  This includes
        all vertices, including control points on curves.  To avoid
        that behavior, those vertices should be removed before calling
        this function.

        This provides a fallback implementation of draw_markers that
        makes multiple calls to :meth:`draw_path`.  Some backends may
        want to override this method in order to draw the marker only
        once and reuse it multiple times.

        Parameters
        ----------
        gc : `GraphicsContextBase`
            The graphics context

        marker_trans : `matplotlib.transforms.Transform`
            An affine transform applied to the marker.

        trans : `matplotlib.transforms.Transform`
            An affine transform applied to the path.


        Draw an RGBA image.

        Parameters
        ----------
        gc : `GraphicsContextBase`
            a graphics context with clipping information.

        x : scalar
            the distance in physical units (i.e., dots or pixels) from the left
            hand side of the canvas.

        y : scalar
            the distance in physical units (i.e., dots or pixels) from the
            bottom side of the canvas.

        im : array_like, shape=(N, M, 4), dtype=np.uint8
            An array of RGBA pixels.

        transform : `matplotlib.transforms.Affine2DBase`
            If and only if the concrete backend is written such that
            :meth:`option_scale_image` returns ``True``, an affine
            transformation *may* be passed to :meth:`draw_image`. It takes the
            form of a :class:`~matplotlib.transforms.Affine2DBase` instance.
            The translation vector of the transformation is given in physical
            units (i.e., dots or pixels). Note that the transformation does not
            override `x` and `y`, and has to be applied *before* translating
            the result by `x` and `y` (this can be accomplished by adding `x`
            and `y` to the translation vector defined by `transform`).


        override this method for renderers that do not necessarily always
        want to rescale and composite raster images. (like SVG, PDF, or PS)


        override this method for renderers that support arbitrary affine
        transformations in :meth:`draw_image` (most vector backends).


        Draw the text instance

        Parameters
        ----------
        gc : `GraphicsContextBase`
            the graphics context

        x : scalar
            the x location of the text in display coords

        y : scalar
            the y location of the text baseline in display coords

        s : str
            the text string

        prop : `matplotlib.font_manager.FontProperties`
            font properties

        angle : scalar
            the rotation angle in degrees

        mtext : `matplotlib.text.Text`
            the original text object to be rendered

        Notes
        -----
        **backend implementers note**

        When you are trying to determine if you have gotten your bounding box
        right (which is what enables the text layout/alignment to work
        properly), it helps to change the line in text.py::

            if 0: bbox_artist(self, renderer)

        to if 1, and then the actual bounding box will be plotted along with
        your text.


        Return true if y small numbers are top for renderer Is used
        for drawing text (:mod:`matplotlib.text`) and images
        (:mod:`matplotlib.image`) only


        Convert points to display units

        You need to override this function (unless your backend
        doesn't have a dpi, e.g., postscript or svg).  Some imaging
        systems assume some value for pixels per inch::

            points to pixels = points * pixels_per_inch/72.0 * dpi/72.0

        Parameters
        ----------
        points : scalar or array_like
            a float or a numpy array of float

        Returns
        -------
        Points converted to pixels


        Used in MixedModeRenderer. Switch back to the vector renderer
        and draw the contents of the raster renderer as an image on
        the vector renderer.


        Used in AggRenderer. Switch to a temporary renderer for image
        filtering effects.


        Used in AggRenderer. Switch back to the original renderer.
        The contents of the temporary renderer is processed with the
        *filter_func* and is drawn on the original renderer as an
        image.


Copy properties from gc to self


        Restore the graphics context from the stack - needed only
        for backends that save graphics contexts on a stack


        Returns whether the renderer is in the process of saving
        to a file, rather than rendering for an on-screen buffer.


        Set the child axes which are currently grabbing the mouse events.
        Usually called by the widgets themselves.
        It is an error to call this if the mouse is already grabbed by
        another axes.


        Release the mouse grab held by the axes, ax.
        Usually called by the widgets.
        It is ok to call this even if you ax doesn't have the mouse
        grab currently.


:meth:`draw` only if idle; defaults to draw but backends can override


Flush the GUI events for the figure.

        Interactive backends need to reimplement this method.


Start a blocking event loop.

        Such an event loop is used by interactive functions, such as `ginput`
        and `waitforbuttonpress`, to wait for events.

        The event loop blocks until a callback function triggers
        `stop_event_loop`, or *timeout* is reached.

        If *timeout* is negative, never timeout.

        Only interactive backends need to reimplement this method and it relies
        on `flush_events` being properly implemented.

        Interactive backends should implement this in a more native way.


Stop the current blocking event loop.

        Interactive backends need to reimplement this to match
        `start_event_loop`


move back up the view lim stack


Draw a rectangle rubberband to indicate zoom limits.

        Note that it is not guaranteed that ``x0 <= x1`` and ``y0 <= y1``.


Move forward in the view lim stack.


Restore the original view.


Push the current view limits and position onto the stack.


        Captures the 'tool_trigger_[name]'

        This only gets used for toggled tools


        Trigger the tool

        Parameters
        ----------
        name : String
            Name (id) of the tool triggered from within the container


        Add a toolitem to the container

        This method must get implemented per backend

        The callback associated with the button click event,
        must be **EXACTLY** `self.trigger_tool(name)`

        Parameters
        ----------
        name : string
            Name of the tool to add, this gets used as the tool's ID and as the
            default label of the buttons
        group : String
            Name of the group that this tool belongs to
        position : Int
            Position of the tool within its group, if -1 it goes at the End
        image_file : String
            Filename of the image for the button or `None`
        description : String
            Description of the tool, used for the tooltips
        toggle : Bool
            * `True` : The button is a toggle (change the pressed/unpressed
              state between consecutive clicks)
            * `False` : The button is a normal button (returns to unpressed
              state after release)


        Toggle the toolitem without firing event

        Parameters
        ----------
        name : String
            Id of the tool to toggle
        toggled : bool
            Whether to set this tool as toggled or not.


        Remove a toolitem from the `ToolContainer`

        This method must get implemented per backend

        Called when `ToolManager` emits a `tool_removed_event`

        Parameters
        ----------
        name : string
            Name of the tool to remove


        convert obj using unit for the specified axis.  If obj is a sequence,
        return the converted sequence.  The output must be a sequence of
        scalars that can be used by the numpy array layer


        Returns a match score between *variant1* and *variant2*.

        An exact match returns 0.0, otherwise 1.0.


        Returns a match score between *stretch1* and *stretch2*.

        The result is the absolute value of the difference between the
        CSS numeric values of *stretch1* and *stretch2*, normalized
        between 0.0 and 1.0.


        Update the label position based on the sequence of bounding
        boxes of all the ticklabels


Move ticks and ticklabels (if present) to the top of the axes.


Move ticks and ticklabels (if present) to the bottom of the axes.


Move ticks and ticklabels (if present) to the right of the axes.


Move ticks and ticklabels (if present) to the left of the axes.


Canvas managed by FigureManager


        Connect event with string *s* to *func*.

        Parameters
        ----------
        s : String
            Name of the event

            The following events are recognized

            - 'tool_message_event'
            - 'tool_removed_event'
            - 'tool_added_event'

            For every tool added a new event is created

            - 'tool_trigger_TOOLNAME`
              Where TOOLNAME is the id of the tool.

        func : function
            Function to be called with signature
            def func(event)


        Disconnect callback id *cid*

        Example usage::

            cid = toolmanager.toolmanager_connect('tool_trigger_zoom',
                                                  on_press)
            #...later
            toolmanager.toolmanager_disconnect(cid)


Emit a `ToolManagerMessageEvent`


        Helper function to cope with `codes` being an
        ndarray or `None`


        Puts a TransformedPath instance at self._transformed_path;
        all invalidation of the transform is then handled by the
        TransformedPath instance.


        Return the :class:`~matplotlib.transforms.TransformedPath` instance
        of this line.


        Default "do nothing" implementation of the
        :meth:`process_selected` method.

        *ind* are the indices of the selected vertices.  *xs* and *ys*
        are the coordinates of the selected vertices.


When the line is picked, update the set of selected indicies.


    Return x times the hanning window of len(x).

    See Also
    --------
    :func:`window_none`
        :func:`window_none` is another window algorithm.


    No window function; simply return x.

    See Also
    --------
    :func:`window_hanning`
        :func:`window_hanning` is another window algorithm.


    Return x: no detrending.

    Parameters
    ----------
    x : any object
        An object containing the data

    axis : integer
        This parameter is ignored.
        It is included for compatibility with detrend_mean

    See Also
    --------
    :func:`denone`
        This function is the same as :func:`denone` except for the default
        *axis*, which has no effect.

    :func:`detrend_mean`

    :func:`detrend_linear`
        :func:`detrend_mean` and :func:`detrend_linear` are other detrend
        algorithms.

    :func:`detrend`
        :func:`detrend` is a wrapper around all the detrend algorithms.


    Return x minus best fit line; 'linear' detrending.

    Parameters
    ----------
    y : 0-D or 1-D array or sequence
        Array or sequence containing the data

    axis : integer
        The axis along which to take the mean.  See numpy.mean for a
        description of this argument.

    See Also
    --------
    :func:`delinear`
        This function is the same as :func:`delinear` except for the default
        *axis*.

    :func:`detrend_mean`

    :func:`detrend_none`
        :func:`detrend_mean` and :func:`detrend_none` are other detrend
        algorithms.

    :func:`detrend`
        :func:`detrend` is a wrapper around all the detrend algorithms.


r"""
    Compute the power spectral density.

    Call signature::

        psd(x, NFFT=256, Fs=2, detrend=mlab.detrend_none,
            window=mlab.window_hanning, noverlap=0, pad_to=None,
            sides='default', scale_by_freq=None)

    The power spectral density :math:`P_{xx}` by Welch's average
    periodogram method.  The vector *x* is divided into *NFFT* length
    segments.  Each segment is detrended by function *detrend* and
    windowed by function *window*.  *noverlap* gives the length of
    the overlap between segments.  The :math:`|\mathrm{fft}(i)|^2`
    of each segment :math:`i` are averaged to compute :math:`P_{xx}`.

    If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.

    Parameters
    ----------
    x : 1-D array or sequence
        Array or sequence containing the data

    %(Spectral)s

    %(PSD)s

    noverlap : integer
        The number of points of overlap between segments.
        The default value is 0 (no overlap).

    Returns
    -------
    Pxx : 1-D array
        The values for the power spectrum `P_{xx}` (real valued)

    freqs : 1-D array
        The frequencies corresponding to the elements in *Pxx*

    References
    ----------
    Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
    Wiley & Sons (1986)

    See Also
    --------
    :func:`specgram`
        :func:`specgram` differs in the default overlap; in not returning the
        mean of the segment periodograms; and in returning the times of the
        segments.

    :func:`magnitude_spectrum`
        :func:`magnitude_spectrum` returns the magnitude spectrum.

    :func:`csd`
        :func:`csd` returns the spectral density between two signals.


    Compute the cross-spectral density.

    Call signature::

        csd(x, y, NFFT=256, Fs=2, detrend=mlab.detrend_none,
            window=mlab.window_hanning, noverlap=0, pad_to=None,
            sides='default', scale_by_freq=None)

    The cross spectral density :math:`P_{xy}` by Welch's average
    periodogram method.  The vectors *x* and *y* are divided into
    *NFFT* length segments.  Each segment is detrended by function
    *detrend* and windowed by function *window*.  *noverlap* gives
    the length of the overlap between segments.  The product of
    the direct FFTs of *x* and *y* are averaged over each segment
    to compute :math:`P_{xy}`, with a scaling to correct for power
    loss due to windowing.

    If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
    padded to *NFFT*.

    Parameters
    ----------
    x, y : 1-D arrays or sequences
        Arrays or sequences containing the data

    %(Spectral)s

    %(PSD)s

    noverlap : integer
        The number of points of overlap between segments.
        The default value is 0 (no overlap).

    Returns
    -------
    Pxy : 1-D array
        The values for the cross spectrum `P_{xy}` before scaling (real valued)

    freqs : 1-D array
        The frequencies corresponding to the elements in *Pxy*

    References
    ----------
    Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John
    Wiley & Sons (1986)

    See Also
    --------
    :func:`psd`
        :func:`psd` is the equivalent to setting y=x.


    return a list of (ind0, ind1) such that mask[ind0:ind1].all() is
    True and we cover all such regions


        Make a reversed instance of the Colormap.

        .. note :: Function not implemented for base class.

        Parameters
        ----------
        name : str, optional
            The name for the reversed colormap. If it's None the
            name will be the name of the parent colormap + "_r".

        Notes
        -----
        See :meth:`LinearSegmentedColormap.reversed` and
        :meth:`ListedColormap.reversed`


The unit vector direction towards the light source


        Calculates the illumination intensity for a surface using the defined
        azimuth and elevation for the light source.

        This computes the normal vectors for the surface, and then passes them
        on to `shade_normals`

        Parameters
        ----------
        elevation : array-like
            A 2d array (or equivalent) of the height values used to generate an
            illumination map
        vert_exag : number, optional
            The amount to exaggerate the elevation values by when calculating
            illumination. This can be used either to correct for differences in
            units between the x-y coordinate system and the elevation
            coordinate system (e.g. decimal degrees vs meters) or to exaggerate
            or de-emphasize topographic effects.
        dx : number, optional
            The x-spacing (columns) of the input *elevation* grid.
        dy : number, optional
            The y-spacing (rows) of the input *elevation* grid.
        fraction : number, optional
            Increases or decreases the contrast of the hillshade.  Values
            greater than one will cause intermediate values to move closer to
            full illumination or shadow (and clipping any values that move
            beyond 0 or 1). Note that this is not visually or mathematically
            the same as vertical exaggeration.
        Returns
        -------
        intensity : ndarray
            A 2d array of illumination values between 0-1, where 0 is
            completely in shadow and 1 is completely illuminated.


        Combine colormapped data values with an illumination intensity map
        (a.k.a.  "hillshade") of the values.

        Parameters
        ----------
        data : array-like
            A 2d array (or equivalent) of the height values used to generate a
            shaded map.
        cmap : `~matplotlib.colors.Colormap` instance
            The colormap used to color the *data* array. Note that this must be
            a `~matplotlib.colors.Colormap` instance.  For example, rather than
            passing in `cmap='gist_earth'`, use
            `cmap=plt.get_cmap('gist_earth')` instead.
        norm : `~matplotlib.colors.Normalize` instance, optional
            The normalization used to scale values before colormapping. If
            None, the input will be linearly scaled between its min and max.
        blend_mode : {'hsv', 'overlay', 'soft'} or callable, optional
            The type of blending used to combine the colormapped data
            values with the illumination intensity.  Default is
            "overlay".  Note that for most topographic surfaces,
            "overlay" or "soft" appear more visually realistic. If a
            user-defined function is supplied, it is expected to
            combine an MxNx3 RGB array of floats (ranging 0 to 1) with
            an MxNx1 hillshade array (also 0 to 1).  (Call signature
            `func(rgb, illum, **kwargs)`) Additional kwargs supplied
            to this function will be passed on to the *blend_mode*
            function.
        vmin : scalar or None, optional
            The minimum value used in colormapping *data*. If *None* the
            minimum value in *data* is used. If *norm* is specified, then this
            argument will be ignored.
        vmax : scalar or None, optional
            The maximum value used in colormapping *data*. If *None* the
            maximum value in *data* is used. If *norm* is specified, then this
            argument will be ignored.
        vert_exag : number, optional
            The amount to exaggerate the elevation values by when calculating
            illumination. This can be used either to correct for differences in
            units between the x-y coordinate system and the elevation
            coordinate system (e.g. decimal degrees vs meters) or to exaggerate
            or de-emphasize topography.
        dx : number, optional
            The x-spacing (columns) of the input *elevation* grid.
        dy : number, optional
            The y-spacing (rows) of the input *elevation* grid.
        fraction : number, optional
            Increases or decreases the contrast of the hillshade.  Values
            greater than one will cause intermediate values to move closer to
            full illumination or shadow (and clipping any values that move
            beyond 0 or 1). Note that this is not visually or mathematically
            the same as vertical exaggeration.
        Additional kwargs are passed on to the *blend_mode* function.

        Returns
        -------
        rgba : ndarray
            An MxNx4 array of floats ranging between 0-1.


        Combines an rgb image with an intensity map using "soft light"
        blending.  Uses the "pegtop" formula.

        Parameters
        ----------
        rgb : ndarray
            An MxNx3 RGB array of floats ranging from 0 to 1 (color image).
        intensity : ndarray
            An MxNx1 array of floats ranging from 0 to 1 (grayscale image).

        Returns
        -------
        rgb : ndarray
            An MxNx3 RGB array representing the combined images.


        Combines an rgb image with an intensity map using "overlay" blending.

        Parameters
        ----------
        rgb : ndarray
            An MxNx3 RGB array of floats ranging from 0 to 1 (color image).
        intensity : ndarray
            An MxNx1 array of floats ranging from 0 to 1 (grayscale image).

        Returns
        -------
        rgb : ndarray
            An MxNx3 RGB array representing the combined images.


        Returns the full string representation of the value with the
        position unspecified.


        Return a short string version of the tick value.

        Defaults to the position-independent long value.


        Return the values of the located ticks given **vmin** and **vmax**.

        .. note::
            To get tick locations with the vmin and vmax values defined
            automatically for the associated :attr:`axis` simply call
            the Locator instance::

                >>> print((type(loc)))
                <type 'Locator'>
                >>> print((loc()))
                [1, 2, 3, 4]


        select a scale for the range from vmin to vmax

        Normally this method is overridden by subclasses to
        change locator behaviour.


        Return the locations of the ticks.

        .. note::

            Because the values are Null, vmin and vmax are not used in this
            method.


    Convert an RGB image to RGBA, as required by the image resample C++
    extension.


Returns `True` if the image can be composited with its neighbors.


        The list of codes in the `Path` as a 1-D numpy array.  Each
        code is one of `STOP`, `MOVETO`, `LINETO`, `CURVE3`, `CURVE4`
        or `CLOSEPOLY`.  For codes that correspond to more than one
        vertex (`CURVE3` and `CURVE4`), that code will be repeated so
        that the length of `self.vertices` and `self.codes` is always
        the same.


        The fraction of a pixel difference below which vertices will
        be simplified out.


`True` if the vertices array should be simplified.


`True` if the `Path` is read-only.


        Return a transformed copy of the path.

        .. seealso::

            :class:`matplotlib.transforms.TransformedPath`
                A specialized path class that will cache the
                transformed result and automatically update when the
                transform changes.