def binned_statistic_2d(x, y, values, statistic='<STR_LIT>',<EOL>bins=<NUM_LIT:10>, range=None):

<EOL>try:<EOL><INDENT>N = len(bins)<EOL><DEDENT>except TypeError:<EOL><INDENT>N = <NUM_LIT:1><EOL><DEDENT>if N != <NUM_LIT:1> and N != <NUM_LIT:2>:<EOL><INDENT>xedges = yedges = np.asarray(bins, float)<EOL>bins = [xedges, yedges]<EOL><DEDENT>medians, edges, xy = binned_statistic_dd([x, y], values, statistic,<EOL>bins, range)<EOL>return medians, edges[<NUM_LIT:0>], edges[<NUM_LIT:1>], xy<EOL>

Compute a bidimensional binned statistic for a set of data.

This is a generalization of a histogram2d function.  A histogram divides
the space into bins, and returns the count of the number of points in
each bin.  This function allows the computation of the sum, mean, median,
or other statistic of the values within each bin.

Parameters
----------
x : (N,) array_like
    A sequence of values to be binned along the first dimension.
y : (M,) array_like
    A sequence of values to be binned along the second dimension.
values : (N,) array_like
    The values on which the statistic will be computed.  This must be
    the same shape as `x`.
statistic : string or callable, optional
    The statistic to compute (default is 'mean').
    The following statistics are available:

      * 'mean' : compute the mean of values for points within each bin.
        Empty bins will be represented by NaN.
      * 'median' : compute the median of values for points within each
        bin. Empty bins will be represented by NaN.
      * 'count' : compute the count of points within each bin.  This is
        identical to an unweighted histogram.  `values` array is not
        referenced.
      * 'sum' : compute the sum of values for points within each bin.
        This is identical to a weighted histogram.
      * function : a user-defined function which takes a 1D array of
        values, and outputs a single numerical statistic. This function
        will be called on the values in each bin.  Empty bins will be
        represented by function([]), or NaN if this returns an error.

bins : int or [int, int] or array-like or [array, array], optional
    The bin specification:

      * the number of bins for the two dimensions (nx=ny=bins),
      * the number of bins in each dimension (nx, ny = bins),
      * the bin edges for the two dimensions (x_edges = y_edges = bins),
      * the bin edges in each dimension (x_edges, y_edges = bins).

range : (2,2) array_like, optional
    The leftmost and rightmost edges of the bins along each dimension
    (if not specified explicitly in the `bins` parameters):
    [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be
    considered outliers and not tallied in the histogram.

Returns
-------
statistic : (nx, ny) ndarray
    The values of the selected statistic in each two-dimensional bin
xedges : (nx + 1) ndarray
    The bin edges along the first dimension.
yedges : (ny + 1) ndarray
    The bin edges along the second dimension.
binnumber : 1-D ndarray of ints
    This assigns to each observation an integer that represents the bin
    in which this observation falls. Array has the same length as `values`.

See Also
--------
numpy.histogram2d, binned_statistic, binned_statistic_dd

Notes
-----

.. versionadded:: 0.11.0


def binned_statistic_dd(sample, values, statistic='<STR_LIT>',<EOL>bins=<NUM_LIT:10>, range=None):

known_stats = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT:count>', '<STR_LIT>', '<STR_LIT>']<EOL>if not callable(statistic) and statistic not in known_stats:<EOL><INDENT>raise ValueError('<STR_LIT>' % (statistic,))<EOL><DEDENT>try:<EOL><INDENT>N, D = sample.shape<EOL><DEDENT>except (AttributeError, ValueError):<EOL><INDENT>sample = np.atleast_2d(sample).T<EOL>N, D = sample.shape<EOL><DEDENT>nbin = np.empty(D, int)<EOL>edges = D * [None]<EOL>dedges = D * [None]<EOL>try:<EOL><INDENT>M = len(bins)<EOL>if M != D:<EOL><INDENT>raise AttributeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>bins = D * [bins]<EOL><DEDENT>if range is None:<EOL><INDENT>smin = np.atleast_1d(np.array(sample.min(<NUM_LIT:0>), float))<EOL>smax = np.atleast_1d(np.array(sample.max(<NUM_LIT:0>), float))<EOL><DEDENT>else:<EOL><INDENT>smin = np.zeros(D)<EOL>smax = np.zeros(D)<EOL>for i in np.arange(D):<EOL><INDENT>smin[i], smax[i] = range[i]<EOL><DEDENT><DEDENT>for i in np.arange(len(smin)):<EOL><INDENT>if smin[i] == smax[i]:<EOL><INDENT>smin[i] = smin[i] - <NUM_LIT><EOL>smax[i] = smax[i] + <NUM_LIT><EOL><DEDENT><DEDENT>for i in np.arange(D):<EOL><INDENT>if np.isscalar(bins[i]):<EOL><INDENT>nbin[i] = bins[i] + <NUM_LIT:2>  <EOL>edges[i] = np.linspace(smin[i], smax[i], nbin[i] - <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>edges[i] = np.asarray(bins[i], float)<EOL>nbin[i] = len(edges[i]) + <NUM_LIT:1>  <EOL><DEDENT>dedges[i] = np.diff(edges[i])<EOL><DEDENT>nbin = np.asarray(nbin)<EOL>Ncount = {}<EOL>for i in np.arange(D):<EOL><INDENT>Ncount[i] = np.digitize(sample[:, i], edges[i])<EOL><DEDENT>for i in np.arange(D):<EOL><INDENT>decimal = int(-np.log10(dedges[i].min())) + <NUM_LIT:6><EOL>on_edge = np.where(np.around(sample[:, i], decimal)<EOL>== np.around(edges[i][-<NUM_LIT:1>], decimal))[<NUM_LIT:0>]<EOL>Ncount[i][on_edge] -= <NUM_LIT:1><EOL><DEDENT>ni = nbin.argsort()<EOL>xy = np.zeros(N, int)<EOL>for i in np.arange(<NUM_LIT:0>, D - <NUM_LIT:1>):<EOL><INDENT>xy += Ncount[ni[i]] * nbin[ni[i + <NUM_LIT:1>:]].prod()<EOL><DEDENT>xy += Ncount[ni[-<NUM_LIT:1>]]<EOL>result = np.empty(nbin.prod(), float)<EOL>if statistic == '<STR_LIT>':<EOL><INDENT>result.fill(np.nan)<EOL>flatcount = np.bincount(xy, None)<EOL>flatsum = np.bincount(xy, values)<EOL>a = flatcount.nonzero()<EOL>result[a] = flatsum[a] / flatcount[a]<EOL><DEDENT>elif statistic == '<STR_LIT>':<EOL><INDENT>result.fill(<NUM_LIT:0>)<EOL>flatcount = np.bincount(xy, None)<EOL>flatsum = np.bincount(xy, values)<EOL>flatsum2 = np.bincount(xy, values ** <NUM_LIT:2>)<EOL>a = flatcount.nonzero()<EOL>result[a] = np.sqrt(flatsum2[a] / flatcount[a]<EOL>- (flatsum[a] / flatcount[a]) ** <NUM_LIT:2>)<EOL><DEDENT>elif statistic == '<STR_LIT:count>':<EOL><INDENT>result.fill(<NUM_LIT:0>)<EOL>flatcount = np.bincount(xy, None)<EOL>a = np.arange(len(flatcount))<EOL>result[a] = flatcount<EOL><DEDENT>elif statistic == '<STR_LIT>':<EOL><INDENT>result.fill(<NUM_LIT:0>)<EOL>flatsum = np.bincount(xy, values)<EOL>a = np.arange(len(flatsum))<EOL>result[a] = flatsum<EOL><DEDENT>elif statistic == '<STR_LIT>':<EOL><INDENT>result.fill(np.nan)<EOL>for i in np.unique(xy):<EOL><INDENT>result[i] = np.median(values[xy == i])<EOL><DEDENT><DEDENT>elif callable(statistic):<EOL><INDENT>with warnings.catch_warnings():<EOL><INDENT>warnings.filterwarnings('<STR_LIT:ignore>', category=RuntimeWarning)<EOL>old = np.seterr(invalid='<STR_LIT:ignore>')<EOL>try:<EOL><INDENT>null = statistic([])<EOL><DEDENT>except:<EOL><INDENT>null = np.nan<EOL><DEDENT>np.seterr(**old)<EOL><DEDENT>result.fill(null)<EOL>for i in np.unique(xy):<EOL><INDENT>result[i] = statistic(values[xy == i])<EOL><DEDENT><DEDENT>result = result.reshape(np.sort(nbin))<EOL>for i in np.arange(nbin.size):<EOL><INDENT>j = ni.argsort()[i]<EOL>result = result.swapaxes(i, j)<EOL>ni[i], ni[j] = ni[j], ni[i]<EOL><DEDENT>core = D * [slice(<NUM_LIT:1>, -<NUM_LIT:1>)]<EOL>result = result[core]<EOL>if (result.shape != nbin - <NUM_LIT:2>).any():<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>return result, edges, xy<EOL>

Compute a multidimensional binned statistic for a set of data.

This is a generalization of a histogramdd function.  A histogram divides
the space into bins, and returns the count of the number of points in
each bin.  This function allows the computation of the sum, mean, median,
or other statistic of the values within each bin.

Parameters
----------
sample : array_like
    Data to histogram passed as a sequence of D arrays of length N, or
    as an (N,D) array.
values : array_like
    The values on which the statistic will be computed.  This must be
    the same shape as x.
statistic : string or callable, optional
    The statistic to compute (default is 'mean').
    The following statistics are available:

      * 'mean' : compute the mean of values for points within each bin.
        Empty bins will be represented by NaN.
      * 'median' : compute the median of values for points within each
        bin. Empty bins will be represented by NaN.
      * 'count' : compute the count of points within each bin.  This is
        identical to an unweighted histogram.  `values` array is not
        referenced.
      * 'sum' : compute the sum of values for points within each bin.
        This is identical to a weighted histogram.
      * function : a user-defined function which takes a 1D array of
        values, and outputs a single numerical statistic. This function
        will be called on the values in each bin.  Empty bins will be
        represented by function([]), or NaN if this returns an error.

bins : sequence or int, optional
    The bin specification:

      * A sequence of arrays describing the bin edges along each dimension.
      * The number of bins for each dimension (nx, ny, ... =bins)
      * The number of bins for all dimensions (nx=ny=...=bins).

range : sequence, optional
    A sequence of lower and upper bin edges to be used if the edges are
    not given explicitely in `bins`. Defaults to the minimum and maximum
    values along each dimension.

Returns
-------
statistic : ndarray, shape(nx1, nx2, nx3,...)
    The values of the selected statistic in each two-dimensional bin
edges : list of ndarrays
    A list of D arrays describing the (nxi + 1) bin edges for each
    dimension
binnumber : 1-D ndarray of ints
    This assigns to each observation an integer that represents the bin
    in which this observation falls. Array has the same length as values.

See Also
--------
np.histogramdd, binned_statistic, binned_statistic_2d

Notes
-----

.. versionadded:: 0.11.0


@deprecate(message="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>def randwppf(ppf, args=(), size=None):

U = random_sample(size=size)<EOL>return ppf(*(U,)+args)<EOL>

returns an array of randomly distributed integers of a distribution
whose percent point function (inverse of the CDF or quantile function)
is given.

args is a tuple of extra arguments to the ppf function (i.e. shape,
location, scale), and size is the size of the output.  Note the ppf
function must accept an array of q values to compute over.


@deprecate(message="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>def randwcdf(cdf, mean=<NUM_LIT:1.0>, args=(), size=None):

import scipy.optimize as optimize<EOL>def _ppfopt(x, q, *nargs):<EOL><INDENT>newargs = (x,)+nargs<EOL>return cdf(*newargs) - q<EOL><DEDENT>def _ppf(q, *nargs):<EOL><INDENT>return optimize.fsolve(_ppfopt, mean, args=(q,)+nargs)<EOL><DEDENT>_vppf = vectorize(_ppf)<EOL>U = random_sample(size=size)<EOL>return _vppf(*(U,)+args)<EOL>

Returns an array of randomly distributed integers given a CDF.

Given a cumulative distribution function (CDF) returns an array of
randomly distributed integers that would satisfy the CDF.

Parameters
----------
cdf : function
    CDF function that accepts a single value and `args`, and returns
    an single value.
mean : float, optional
    The mean of the distribution which helps the solver.  Defaults
    to 1.0.
args : tuple, optional
    Extra arguments to the cdf function (i.e. shape, location, scale)
size : {int, None}, optional
    Is the size of the output.  If None, only 1 value will be returned.

Returns
-------
randwcdf : ndarray
    Array of random numbers.

Notes
-----
Can use the ``scipy.stats.distributions.*.cdf`` functions for the
`cdf` parameter.


lam = np.asarray(lam)<EOL>shp = lam.shape<EOL>lam = np.atleast_1d(lam).astype(np.float64)<EOL>threshold = <NUM_LIT><EOL>low_mask = lam < -<NUM_LIT:0.5><EOL>neghalf_mask = lam == -<NUM_LIT:0.5><EOL>small_mask = np.abs(lam) < threshold<EOL>reg_mask = ~(low_mask | neghalf_mask | small_mask)<EOL>small = lam[small_mask]<EOL>reg = lam[reg_mask]<EOL>v = np.empty_like(lam)<EOL>v[low_mask] = np.nan<EOL>v[neghalf_mask] = np.inf<EOL>if small.size > <NUM_LIT:0>:<EOL><INDENT>v[small_mask] = _tukeylambda_var_p(small) / _tukeylambda_var_q(small)<EOL><DEDENT>if reg.size > <NUM_LIT:0>:<EOL><INDENT>v[reg_mask] = (<NUM_LIT> / reg**<NUM_LIT:2>) * (<NUM_LIT:1.0> / (<NUM_LIT:1.0> + <NUM_LIT:2> * reg) -<EOL>beta(reg + <NUM_LIT:1>, reg + <NUM_LIT:1>))<EOL><DEDENT>v.shape = shp<EOL>return v<EOL>

Variance of the Tukey Lambda distribution.

    Parameters
    ----------
    lam : array_like
        The lambda values at which to compute the variance.

    Returns
    -------
    v : ndarray
        The variance.  For lam < -0.5, the variance is not defined, so
        np.nan is returned.  For lam = 0.5, np.inf is returned.

    Notes
    -----
    In an interval around lambda=0, this function uses the [4,4] Pade
    approximation to compute the variance.  Otherwise it uses the standard
    formula (http://en.wikipedia.org/wiki/Tukey_lambda_distribution).  The
    Pade approximation is used because the standard formula has a removable
    discontinuity at lambda = 0, and does not produce accurate numerical
    results near lambda = 0.


lam = np.asarray(lam)<EOL>shp = lam.shape<EOL>lam = np.atleast_1d(lam).astype(np.float64)<EOL>threshold = <NUM_LIT><EOL>low_mask = lam < -<NUM_LIT><EOL>negqrtr_mask = lam == -<NUM_LIT><EOL>small_mask = np.abs(lam) < threshold<EOL>reg_mask = ~(low_mask | negqrtr_mask | small_mask)<EOL>small = lam[small_mask]<EOL>reg = lam[reg_mask]<EOL>k = np.empty_like(lam)<EOL>k[low_mask] = np.nan<EOL>k[negqrtr_mask] = np.inf<EOL>if small.size > <NUM_LIT:0>:<EOL><INDENT>k[small_mask] = _tukeylambda_kurt_p(small) / _tukeylambda_kurt_q(small)<EOL><DEDENT>if reg.size > <NUM_LIT:0>:<EOL><INDENT>numer = (<NUM_LIT:1.0> / (<NUM_LIT:4> * reg + <NUM_LIT:1>) - <NUM_LIT:4> * beta(<NUM_LIT:3> * reg + <NUM_LIT:1>, reg + <NUM_LIT:1>) +<EOL><NUM_LIT:3> * beta(<NUM_LIT:2> * reg + <NUM_LIT:1>, <NUM_LIT:2> * reg + <NUM_LIT:1>))<EOL>denom = <NUM_LIT:2> * (<NUM_LIT:1.0>/(<NUM_LIT:2> * reg + <NUM_LIT:1>) - beta(reg + <NUM_LIT:1>, reg + <NUM_LIT:1>))**<NUM_LIT:2><EOL>k[reg_mask] = numer / denom - <NUM_LIT:3><EOL><DEDENT>k.shape = shp<EOL>return k<EOL>

Kurtosis of the Tukey Lambda distribution.

    Parameters
    ----------
    lam : array_like
        The lambda values at which to compute the variance.

    Returns
    -------
    v : ndarray
        The variance.  For lam < -0.25, the variance is not defined, so
        np.nan is returned.  For lam = 0.25, np.inf is returned.


def _process_parameters(dim, mean, cov):

<EOL>if dim is None:<EOL><INDENT>if mean is None:<EOL><INDENT>if cov is None:<EOL><INDENT>dim = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>cov = np.asarray(cov, dtype=float)<EOL>if cov.ndim < <NUM_LIT:2>:<EOL><INDENT>dim = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>dim = cov.shape[<NUM_LIT:0>]<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>mean = np.asarray(mean, dtype=float)<EOL>dim = mean.size<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not np.isscalar(dim):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>if mean is None:<EOL><INDENT>mean = np.zeros(dim)<EOL><DEDENT>mean = np.asarray(mean, dtype=float)<EOL>if cov is None:<EOL><INDENT>cov = <NUM_LIT:1.0><EOL><DEDENT>cov = np.asarray(cov, dtype=float)<EOL>if dim == <NUM_LIT:1>:<EOL><INDENT>mean.shape = (<NUM_LIT:1>,)<EOL>cov.shape = (<NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>if mean.ndim != <NUM_LIT:1> or mean.shape[<NUM_LIT:0>] != dim:<EOL><INDENT>raise ValueError("<STR_LIT>" % dim)<EOL><DEDENT>if cov.ndim == <NUM_LIT:0>:<EOL><INDENT>cov = cov * np.eye(dim)<EOL><DEDENT>elif cov.ndim == <NUM_LIT:1>:<EOL><INDENT>cov = np.diag(cov)<EOL><DEDENT>elif cov.ndim == <NUM_LIT:2> and cov.shape != (dim, dim):<EOL><INDENT>rows, cols = cov.shape<EOL>if rows != cols:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>" % str(cov.shape))<EOL><DEDENT>else:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>msg = msg % (str(cov.shape), len(mean))<EOL><DEDENT>raise ValueError(msg)<EOL><DEDENT>elif cov.ndim > <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % cov.ndim)<EOL><DEDENT>return dim, mean, cov<EOL>

Infer dimensionality from mean or covariance matrix, ensure that
mean and covariance are full vector resp. matrix.


x = np.asarray(x, dtype=float)<EOL>if x.ndim == <NUM_LIT:0>:<EOL><INDENT>x = x[np.newaxis]<EOL><DEDENT>elif x.ndim == <NUM_LIT:1>:<EOL><INDENT>if dim == <NUM_LIT:1>:<EOL><INDENT>x = x[:, np.newaxis]<EOL><DEDENT>else:<EOL><INDENT>x = x[np.newaxis, :]<EOL><DEDENT><DEDENT>return x<EOL>

Adjust quantiles array so that last axis labels the components of
each data point.


out = out.squeeze()<EOL>if out.ndim == <NUM_LIT:0>:<EOL><INDENT>out = out[()]<EOL><DEDENT>return out<EOL>

Remove single-dimensional entries from array and convert to scalar,
if necessary.


def _eigvalsh_to_eps(spectrum, cond=None, rcond=None):

if rcond is not None:<EOL><INDENT>cond = rcond<EOL><DEDENT>if cond in [None, -<NUM_LIT:1>]:<EOL><INDENT>t = spectrum.dtype.char.lower()<EOL>factor = {'<STR_LIT:f>': <NUM_LIT>, '<STR_LIT:d>': <NUM_LIT>}<EOL>cond = factor[t] * np.finfo(t).eps<EOL><DEDENT>eps = cond * np.max(abs(spectrum))<EOL>return eps<EOL>

Determine which eigenvalues are "small" given the spectrum.

This is for compatibility across various linear algebra functions
that should agree about whether or not a Hermitian matrix is numerically
singular and what is its numerical matrix rank.
This is designed to be compatible with scipy.linalg.pinvh.

Parameters
----------
spectrum : 1d ndarray
    Array of eigenvalues of a Hermitian matrix.
cond, rcond : float, optional
    Cutoff for small eigenvalues.
    Singular values smaller than rcond * largest_eigenvalue are
    considered zero.
    If None or -1, suitable machine precision is used.

Returns
-------
eps : float
    Magnitude cutoff for numerical negligibility.


return np.array([<NUM_LIT:0> if abs(x) <= eps else <NUM_LIT:1>/x for x in v], dtype=float)<EOL>

A helper function for computing the pseudoinverse.

Parameters
----------
v : iterable of numbers
    This may be thought of as a vector of eigenvalues or singular values.
eps : float
    Values with magnitude no greater than eps are considered negligible.

Returns
-------
v_pinv : 1d float ndarray
    A vector of pseudo-inverted numbers.


return np.sum(gammaln(alpha)) - gammaln(np.sum(alpha))<EOL>

r"""
    Internal helper function to compute the log of the useful quotient

    .. math::
        B(\alpha) = \frac{\prod_{i=1}{K}\Gamma(\alpha_i)}{\Gamma\left(\sum_{i=1}^{K}\alpha_i\right)}

    Parameters
    ----------
    %(_dirichlet_doc_default_callparams)s

    Returns
    -------
    B : scalar
        Helper quotient, internal use only


def __call__(self, mean=None, cov=<NUM_LIT:1>, allow_singular=False):

return multivariate_normal_frozen(mean, cov,<EOL>allow_singular=allow_singular)<EOL>

Create a frozen multivariate normal distribution.

See `multivariate_normal_frozen` for more information.


def _logpdf(self, x, mean, prec_U, log_det_cov, rank):

dev = x - mean<EOL>maha = np.sum(np.square(np.dot(dev, prec_U)), axis=-<NUM_LIT:1>)<EOL>return -<NUM_LIT:0.5> * (rank * _LOG_2PI + log_det_cov + maha)<EOL>

Parameters
----------
x : ndarray
    Points at which to evaluate the log of the probability
    density function
mean : ndarray
    Mean of the distribution
prec_U : ndarray
    A decomposition such that np.dot(prec_U, prec_U.T)
    is the precision matrix, i.e. inverse of the covariance matrix.
log_det_cov : float
    Logarithm of the determinant of the covariance matrix
rank : int
    Rank of the covariance matrix.

Notes
-----
As this function does no argument checking, it should not be
called directly; use 'logpdf' instead.


def logpdf(self, x, mean, cov, allow_singular=False):

dim, mean, cov = _process_parameters(None, mean, cov)<EOL>x = _process_quantiles(x, dim)<EOL>psd = _PSD(cov, allow_singular=allow_singular)<EOL>out = self._logpdf(x, mean, psd.U, psd.log_pdet, psd.rank)<EOL>return _squeeze_output(out)<EOL>

Log of the multivariate normal probability density function.

Parameters
----------
x : array_like
    Quantiles, with the last axis of `x` denoting the components.
%(_doc_default_callparams)s

Notes
-----
%(_doc_callparams_note)s

Returns
-------
pdf : ndarray
    Log of the probability density function evaluated at `x`


def pdf(self, x, mean, cov, allow_singular=False):

dim, mean, cov = _process_parameters(None, mean, cov)<EOL>x = _process_quantiles(x, dim)<EOL>psd = _PSD(cov, allow_singular=allow_singular)<EOL>out = np.exp(self._logpdf(x, mean, psd.U, psd.log_pdet, psd.rank))<EOL>return _squeeze_output(out)<EOL>

Multivariate normal probability density function.

Parameters
----------
x : array_like
    Quantiles, with the last axis of `x` denoting the components.
%(_doc_default_callparams)s

Notes
-----
%(_doc_callparams_note)s

Returns
-------
pdf : ndarray
    Probability density function evaluated at `x`


def rvs(self, mean=None, cov=<NUM_LIT:1>, size=<NUM_LIT:1>):

dim, mean, cov = _process_parameters(None, mean, cov)<EOL>out = np.random.multivariate_normal(mean, cov, size)<EOL>return _squeeze_output(out)<EOL>

Draw random samples from a multivariate normal distribution.

Parameters
----------
%(_doc_default_callparams)s
size : integer, optional
    Number of samples to draw (default 1).

Notes
-----
%(_doc_callparams_note)s

Returns
-------
rvs : ndarray or scalar
    Random variates of size (`size`, `N`), where `N` is the
    dimension of the random variable.


def entropy(self, mean=None, cov=<NUM_LIT:1>):

dim, mean, cov = _process_parameters(None, mean, cov)<EOL>return <NUM_LIT:0.5> * np.log(np.linalg.det(<NUM_LIT:2> * np.pi * np.e * cov))<EOL>

Compute the differential entropy of the multivariate normal.

Parameters
----------
%(_doc_default_callparams)s

Notes
-----
%(_doc_callparams_note)s

Returns
-------
h : scalar
    Entropy of the multivariate normal distribution


def __init__(self, mean=None, cov=<NUM_LIT:1>, allow_singular=False):

self.dim, self.mean, self.cov = _process_parameters(None, mean, cov)<EOL>self.cov_info = _PSD(self.cov, allow_singular=allow_singular)<EOL>self._mnorm = multivariate_normal_gen()<EOL>

Create a frozen multivariate normal distribution.

Parameters
----------
mean : array_like, optional
    Mean of the distribution (default zero)
cov : array_like, optional
    Covariance matrix of the distribution (default one)
allow_singular : bool, optional
    If this flag is True then tolerate a singular
    covariance matrix (default False).

Examples
--------
When called with the default parameters, this will create a 1D random
variable with mean 0 and covariance 1:

>>> from scipy.stats import multivariate_normal
>>> r = multivariate_normal()
>>> r.mean
array([ 0.])
>>> r.cov
array([[1.]])


log_pdet = self.cov_info.log_pdet<EOL>rank = self.cov_info.rank<EOL>return <NUM_LIT:0.5> * (rank * (_LOG_2PI + <NUM_LIT:1>) + log_pdet)<EOL>

Computes the differential entropy of the multivariate normal.

Returns
-------
h : scalar
    Entropy of the multivariate normal distribution


lnB = _lnB(alpha)<EOL>return - lnB + np.sum((np.log(x.T) * (alpha - <NUM_LIT:1>)).T, <NUM_LIT:0>)<EOL>

Parameters
----------
x : ndarray
    Points at which to evaluate the log of the probability
    density function
%(_dirichlet_doc_default_callparams)s

Notes
-----
As this function does no argument checking, it should not be
called directly; use 'logpdf' instead.


alpha = _dirichlet_check_parameters(alpha)<EOL>x = _dirichlet_check_input(alpha, x)<EOL>out = self._logpdf(x, alpha)<EOL>return _squeeze_output(out)<EOL>

Log of the Dirichlet probability density function.

Parameters
----------
x : array_like
    Quantiles, with the last axis of `x` denoting the components.
%(_dirichlet_doc_default_callparams)s

Returns
-------
pdf : ndarray
    Log of the probability density function evaluated at `x`


alpha = _dirichlet_check_parameters(alpha)<EOL>x = _dirichlet_check_input(alpha, x)<EOL>out = np.exp(self._logpdf(x, alpha))<EOL>return _squeeze_output(out)<EOL>

The Dirichlet probability density function.

Parameters
----------
x : array_like
    Quantiles, with the last axis of `x` denoting the components.
%(_dirichlet_doc_default_callparams)s

Returns
-------
pdf : ndarray
    The probability density function evaluated at `x`


alpha = _dirichlet_check_parameters(alpha)<EOL>out = alpha / (np.sum(alpha))<EOL>return _squeeze_output(out)<EOL>

Compute the mean of the dirichlet distribution.

Parameters
----------
%(_dirichlet_doc_default_callparams)s

Returns
-------
mu : scalar
    Mean of the Dirichlet distribution


alpha = _dirichlet_check_parameters(alpha)<EOL>alpha0 = np.sum(alpha)<EOL>out = (alpha * (alpha0 - alpha)) / ((alpha0 * alpha0) * (alpha0 + <NUM_LIT:1>))<EOL>return out<EOL>

Compute the variance of the dirichlet distribution.

Parameters
----------
%(_dirichlet_doc_default_callparams)s

Returns
-------
v : scalar
    Variance of the Dirichlet distribution


alpha = _dirichlet_check_parameters(alpha)<EOL>alpha0 = np.sum(alpha)<EOL>lnB = _lnB(alpha)<EOL>K = alpha.shape[<NUM_LIT:0>]<EOL>out = lnB + (alpha0 - K) * scipy.special.psi(alpha0) - np.sum(<EOL>(alpha - <NUM_LIT:1>) * scipy.special.psi(alpha))<EOL>return _squeeze_output(out)<EOL>

Compute the differential entropy of the dirichlet distribution.

Parameters
----------
%(_dirichlet_doc_default_callparams)s

Returns
-------
h : scalar
    Entropy of the Dirichlet distribution


alpha = _dirichlet_check_parameters(alpha)<EOL>return np.random.dirichlet(alpha, size=size)<EOL>

Draw random samples from a Dirichlet distribution.

Parameters
----------
%(_dirichlet_doc_default_callparams)s
size : integer, optional
    Number of samples to draw (default 1).

Returns
-------
rvs : ndarray or scalar
    Random variates of size (`size`, `N`), where `N` is the
    dimension of the random variable.


res = mvsdist(data)<EOL>if alpha >= <NUM_LIT:1> or alpha <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" % alpha)<EOL><DEDENT>return tuple((x.mean(), x.interval(alpha)) for x in res)<EOL>

Bayesian confidence intervals for the mean, var, and std.

Parameters
----------
data : array_like
    Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`.
    Requires 2 or more data points.
alpha : float, optional
    Probability that the returned confidence interval contains
    the true parameter.

Returns
-------
mean_cntr, var_cntr, std_cntr : tuple
    The three results are for the mean, variance and standard deviation,
    respectively.  Each result is a tuple of the form::

        (center, (lower, upper))

    with `center` the mean of the conditional pdf of the value given the
    data, and `(lower, upper)` a confidence interval, centered on the
    median, containing the estimate to a probability `alpha`.

Notes
-----
Each tuple of mean, variance, and standard deviation estimates represent
the (center, (lower, upper)) with center the mean of the conditional pdf
of the value given the data and (lower, upper) is a confidence interval
centered on the median, containing the estimate to a probability
`alpha`.

Converts data to 1-D and assumes all data has the same mean and variance.
Uses Jeffrey's prior for variance and std.

Equivalent to tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))

References
----------
T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and
standard-deviation from data", http://hdl.handle.net/1877/438, 2006.


x = ravel(data)<EOL>n = len(x)<EOL>if (n < <NUM_LIT:2>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>xbar = x.mean()<EOL>C = x.var()<EOL>if (n > <NUM_LIT:1000>):  <EOL><INDENT>mdist = distributions.norm(loc=xbar, scale=math.sqrt(C/n))<EOL>sdist = distributions.norm(loc=math.sqrt(C), scale=math.sqrt(C/(<NUM_LIT>*n)))<EOL>vdist = distributions.norm(loc=C, scale=math.sqrt(<NUM_LIT>/n)*C)<EOL><DEDENT>else:<EOL><INDENT>nm1 = n-<NUM_LIT:1><EOL>fac = n*C/<NUM_LIT><EOL>val = nm1/<NUM_LIT><EOL>mdist = distributions.t(nm1,loc=xbar,scale=math.sqrt(C/nm1))<EOL>sdist = distributions.gengamma(val,-<NUM_LIT:2>,scale=math.sqrt(fac))<EOL>vdist = distributions.invgamma(val,scale=fac)<EOL><DEDENT>return mdist, vdist, sdist<EOL>

'Frozen' distributions for mean, variance, and standard deviation of data.

Parameters
----------
data : array_like
    Input array. Converted to 1-D using ravel.
    Requires 2 or more data-points.

Returns
-------
mdist : "frozen" distribution object
    Distribution object representing the mean of the data
vdist : "frozen" distribution object
    Distribution object representing the variance of the data
sdist : "frozen" distribution object
    Distribution object representing the standard deviation of the data

Notes
-----
The return values from bayes_mvs(data) is equivalent to
``tuple((x.mean(), x.interval(0.90)) for x in mvsdist(data))``.

In other words, calling ``<dist>.mean()`` and ``<dist>.interval(0.90)``
on the three distribution objects returned from this function will give
the same results that are returned from `bayes_mvs`.

Examples
--------
>>> from scipy.stats import mvsdist
>>> data = [6, 9, 12, 7, 8, 8, 13]
>>> mean, var, std = mvsdist(data)

We now have frozen distribution objects "mean", "var" and "std" that we can
examine:

>>> mean.mean()
9.0
>>> mean.interval(0.95)
(6.6120585482655692, 11.387941451734431)
>>> mean.std()
1.1952286093343936


if n > <NUM_LIT:4> or n < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>n = int(n)<EOL>S = zeros(n+<NUM_LIT:1>,'<STR_LIT:d>')<EOL>data = ravel(data)<EOL>N = len(data)<EOL>for k in range(<NUM_LIT:1>,n+<NUM_LIT:1>):<EOL><INDENT>S[k] = sum(data**k,axis=<NUM_LIT:0>)<EOL><DEDENT>if n == <NUM_LIT:1>:<EOL><INDENT>return S[<NUM_LIT:1>]*<NUM_LIT:1.0>/N<EOL><DEDENT>elif n == <NUM_LIT:2>:<EOL><INDENT>return (N*S[<NUM_LIT:2>]-S[<NUM_LIT:1>]**<NUM_LIT>)/(N*(N-<NUM_LIT:1.0>))<EOL><DEDENT>elif n == <NUM_LIT:3>:<EOL><INDENT>return (<NUM_LIT:2>*S[<NUM_LIT:1>]**<NUM_LIT:3> - <NUM_LIT:3>*N*S[<NUM_LIT:1>]*S[<NUM_LIT:2>]+N*N*S[<NUM_LIT:3>]) / (N*(N-<NUM_LIT:1.0>)*(N-<NUM_LIT>))<EOL><DEDENT>elif n == <NUM_LIT:4>:<EOL><INDENT>return (-<NUM_LIT:6>*S[<NUM_LIT:1>]**<NUM_LIT:4> + <NUM_LIT:12>*N*S[<NUM_LIT:1>]**<NUM_LIT:2> * S[<NUM_LIT:2>] - <NUM_LIT:3>*N*(N-<NUM_LIT:1.0>)*S[<NUM_LIT:2>]**<NUM_LIT:2> -<EOL><NUM_LIT:4>*N*(N+<NUM_LIT:1>)*S[<NUM_LIT:1>]*S[<NUM_LIT:3>] + N*N*(N+<NUM_LIT:1>)*S[<NUM_LIT:4>]) /(N*(N-<NUM_LIT:1.0>)*(N-<NUM_LIT>)*(N-<NUM_LIT>))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Return the nth k-statistic (1<=n<=4 so far).

The nth k-statistic is the unique symmetric unbiased estimator of the nth
cumulant kappa_n.

Parameters
----------
data : array_like
    Input array.
n : int, {1, 2, 3, 4}, optional
    Default is equal to 2.

Returns
-------
kstat : float
    The nth k-statistic.

See Also
--------
kstatvar: Returns an unbiased estimator of the variance of the k-statistic.

Notes
-----
The cumulants are related to central moments but are specifically defined
using a power series expansion of the logarithm of the characteristic
function (which is the Fourier transform of the PDF).
In particular let phi(t) be the characteristic function, then::

    ln phi(t) = > kappa_n (it)^n / n!    (sum from n=0 to inf)

The first few cumulants (kappa_n)  in terms of central moments (mu_n) are::

    kappa_1 = mu_1
    kappa_2 = mu_2
    kappa_3 = mu_3
    kappa_4 = mu_4 - 3*mu_2**2
    kappa_5 = mu_5 - 10*mu_2 * mu_3

References
----------
http://mathworld.wolfram.com/k-Statistic.html

http://mathworld.wolfram.com/Cumulant.html


data = ravel(data)<EOL>N = len(data)<EOL>if n == <NUM_LIT:1>:<EOL><INDENT>return kstat(data,n=<NUM_LIT:2>)*<NUM_LIT:1.0>/N<EOL><DEDENT>elif n == <NUM_LIT:2>:<EOL><INDENT>k2 = kstat(data,n=<NUM_LIT:2>)<EOL>k4 = kstat(data,n=<NUM_LIT:4>)<EOL>return (<NUM_LIT:2>*k2*k2*N + (N-<NUM_LIT:1>)*k4)/(N*(N+<NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Returns an unbiased estimator of the variance of the k-statistic.

See `kstat` for more details of the k-statistic.

Parameters
----------
data : array_like
    Input array.
n : int, {1, 2}, optional
    Default is equal to 2.

Returns
-------
kstatvar : float
    The nth k-statistic variance.

See Also
--------
kstat


N = len(x)<EOL>osm_uniform = np.zeros(N, dtype=np.float64)<EOL>osm_uniform[-<NUM_LIT:1>] = <NUM_LIT:0.5>**(<NUM_LIT:1.0> / N)<EOL>osm_uniform[<NUM_LIT:0>] = <NUM_LIT:1> - osm_uniform[-<NUM_LIT:1>]<EOL>i = np.arange(<NUM_LIT:2>, N)<EOL>osm_uniform[<NUM_LIT:1>:-<NUM_LIT:1>] = (i - <NUM_LIT>) / (N + <NUM_LIT>)<EOL>return osm_uniform<EOL>

See Notes section of `probplot` for details.


if isinstance(dist, rv_generic):<EOL><INDENT>pass<EOL><DEDENT>elif isinstance(dist, string_types):<EOL><INDENT>try:<EOL><INDENT>dist = getattr(distributions, dist)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ValueError("<STR_LIT>" % dist)<EOL><DEDENT><DEDENT>elif enforce_subclass:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise ValueError(msg)<EOL><DEDENT>return dist<EOL>

Parse `dist` keyword.

    Parameters
    ----------
    dist : str or stats.distributions instance.
        Several functions take `dist` as a keyword, hence this utility
        function.
    enforce_subclass : bool, optional
        If True (default), `dist` needs to be a
        `_distn_infrastructure.rv_generic` instance.
        It can sometimes be useful to set this keyword to False, if a function
        wants to accept objects that just look somewhat like such an instance
        (for example, they have a ``ppf`` method).


def probplot(x, sparams=(), dist='<STR_LIT>', fit=True, plot=None):

x = np.asarray(x)<EOL>osm_uniform = _calc_uniform_order_statistic_medians(x)<EOL>dist = _parse_dist_kw(dist, enforce_subclass=False)<EOL>if sparams is None:<EOL><INDENT>sparams = ()<EOL><DEDENT>if isscalar(sparams):<EOL><INDENT>sparams = (sparams,)<EOL><DEDENT>if not isinstance(sparams, tuple):<EOL><INDENT>sparams = tuple(sparams)<EOL><DEDENT>osm = dist.ppf(osm_uniform, *sparams)<EOL>osr = sort(x)<EOL>if fit or (plot is not None):<EOL><INDENT>slope, intercept, r, prob, sterrest = stats.linregress(osm, osr)<EOL><DEDENT>if plot is not None:<EOL><INDENT>plot.plot(osm, osr, '<STR_LIT>', osm, slope*osm + intercept, '<STR_LIT>')<EOL>try:<EOL><INDENT>if hasattr(plot, '<STR_LIT>'):<EOL><INDENT>plot.set_title('<STR_LIT>')<EOL>plot.set_xlabel('<STR_LIT>')<EOL>plot.set_ylabel('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>plot.title('<STR_LIT>')<EOL>plot.xlabel('<STR_LIT>')<EOL>plot.ylabel('<STR_LIT>')<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>xmin = amin(osm)<EOL>xmax = amax(osm)<EOL>ymin = amin(x)<EOL>ymax = amax(x)<EOL>posx = xmin + <NUM_LIT> * (xmax - xmin)<EOL>posy = ymin + <NUM_LIT> * (ymax - ymin)<EOL>plot.text(posx, posy, "<STR_LIT>" % r**<NUM_LIT:2>)<EOL><DEDENT>if fit:<EOL><INDENT>return (osm, osr), (slope, intercept, r)<EOL><DEDENT>else:<EOL><INDENT>return osm, osr<EOL><DEDENT>

Calculate quantiles for a probability plot, and optionally show the plot.

Generates a probability plot of sample data against the quantiles of a
specified theoretical distribution (the normal distribution by default).
`probplot` optionally calculates a best-fit line for the data and plots the
results using Matplotlib or a given plot function.

Parameters
----------
x : array_like
    Sample/response data from which `probplot` creates the plot.
sparams : tuple, optional
    Distribution-specific shape parameters (shape parameters plus location
    and scale).
dist : str or stats.distributions instance, optional
    Distribution or distribution function name. The default is 'norm' for a
    normal probability plot.  Objects that look enough like a
    stats.distributions instance (i.e. they have a ``ppf`` method) are also
    accepted.
fit : bool, optional
    Fit a least-squares regression (best-fit) line to the sample data if
    True (default).
plot : object, optional
    If given, plots the quantiles and least squares fit.
    `plot` is an object that has to have methods "plot" and "text".
    The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
    or a custom object with the same methods.
    Default is None, which means that no plot is created.

Returns
-------
(osm, osr) : tuple of ndarrays
    Tuple of theoretical quantiles (osm, or order statistic medians) and
    ordered responses (osr).  `osr` is simply sorted input `x`.
    For details on how `osm` is calculated see the Notes section.
(slope, intercept, r) : tuple of floats, optional
    Tuple  containing the result of the least-squares fit, if that is
    performed by `probplot`. `r` is the square root of the coefficient of
    determination.  If ``fit=False`` and ``plot=None``, this tuple is not
    returned.

Notes
-----
Even if `plot` is given, the figure is not shown or saved by `probplot`;
``plt.show()`` or ``plt.savefig('figname.png')`` should be used after
calling `probplot`.

`probplot` generates a probability plot, which should not be confused with
a Q-Q or a P-P plot.  Statsmodels has more extensive functionality of this
type, see ``statsmodels.api.ProbPlot``.

The formula used for the theoretical quantiles (horizontal axis of the
probability plot) is Filliben's estimate::

    quantiles = dist.ppf(val), for

            0.5**(1/n),                  for i = n
      val = (i - 0.3175) / (n + 0.365),  for i = 2, ..., n-1
            1 - 0.5**(1/n),              for i = 1

where ``i`` indicates the i-th ordered value and ``n`` is the total number
of values.

Examples
--------
>>> from scipy import stats
>>> import matplotlib.pyplot as plt
>>> nsample = 100
>>> np.random.seed(7654321)

A t distribution with small degrees of freedom:

>>> ax1 = plt.subplot(221)
>>> x = stats.t.rvs(3, size=nsample)
>>> res = stats.probplot(x, plot=plt)

A t distribution with larger degrees of freedom:

>>> ax2 = plt.subplot(222)
>>> x = stats.t.rvs(25, size=nsample)
>>> res = stats.probplot(x, plot=plt)

A mixture of two normal distributions with broadcasting:

>>> ax3 = plt.subplot(223)
>>> x = stats.norm.rvs(loc=[0,5], scale=[1,1.5],
...                    size=(nsample/2.,2)).ravel()
>>> res = stats.probplot(x, plot=plt)

A standard normal distribution:

>>> ax4 = plt.subplot(224)
>>> x = stats.norm.rvs(loc=0, scale=1, size=nsample)
>>> res = stats.probplot(x, plot=plt)

Produce a new figure with a loggamma distribution, using the ``dist`` and
``sparams`` keywords:

>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> x = stats.loggamma.rvs(c=2.5, size=500)
>>> stats.probplot(x, dist=stats.loggamma, sparams=(2.5,), plot=ax)
>>> ax.set_title("Probplot for loggamma dist with shape parameter 2.5")

Show the results with Matplotlib:

>>> plt.show()


def ppcc_max(x, brack=(<NUM_LIT:0.0>,<NUM_LIT:1.0>), dist='<STR_LIT>'):

dist = _parse_dist_kw(dist)<EOL>osm_uniform = _calc_uniform_order_statistic_medians(x)<EOL>osr = sort(x)<EOL>def tempfunc(shape, mi, yvals, func):<EOL><INDENT>xvals = func(mi, shape)<EOL>r, prob = stats.pearsonr(xvals, yvals)<EOL>return <NUM_LIT:1>-r<EOL><DEDENT>return optimize.brent(tempfunc, brack=brack, args=(osm_uniform, osr, dist.ppf))<EOL>

Returns the shape parameter that maximizes the probability plot
    correlation coefficient for the given data to a one-parameter
    family of distributions.

    See also ppcc_plot


def ppcc_plot(x,a,b,dist='<STR_LIT>', plot=None, N=<NUM_LIT>):

svals = r_[a:b:complex(N)]<EOL>ppcc = svals*<NUM_LIT:0.0><EOL>k = <NUM_LIT:0><EOL>for sval in svals:<EOL><INDENT>r1,r2 = probplot(x,sval,dist=dist,fit=<NUM_LIT:1>)<EOL>ppcc[k] = r2[-<NUM_LIT:1>]<EOL>k += <NUM_LIT:1><EOL><DEDENT>if plot is not None:<EOL><INDENT>plot.plot(svals, ppcc, '<STR_LIT:x>')<EOL>plot.title('<STR_LIT>' % dist)<EOL>plot.xlabel('<STR_LIT>')<EOL>plot.ylabel('<STR_LIT>')<EOL><DEDENT>return svals, ppcc<EOL>

Returns (shape, ppcc), and optionally plots shape vs. ppcc
    (probability plot correlation coefficient) as a function of shape
    parameter for a one-parameter family of distributions from shape
    value a to b.

    See also ppcc_max


data = np.asarray(data)<EOL>N = data.shape[<NUM_LIT:0>]<EOL>if N == <NUM_LIT:0>:<EOL><INDENT>return np.nan<EOL><DEDENT>y = boxcox(data, lmb)<EOL>y_mean = np.mean(y, axis=<NUM_LIT:0>)<EOL>llf = (lmb - <NUM_LIT:1>) * np.sum(np.log(data), axis=<NUM_LIT:0>)<EOL>llf -= N / <NUM_LIT> * np.log(np.sum((y - y_mean)**<NUM_LIT> / N, axis=<NUM_LIT:0>))<EOL>return llf<EOL>

r"""The boxcox log-likelihood function.

    Parameters
    ----------
    lmb : scalar
        Parameter for Box-Cox transformation.  See `boxcox` for details.
    data : array_like
        Data to calculate Box-Cox log-likelihood for.  If `data` is
        multi-dimensional, the log-likelihood is calculated along the first
        axis.

    Returns
    -------
    llf : float or ndarray
        Box-Cox log-likelihood of `data` given `lmb`.  A float for 1-D `data`,
        an array otherwise.

    See Also
    --------
    boxcox, probplot, boxcox_normplot, boxcox_normmax

    Notes
    -----
    The Box-Cox log-likelihood function is defined here as

    .. math::

        llf = (\lambda - 1) \sum_i(\log(x_i)) -
              N/2 \log(\sum_i (y_i - \bar{y})^2 / N),

    where ``y`` is the Box-Cox transformed input data ``x``.

    Examples
    --------
    >>> from scipy import stats
    >>> import matplotlib.pyplot as plt
    >>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes
    >>> np.random.seed(1245)

    Generate some random variates and calculate Box-Cox log-likelihood values
    for them for a range of ``lmbda`` values:

    >>> x = stats.loggamma.rvs(5, loc=10, size=1000)
    >>> lmbdas = np.linspace(-2, 10)
    >>> llf = np.zeros(lmbdas.shape, dtype=np.float)
    >>> for ii, lmbda in enumerate(lmbdas):
    ...     llf[ii] = stats.boxcox_llf(lmbda, x)

    Also find the optimal lmbda value with `boxcox`:

    >>> x_most_normal, lmbda_optimal = stats.boxcox(x)

    Plot the log-likelihood as function of lmbda.  Add the optimal lmbda as a
    horizontal line to check that that's really the optimum:

    >>> fig = plt.figure()
    >>> ax = fig.add_subplot(111)
    >>> ax.plot(lmbdas, llf, 'b.-')
    >>> ax.axhline(stats.boxcox_llf(lmbda_optimal, x), color='r')
    >>> ax.set_xlabel('lmbda parameter')
    >>> ax.set_ylabel('Box-Cox log-likelihood')

    Now add some probability plots to show that where the log-likelihood is
    maximized the data transformed with `boxcox` looks closest to normal:

    >>> locs = [3, 10, 4]  # 'lower left', 'center', 'lower right'
    >>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs):
    ...     xt = stats.boxcox(x, lmbda=lmbda)
    ...     (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt)
    ...     ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc)
    ...     ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-')
    ...     ax_inset.set_xticklabels([])
    ...     ax_inset.set_yticklabels([])
    ...     ax_inset.set_title('$\lambda=%1.2f$' % lmbda)

    >>> plt.show()


x = np.asarray(x)<EOL>if x.size == <NUM_LIT:0>:<EOL><INDENT>return x<EOL><DEDENT>if any(x <= <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if lmbda is not None:  <EOL><INDENT>return special.boxcox(x, lmbda)<EOL><DEDENT>lmax = boxcox_normmax(x, method='<STR_LIT>')<EOL>y = boxcox(x, lmax)<EOL>if alpha is None:<EOL><INDENT>return y, lmax<EOL><DEDENT>else:<EOL><INDENT>interval = _boxcox_conf_interval(x, lmax, alpha)<EOL>return y, lmax, interval<EOL><DEDENT>

r"""
    Return a positive dataset transformed by a Box-Cox power transformation.

    Parameters
    ----------
    x : ndarray
        Input array.  Should be 1-dimensional.
    lmbda : {None, scalar}, optional
        If `lmbda` is not None, do the transformation for that value.

        If `lmbda` is None, find the lambda that maximizes the log-likelihood
        function and return it as the second output argument.
    alpha : {None, float}, optional
        If `alpha` is not None, return the ``100 * (1-alpha)%`` confidence
        interval for `lmbda` as the third output argument.
        Must be between 0.0 and 1.0.

    Returns
    -------
    boxcox : ndarray
        Box-Cox power transformed array.
    maxlog : float, optional
        If the `lmbda` parameter is None, the second returned argument is
        the lambda that maximizes the log-likelihood function.
    (min_ci, max_ci) : tuple of float, optional
        If `lmbda` parameter is None and `alpha` is not None, this returned
        tuple of floats represents the minimum and maximum confidence limits
        given `alpha`.

    See Also
    --------
    probplot, boxcox_normplot, boxcox_normmax, boxcox_llf

    Notes
    -----
    The Box-Cox transform is given by::

        y = (x**lmbda - 1) / lmbda,  for lmbda > 0
            log(x),                  for lmbda = 0

    `boxcox` requires the input data to be positive.  Sometimes a Box-Cox
    transformation provides a shift parameter to achieve this; `boxcox` does
    not.  Such a shift parameter is equivalent to adding a positive constant to
    `x` before calling `boxcox`.

    The confidence limits returned when `alpha` is provided give the interval
    where:

    .. math::

        llf(\hat{\lambda}) - llf(\lambda) < \frac{1}{2}\chi^2(1 - \alpha, 1),

    with ``llf`` the log-likelihood function and :math:`\chi^2` the chi-squared
    function.

    References
    ----------
    G.E.P. Box and D.R. Cox, "An Analysis of Transformations", Journal of the
    Royal Statistical Society B, 26, 211-252 (1964).

    Examples
    --------
    >>> from scipy import stats
    >>> import matplotlib.pyplot as plt

    We generate some random variates from a non-normal distribution and make a
    probability plot for it, to show it is non-normal in the tails:

    >>> fig = plt.figure()
    >>> ax1 = fig.add_subplot(211)
    >>> x = stats.loggamma.rvs(5, size=500) + 5
    >>> stats.probplot(x, dist=stats.norm, plot=ax1)
    >>> ax1.set_xlabel('')
    >>> ax1.set_title('Probplot against normal distribution')

    We now use `boxcox` to transform the data so it's closest to normal:

    >>> ax2 = fig.add_subplot(212)
    >>> xt, _ = stats.boxcox(x)
    >>> stats.probplot(xt, dist=stats.norm, plot=ax2)
    >>> ax2.set_title('Probplot after Box-Cox transformation')

    >>> plt.show()


def boxcox_normmax(x, brack=(-<NUM_LIT>, <NUM_LIT>), method='<STR_LIT>'):

def _pearsonr(x, brack):<EOL><INDENT>osm_uniform = _calc_uniform_order_statistic_medians(x)<EOL>xvals = distributions.norm.ppf(osm_uniform)<EOL>def _eval_pearsonr(lmbda, xvals, samps):<EOL><INDENT>y = boxcox(samps, lmbda)<EOL>yvals = np.sort(y)<EOL>r, prob = stats.pearsonr(xvals, yvals)<EOL>return <NUM_LIT:1> - r<EOL><DEDENT>return optimize.brent(_eval_pearsonr, brack=brack, args=(xvals, x))<EOL><DEDENT>def _mle(x, brack):<EOL><INDENT>def _eval_mle(lmb, data):<EOL><INDENT>return -boxcox_llf(lmb, data)<EOL><DEDENT>return optimize.brent(_eval_mle, brack=brack, args=(x,))<EOL><DEDENT>def _all(x, brack):<EOL><INDENT>maxlog = np.zeros(<NUM_LIT:2>, dtype=np.float)<EOL>maxlog[<NUM_LIT:0>] = _pearsonr(x, brack)<EOL>maxlog[<NUM_LIT:1>] = _mle(x, brack)<EOL>return maxlog<EOL><DEDENT>methods = {'<STR_LIT>': _pearsonr,<EOL>'<STR_LIT>': _mle,<EOL>'<STR_LIT:all>': _all}<EOL>if method not in methods.keys():<EOL><INDENT>raise ValueError("<STR_LIT>" % method)<EOL><DEDENT>optimfunc = methods[method]<EOL>return optimfunc(x, brack)<EOL>

Compute optimal Box-Cox transform parameter for input data.

    Parameters
    ----------
    x : array_like
        Input array.
    brack : 2-tuple, optional
        The starting interval for a downhill bracket search with
        `optimize.brent`.  Note that this is in most cases not critical; the
        final result is allowed to be outside this bracket.
    method : str, optional
        The method to determine the optimal transform parameter (`boxcox`
        ``lmbda`` parameter). Options are:

        'pearsonr'  (default)
            Maximizes the Pearson correlation coefficient between
            ``y = boxcox(x)`` and the expected values for ``y`` if `x` would be
            normally-distributed.

        'mle'
            Minimizes the log-likelihood `boxcox_llf`.  This is the method used
            in `boxcox`.

        'all'
            Use all optimization methods available, and return all results.
            Useful to compare different methods.

    Returns
    -------
    maxlog : float or ndarray
        The optimal transform parameter found.  An array instead of a scalar
        for ``method='all'``.

    See Also
    --------
    boxcox, boxcox_llf, boxcox_normplot

    Examples
    --------
    >>> from scipy import stats
    >>> import matplotlib.pyplot as plt
    >>> np.random.seed(1234)  # make this example reproducible

    Generate some data and determine optimal ``lmbda`` in various ways:

    >>> x = stats.loggamma.rvs(5, size=30) + 5
    >>> y, lmax_mle = stats.boxcox(x)
    >>> lmax_pearsonr = stats.boxcox_normmax(x)

    >>> lmax_mle
    7.177...
    >>> lmax_pearsonr
    7.916...
    >>> stats.boxcox_normmax(x, method='all')
    array([ 7.91667384,  7.17718692])

    >>> fig = plt.figure()
    >>> ax = fig.add_subplot(111)
    >>> stats.boxcox_normplot(x, -10, 10, plot=ax)
    >>> ax.axvline(lmax_mle, color='r')
    >>> ax.axvline(lmax_pearsonr, color='g', ls='--')

    >>> plt.show()


def boxcox_normplot(x, la, lb, plot=None, N=<NUM_LIT>):

x = np.asarray(x)<EOL>if x.size == <NUM_LIT:0>:<EOL><INDENT>return x<EOL><DEDENT>if lb <= la:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>lmbdas = np.linspace(la, lb, num=N)<EOL>ppcc = lmbdas * <NUM_LIT:0.0><EOL>for i, val in enumerate(lmbdas):<EOL><INDENT>z = boxcox(x, lmbda=val)<EOL>_, r2 = probplot(z, dist='<STR_LIT>', fit=True)<EOL>ppcc[i] = r2[-<NUM_LIT:1>]<EOL><DEDENT>if plot is not None:<EOL><INDENT>plot.plot(lmbdas, ppcc, '<STR_LIT:x>')<EOL>try:<EOL><INDENT>if hasattr(plot, '<STR_LIT>'):<EOL><INDENT>plot.set_title('<STR_LIT>')<EOL>plot.set_ylabel('<STR_LIT>')<EOL>plot.set_xlabel('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>plot.title('<STR_LIT>')<EOL>plot.ylabel('<STR_LIT>')<EOL>plot.xlabel('<STR_LIT>')<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return lmbdas, ppcc<EOL>

Compute parameters for a Box-Cox normality plot, optionally show it.

    A Box-Cox normality plot shows graphically what the best transformation
    parameter is to use in `boxcox` to obtain a distribution that is close
    to normal.

    Parameters
    ----------
    x : array_like
        Input array.
    la, lb : scalar
        The lower and upper bounds for the ``lmbda`` values to pass to `boxcox`
        for Box-Cox transformations.  These are also the limits of the
        horizontal axis of the plot if that is generated.
    plot : object, optional
        If given, plots the quantiles and least squares fit.
        `plot` is an object that has to have methods "plot" and "text".
        The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
        or a custom object with the same methods.
        Default is None, which means that no plot is created.
    N : int, optional
        Number of points on the horizontal axis (equally distributed from
        `la` to `lb`).

    Returns
    -------
    lmbdas : ndarray
        The ``lmbda`` values for which a Box-Cox transform was done.
    ppcc : ndarray
        Probability Plot Correlelation Coefficient, as obtained from `probplot`
        when fitting the Box-Cox transformed input `x` against a normal
        distribution.

    See Also
    --------
    probplot, boxcox, boxcox_normmax, boxcox_llf, ppcc_max

    Notes
    -----
    Even if `plot` is given, the figure is not shown or saved by
    `boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')``
    should be used after calling `probplot`.

    Examples
    --------
    >>> from scipy import stats
    >>> import matplotlib.pyplot as plt

    Generate some non-normally distributed data, and create a Box-Cox plot:

    >>> x = stats.loggamma.rvs(5, size=500) + 5
    >>> fig = plt.figure()
    >>> ax = fig.add_subplot(111)
    >>> stats.boxcox_normplot(x, -20, 20, plot=ax)

    Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in
    the same plot:

    >>> _, maxlog = stats.boxcox(x)
    >>> ax.axvline(maxlog, color='r')

    >>> plt.show()


N = len(x)<EOL>if N < <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if a is None:<EOL><INDENT>a = zeros(N,'<STR_LIT:f>')<EOL>init = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>if len(a) != N//<NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>init = <NUM_LIT:1><EOL><DEDENT>y = sort(x)<EOL>a, w, pw, ifault = statlib.swilk(y, a[:N//<NUM_LIT:2>], init)<EOL>if ifault not in [<NUM_LIT:0>,<NUM_LIT:2>]:<EOL><INDENT>warnings.warn(str(ifault))<EOL><DEDENT>if N > <NUM_LIT>:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT>if reta:<EOL><INDENT>return w, pw, a<EOL><DEDENT>else:<EOL><INDENT>return w, pw<EOL><DEDENT>

Perform the Shapiro-Wilk test for normality.

The Shapiro-Wilk test tests the null hypothesis that the
data was drawn from a normal distribution.

Parameters
----------
x : array_like
    Array of sample data.
a : array_like, optional
    Array of internal parameters used in the calculation.  If these
    are not given, they will be computed internally.  If x has length
    n, then a must have length n/2.
reta : bool, optional
    Whether or not to return the internally computed a values.  The
    default is False.

Returns
-------
W : float
    The test statistic.
p-value : float
    The p-value for the hypothesis test.
a : array_like, optional
    If `reta` is True, then these are the internally computed "a"
    values that may be passed into this function on future calls.

See Also
--------
anderson : The Anderson-Darling test for normality

References
----------
.. [1] http://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm


if dist not in ['<STR_LIT>','<STR_LIT>','<STR_LIT>','<STR_LIT>','<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>y = sort(x)<EOL>xbar = np.mean(x, axis=<NUM_LIT:0>)<EOL>N = len(y)<EOL>if dist == '<STR_LIT>':<EOL><INDENT>s = np.std(x, ddof=<NUM_LIT:1>, axis=<NUM_LIT:0>)<EOL>w = (y-xbar)/s<EOL>z = distributions.norm.cdf(w)<EOL>sig = array([<NUM_LIT:15>,<NUM_LIT:10>,<NUM_LIT:5>,<NUM_LIT>,<NUM_LIT:1>])<EOL>critical = around(_Avals_norm / (<NUM_LIT:1.0> + <NUM_LIT>/N - <NUM_LIT>/N/N),<NUM_LIT:3>)<EOL><DEDENT>elif dist == '<STR_LIT>':<EOL><INDENT>w = y / xbar<EOL>z = distributions.expon.cdf(w)<EOL>sig = array([<NUM_LIT:15>,<NUM_LIT:10>,<NUM_LIT:5>,<NUM_LIT>,<NUM_LIT:1>])<EOL>critical = around(_Avals_expon / (<NUM_LIT:1.0> + <NUM_LIT>/N),<NUM_LIT:3>)<EOL><DEDENT>elif dist == '<STR_LIT>':<EOL><INDENT>def rootfunc(ab,xj,N):<EOL><INDENT>a,b = ab<EOL>tmp = (xj-a)/b<EOL>tmp2 = exp(tmp)<EOL>val = [sum(<NUM_LIT:1.0>/(<NUM_LIT:1>+tmp2),axis=<NUM_LIT:0>)-<NUM_LIT:0.5>*N,<EOL>sum(tmp*(<NUM_LIT:1.0>-tmp2)/(<NUM_LIT:1>+tmp2),axis=<NUM_LIT:0>)+N]<EOL>return array(val)<EOL><DEDENT>sol0 = array([xbar,np.std(x, ddof=<NUM_LIT:1>, axis=<NUM_LIT:0>)])<EOL>sol = optimize.fsolve(rootfunc,sol0,args=(x,N),xtol=<NUM_LIT>)<EOL>w = (y-sol[<NUM_LIT:0>])/sol[<NUM_LIT:1>]<EOL>z = distributions.logistic.cdf(w)<EOL>sig = array([<NUM_LIT>,<NUM_LIT:10>,<NUM_LIT:5>,<NUM_LIT>,<NUM_LIT:1>,<NUM_LIT:0.5>])<EOL>critical = around(_Avals_logistic / (<NUM_LIT:1.0>+<NUM_LIT>/N),<NUM_LIT:3>)<EOL><DEDENT>else:  <EOL><INDENT>xbar, s = distributions.gumbel_l.fit(x)<EOL>w = (y-xbar)/s<EOL>z = distributions.gumbel_l.cdf(w)<EOL>sig = array([<NUM_LIT>,<NUM_LIT:10>,<NUM_LIT:5>,<NUM_LIT>,<NUM_LIT:1>])<EOL>critical = around(_Avals_gumbel / (<NUM_LIT:1.0> + <NUM_LIT>/sqrt(N)),<NUM_LIT:3>)<EOL><DEDENT>i = arange(<NUM_LIT:1>,N+<NUM_LIT:1>)<EOL>S = sum((<NUM_LIT:2>*i-<NUM_LIT:1.0>)/N*(log(z)+log(<NUM_LIT:1>-z[::-<NUM_LIT:1>])),axis=<NUM_LIT:0>)<EOL>A2 = -N-S<EOL>return A2, critical, sig<EOL>

Anderson-Darling test for data coming from a particular distribution

The Anderson-Darling test is a modification of the Kolmogorov-
Smirnov test `kstest` for the null hypothesis that a sample is
drawn from a population that follows a particular distribution.
For the Anderson-Darling test, the critical values depend on
which distribution is being tested against.  This function works
for normal, exponential, logistic, or Gumbel (Extreme Value
Type I) distributions.

Parameters
----------
x : array_like
    array of sample data
dist : {'norm','expon','logistic','gumbel','extreme1'}, optional
    the type of distribution to test against.  The default is 'norm'
    and 'extreme1' is a synonym for 'gumbel'

Returns
-------
A2 : float
    The Anderson-Darling test statistic
critical : list
    The critical values for this distribution
sig : list
    The significance levels for the corresponding critical values
    in percents.  The function returns critical values for a
    differing set of significance levels depending on the
    distribution that is being tested against.

Notes
-----
Critical values provided are for the following significance levels:

normal/exponenential
    15%, 10%, 5%, 2.5%, 1%
logistic
    25%, 10%, 5%, 2.5%, 1%, 0.5%
Gumbel
    25%, 10%, 5%, 2.5%, 1%

If A2 is larger than these critical values then for the corresponding
significance level, the null hypothesis that the data come from the
chosen distribution can be rejected.

References
----------
.. [1] http://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
.. [2] Stephens, M. A. (1974). EDF Statistics for Goodness of Fit and
       Some Comparisons, Journal of the American Statistical Association,
       Vol. 69, pp. 730-737.
.. [3] Stephens, M. A. (1976). Asymptotic Results for Goodness-of-Fit
       Statistics with Unknown Parameters, Annals of Statistics, Vol. 4,
       pp. 357-369.
.. [4] Stephens, M. A. (1977). Goodness of Fit for the Extreme Value
       Distribution, Biometrika, Vol. 64, pp. 583-588.
.. [5] Stephens, M. A. (1977). Goodness of Fit with Special Reference
       to Tests for Exponentiality , Technical Report No. 262,
       Department of Statistics, Stanford University, Stanford, CA.
.. [6] Stephens, M. A. (1979). Tests of Fit for the Logistic Distribution
       Based on the Empirical Distribution Function, Biometrika, Vol. 66,
       pp. 591-595.


def _anderson_ksamp_midrank(samples, Z, Zstar, k, n, N):

A2akN = <NUM_LIT:0.><EOL>Z_ssorted_left = Z.searchsorted(Zstar, '<STR_LIT:left>')<EOL>if N == Zstar.size:<EOL><INDENT>lj = <NUM_LIT:1.><EOL><DEDENT>else:<EOL><INDENT>lj = Z.searchsorted(Zstar, '<STR_LIT:right>') - Z_ssorted_left<EOL><DEDENT>Bj = Z_ssorted_left + lj / <NUM_LIT><EOL>for i in arange(<NUM_LIT:0>, k):<EOL><INDENT>s = np.sort(samples[i])<EOL>s_ssorted_right = s.searchsorted(Zstar, side='<STR_LIT:right>')<EOL>Mij = s_ssorted_right.astype(np.float)<EOL>fij = s_ssorted_right - s.searchsorted(Zstar, '<STR_LIT:left>')<EOL>Mij -= fij / <NUM_LIT><EOL>inner = lj / float(N) * (N * Mij - Bj * n[i])**<NUM_LIT:2> /(Bj * (N - Bj) - N * lj / <NUM_LIT>)<EOL>A2akN += inner.sum() / n[i]<EOL><DEDENT>A2akN *= (N - <NUM_LIT:1.>) / N<EOL>return A2akN<EOL>

Compute A2akN equation 7 of Scholz and Stephens.

Parameters
----------
samples : sequence of 1-D array_like
    Array of sample arrays.
Z : array_like
    Sorted array of all observations.
Zstar : array_like
    Sorted array of unique observations.
k : int
    Number of samples.
n : array_like
    Number of observations in each sample.
N : int
    Total number of observations.

Returns
-------
A2aKN : float
    The A2aKN statistics of Scholz and Stephens 1987.


def _anderson_ksamp_right(samples, Z, Zstar, k, n, N):

A2kN = <NUM_LIT:0.><EOL>lj = Z.searchsorted(Zstar[:-<NUM_LIT:1>], '<STR_LIT:right>') - Z.searchsorted(Zstar[:-<NUM_LIT:1>],<EOL>'<STR_LIT:left>')<EOL>Bj = lj.cumsum()<EOL>for i in arange(<NUM_LIT:0>, k):<EOL><INDENT>s = np.sort(samples[i])<EOL>Mij = s.searchsorted(Zstar[:-<NUM_LIT:1>], side='<STR_LIT:right>')<EOL>inner = lj / float(N) * (N * Mij - Bj * n[i])**<NUM_LIT:2> / (Bj * (N - Bj))<EOL>A2kN += inner.sum() / n[i]<EOL><DEDENT>return A2kN<EOL>

Compute A2akN equation 6 of Scholz & Stephens.

Parameters
----------
samples : sequence of 1-D array_like
    Array of sample arrays.
Z : array_like
    Sorted array of all observations.
Zstar : array_like
    Sorted array of unique observations.
k : int
    Number of samples.
n : array_like
    Number of observations in each sample.
N : int
    Total number of observations.

Returns
-------
A2KN : float
    The A2KN statistics of Scholz and Stephens 1987.


k = len(samples)<EOL>if (k < <NUM_LIT:2>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>samples = list(map(np.asarray, samples))<EOL>Z = np.sort(np.hstack(samples))<EOL>N = Z.size<EOL>Zstar = np.unique(Z)<EOL>if Zstar.size < <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>n = np.array([sample.size for sample in samples])<EOL>if any(n == <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if midrank:<EOL><INDENT>A2kN = _anderson_ksamp_midrank(samples, Z, Zstar, k, n, N)<EOL><DEDENT>else:<EOL><INDENT>A2kN = _anderson_ksamp_right(samples, Z, Zstar, k, n, N)<EOL><DEDENT>h = (<NUM_LIT:1.> / arange(<NUM_LIT:1>, N)).sum()<EOL>H = (<NUM_LIT:1.> / n).sum()<EOL>g = <NUM_LIT:0><EOL>for l in arange(<NUM_LIT:1>, N-<NUM_LIT:1>):<EOL><INDENT>inner = np.array([<NUM_LIT:1.> / ((N - l) * m) for m in arange(l+<NUM_LIT:1>, N)])<EOL>g += inner.sum()<EOL><DEDENT>a = (<NUM_LIT:4>*g - <NUM_LIT:6>) * (k - <NUM_LIT:1>) + (<NUM_LIT:10> - <NUM_LIT:6>*g)*H<EOL>b = (<NUM_LIT:2>*g - <NUM_LIT:4>)*k**<NUM_LIT:2> + <NUM_LIT:8>*h*k + (<NUM_LIT:2>*g - <NUM_LIT>*h - <NUM_LIT:4>)*H - <NUM_LIT:8>*h + <NUM_LIT:4>*g - <NUM_LIT:6><EOL>c = (<NUM_LIT:6>*h + <NUM_LIT:2>*g - <NUM_LIT:2>)*k**<NUM_LIT:2> + (<NUM_LIT:4>*h - <NUM_LIT:4>*g + <NUM_LIT:6>)*k + (<NUM_LIT:2>*h - <NUM_LIT:6>)*H + <NUM_LIT:4>*h<EOL>d = (<NUM_LIT:2>*h + <NUM_LIT:6>)*k**<NUM_LIT:2> - <NUM_LIT:4>*h*k<EOL>sigmasq = (a*N**<NUM_LIT:3> + b*N**<NUM_LIT:2> + c*N + d) / ((N - <NUM_LIT:1.>) * (N - <NUM_LIT>) * (N - <NUM_LIT>))<EOL>m = k - <NUM_LIT:1><EOL>A2 = (A2kN - m) / math.sqrt(sigmasq)<EOL>b0 = np.array([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>b1 = np.array([-<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>b2 = np.array([-<NUM_LIT>, -<NUM_LIT>, -<NUM_LIT>, -<NUM_LIT>, -<NUM_LIT>])<EOL>critical = b0 + b1 / math.sqrt(m) + b2 / m<EOL>pf = np.polyfit(critical, log(np.array([<NUM_LIT>, <NUM_LIT:0.1>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>])), <NUM_LIT:2>)<EOL>if A2 < critical.min() or A2 > critical.max():<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT>p = math.exp(np.polyval(pf, A2))<EOL>return A2, critical, p<EOL>

The Anderson-Darling test for k-samples.

    The k-sample Anderson-Darling test is a modification of the
    one-sample Anderson-Darling test. It tests the null hypothesis
    that k-samples are drawn from the same population without having
    to specify the distribution function of that population. The
    critical values depend on the number of samples.

    Parameters
    ----------
    samples : sequence of 1-D array_like
        Array of sample data in arrays.
    midrank : bool, optional
        Type of Anderson-Darling test which is computed. Default
        (True) is the midrank test applicable to continuous and
        discrete populations. If False, the right side empirical
        distribution is used.

    Returns
    -------
    A2 : float
        Normalized k-sample Anderson-Darling test statistic.
    critical : array
        The critical values for significance levels 25%, 10%, 5%, 2.5%, 1%.
    p : float
        An approximate significance level at which the null hypothesis for the
        provided samples can be rejected.

    Raises
    ------
    ValueError
        If less than 2 samples are provided, a sample is empty, or no
        distinct observations are in the samples.

    See Also
    --------
    ks_2samp : 2 sample Kolmogorov-Smirnov test
    anderson : 1 sample Anderson-Darling test

    Notes
    -----
    [1]_ Defines three versions of the k-sample Anderson-Darling test:
    one for continuous distributions and two for discrete
    distributions, in which ties between samples may occur. The
    default of this routine is to compute the version based on the
    midrank empirical distribution function. This test is applicable
    to continuous and discrete data. If midrank is set to False, the
    right side empirical distribution is used for a test for discrete
    data. According to [1]_, the two discrete test statistics differ
    only slightly if a few collisions due to round-off errors occur in
    the test not adjusted for ties between samples.

    .. versionadded:: 0.14.0

    References
    ----------
    .. [1] Scholz, F. W and Stephens, M. A. (1987), K-Sample
           Anderson-Darling Tests, Journal of the American Statistical
           Association, Vol. 82, pp. 918-924.

    Examples
    --------
    >>> from scipy import stats
    >>> np.random.seed(314159)

    The null hypothesis that the two random samples come from the same
    distribution can be rejected at the 5% level because the returned
    test value is greater than the critical value for 5% (1.961) but
    not at the 2.5% level. The interpolation gives an approximate
    significance level of 3.1%:

    >>> stats.anderson_ksamp([np.random.normal(size=50),
    ... np.random.normal(loc=0.5, size=30)])
    (2.4615796189876105,
      array([ 0.325,  1.226,  1.961,  2.718,  3.752]),
      0.03134990135800783)

    The null hypothesis cannot be rejected for three samples from an
    identical distribution. The approximate p-value (87%) has to be
    computed by extrapolation and may not be very accurate:

    >>> stats.anderson_ksamp([np.random.normal(size=50),
    ... np.random.normal(size=30), np.random.normal(size=20)])
    (-0.73091722665244196,
      array([ 0.44925884,  1.3052767 ,  1.9434184 ,  2.57696569,  3.41634856]),
      0.8789283903979661)


x,y = asarray(x),asarray(y)<EOL>n = len(x)<EOL>m = len(y)<EOL>if m < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if n < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>N = m+n<EOL>xy = r_[x,y]  <EOL>rank = stats.rankdata(xy)<EOL>symrank = amin(array((rank,N-rank+<NUM_LIT:1>)),<NUM_LIT:0>)<EOL>AB = sum(symrank[:n],axis=<NUM_LIT:0>)<EOL>uxy = unique(xy)<EOL>repeats = (len(uxy) != len(xy))<EOL>exact = ((m < <NUM_LIT>) and (n < <NUM_LIT>) and not repeats)<EOL>if repeats and ((m < <NUM_LIT>) or (n < <NUM_LIT>)):<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT>if exact:<EOL><INDENT>astart, a1, ifault = statlib.gscale(n,m)<EOL>ind = AB-astart<EOL>total = sum(a1,axis=<NUM_LIT:0>)<EOL>if ind < len(a1)/<NUM_LIT>:<EOL><INDENT>cind = int(ceil(ind))<EOL>if (ind == cind):<EOL><INDENT>pval = <NUM_LIT>*sum(a1[:cind+<NUM_LIT:1>],axis=<NUM_LIT:0>)/total<EOL><DEDENT>else:<EOL><INDENT>pval = <NUM_LIT>*sum(a1[:cind],axis=<NUM_LIT:0>)/total<EOL><DEDENT><DEDENT>else:<EOL><INDENT>find = int(floor(ind))<EOL>if (ind == floor(ind)):<EOL><INDENT>pval = <NUM_LIT>*sum(a1[find:],axis=<NUM_LIT:0>)/total<EOL><DEDENT>else:<EOL><INDENT>pval = <NUM_LIT>*sum(a1[find+<NUM_LIT:1>:],axis=<NUM_LIT:0>)/total<EOL><DEDENT><DEDENT>return AB, min(<NUM_LIT:1.0>,pval)<EOL><DEDENT>if N % <NUM_LIT:2>:  <EOL><INDENT>mnAB = n*(N+<NUM_LIT:1.0>)**<NUM_LIT:2> / <NUM_LIT> / N<EOL>varAB = n*m*(N+<NUM_LIT:1.0>)*(<NUM_LIT:3>+N**<NUM_LIT:2>)/(<NUM_LIT>*N**<NUM_LIT:2>)<EOL><DEDENT>else:<EOL><INDENT>mnAB = n*(N+<NUM_LIT>)/<NUM_LIT><EOL>varAB = m*n*(N+<NUM_LIT:2>)*(N-<NUM_LIT>)/<NUM_LIT>/(N-<NUM_LIT:1.0>)<EOL><DEDENT>if repeats:   <EOL><INDENT>fac = sum(symrank**<NUM_LIT:2>,axis=<NUM_LIT:0>)<EOL>if N % <NUM_LIT:2>:  <EOL><INDENT>varAB = m*n*(<NUM_LIT:16>*N*fac-(N+<NUM_LIT:1>)**<NUM_LIT:4>)/(<NUM_LIT> * N**<NUM_LIT:2> * (N-<NUM_LIT:1>))<EOL><DEDENT>else:  <EOL><INDENT>varAB = m*n*(<NUM_LIT:16>*fac-N*(N+<NUM_LIT:2>)**<NUM_LIT:2>)/(<NUM_LIT> * N * (N-<NUM_LIT:1>))<EOL><DEDENT><DEDENT>z = (AB - mnAB)/sqrt(varAB)<EOL>pval = distributions.norm.sf(abs(z)) * <NUM_LIT><EOL>return AB, pval<EOL>

Perform the Ansari-Bradley test for equal scale parameters

The Ansari-Bradley test is a non-parametric test for the equality
of the scale parameter of the distributions from which two
samples were drawn.

Parameters
----------
x, y : array_like
    arrays of sample data

Returns
-------
AB : float
    The Ansari-Bradley test statistic
p-value : float
    The p-value of the hypothesis test

See Also
--------
fligner : A non-parametric test for the equality of k variances
mood : A non-parametric test for the equality of two scale parameters

Notes
-----
The p-value given is exact when the sample sizes are both less than
55 and there are no ties, otherwise a normal approximation for the
p-value is used.

References
----------
.. [1] Sprent, Peter and N.C. Smeeton.  Applied nonparametric statistical
       methods.  3rd ed. Chapman and Hall/CRC. 2001.  Section 5.8.2.


k = len(args)<EOL>if k < <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>Ni = zeros(k)<EOL>ssq = zeros(k,'<STR_LIT:d>')<EOL>for j in range(k):<EOL><INDENT>Ni[j] = len(args[j])<EOL>ssq[j] = np.var(args[j], ddof=<NUM_LIT:1>)<EOL><DEDENT>Ntot = sum(Ni,axis=<NUM_LIT:0>)<EOL>spsq = sum((Ni-<NUM_LIT:1>)*ssq,axis=<NUM_LIT:0>)/(<NUM_LIT:1.0>*(Ntot-k))<EOL>numer = (Ntot*<NUM_LIT:1.0>-k)*log(spsq) - sum((Ni-<NUM_LIT:1.0>)*log(ssq),axis=<NUM_LIT:0>)<EOL>denom = <NUM_LIT:1.0> + (<NUM_LIT:1.0>/(<NUM_LIT:3>*(k-<NUM_LIT:1>)))*((sum(<NUM_LIT:1.0>/(Ni-<NUM_LIT:1.0>),axis=<NUM_LIT:0>))-<NUM_LIT:1.0>/(Ntot-k))<EOL>T = numer / denom<EOL>pval = distributions.chi2.sf(T,k-<NUM_LIT:1>)  <EOL>return T, pval<EOL>

Perform Bartlett's test for equal variances

Bartlett's test tests the null hypothesis that all input samples
are from populations with equal variances.  For samples
from significantly non-normal populations, Levene's test
`levene` is more robust.

Parameters
----------
sample1, sample2,... : array_like
    arrays of sample data.  May be different lengths.

Returns
-------
T : float
    The test statistic.
p-value : float
    The p-value of the test.

References
----------
.. [1]  http://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm

.. [2]  Snedecor, George W. and Cochran, William G. (1989), Statistical
          Methods, Eighth Edition, Iowa State University Press.


<EOL>center = '<STR_LIT>'<EOL>proportiontocut = <NUM_LIT><EOL>for kw, value in kwds.items():<EOL><INDENT>if kw not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>" % kw)<EOL><DEDENT>if kw == '<STR_LIT>':<EOL><INDENT>center = value<EOL><DEDENT>else:<EOL><INDENT>proportiontocut = value<EOL><DEDENT><DEDENT>k = len(args)<EOL>if k < <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>Ni = zeros(k)<EOL>Yci = zeros(k, '<STR_LIT:d>')<EOL>if center not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>+ "<STR_LIT>")<EOL><DEDENT>if center == '<STR_LIT>':<EOL><INDENT>func = lambda x: np.median(x, axis=<NUM_LIT:0>)<EOL><DEDENT>elif center == '<STR_LIT>':<EOL><INDENT>func = lambda x: np.mean(x, axis=<NUM_LIT:0>)<EOL><DEDENT>else:  <EOL><INDENT>args = tuple(stats.trimboth(np.sort(arg), proportiontocut)<EOL>for arg in args)<EOL>func = lambda x: np.mean(x, axis=<NUM_LIT:0>)<EOL><DEDENT>for j in range(k):<EOL><INDENT>Ni[j] = len(args[j])<EOL>Yci[j] = func(args[j])<EOL><DEDENT>Ntot = sum(Ni, axis=<NUM_LIT:0>)<EOL>Zij = [None]*k<EOL>for i in range(k):<EOL><INDENT>Zij[i] = abs(asarray(args[i])-Yci[i])<EOL><DEDENT>Zbari = zeros(k, '<STR_LIT:d>')<EOL>Zbar = <NUM_LIT:0.0><EOL>for i in range(k):<EOL><INDENT>Zbari[i] = np.mean(Zij[i], axis=<NUM_LIT:0>)<EOL>Zbar += Zbari[i]*Ni[i]<EOL><DEDENT>Zbar /= Ntot<EOL>numer = (Ntot-k) * sum(Ni*(Zbari-Zbar)**<NUM_LIT:2>, axis=<NUM_LIT:0>)<EOL>dvar = <NUM_LIT:0.0><EOL>for i in range(k):<EOL><INDENT>dvar += sum((Zij[i]-Zbari[i])**<NUM_LIT:2>, axis=<NUM_LIT:0>)<EOL><DEDENT>denom = (k-<NUM_LIT:1.0>)*dvar<EOL>W = numer / denom<EOL>pval = distributions.f.sf(W, k-<NUM_LIT:1>, Ntot-k)  <EOL>return W, pval<EOL>

Perform Levene test for equal variances.

The Levene test tests the null hypothesis that all input samples
are from populations with equal variances.  Levene's test is an
alternative to Bartlett's test `bartlett` in the case where
there are significant deviations from normality.

Parameters
----------
sample1, sample2, ... : array_like
    The sample data, possibly with different lengths
center : {'mean', 'median', 'trimmed'}, optional
    Which function of the data to use in the test.  The default
    is 'median'.
proportiontocut : float, optional
    When `center` is 'trimmed', this gives the proportion of data points
    to cut from each end. (See `scipy.stats.trim_mean`.)
    Default is 0.05.

Returns
-------
W : float
    The test statistic.
p-value : float
    The p-value for the test.

Notes
-----
Three variations of Levene's test are possible.  The possibilities
and their recommended usages are:

  * 'median' : Recommended for skewed (non-normal) distributions>
  * 'mean' : Recommended for symmetric, moderate-tailed distributions.
  * 'trimmed' : Recommended for heavy-tailed distributions.

References
----------
.. [1]  http://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm
.. [2]   Levene, H. (1960). In Contributions to Probability and Statistics:
           Essays in Honor of Harold Hotelling, I. Olkin et al. eds.,
           Stanford University Press, pp. 278-292.
.. [3]  Brown, M. B. and Forsythe, A. B. (1974), Journal of the American
          Statistical Association, 69, 364-367


<EOL>center = '<STR_LIT>'<EOL>proportiontocut = <NUM_LIT><EOL>for kw, value in kwds.items():<EOL><INDENT>if kw not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>" % kw)<EOL><DEDENT>if kw == '<STR_LIT>':<EOL><INDENT>center = value<EOL><DEDENT>else:<EOL><INDENT>proportiontocut = value<EOL><DEDENT><DEDENT>k = len(args)<EOL>if k < <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if center not in ['<STR_LIT>','<STR_LIT>','<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>+ "<STR_LIT>")<EOL><DEDENT>if center == '<STR_LIT>':<EOL><INDENT>func = lambda x: np.median(x, axis=<NUM_LIT:0>)<EOL><DEDENT>elif center == '<STR_LIT>':<EOL><INDENT>func = lambda x: np.mean(x, axis=<NUM_LIT:0>)<EOL><DEDENT>else:  <EOL><INDENT>args = tuple(stats.trimboth(arg, proportiontocut) for arg in args)<EOL>func = lambda x: np.mean(x, axis=<NUM_LIT:0>)<EOL><DEDENT>Ni = asarray([len(args[j]) for j in range(k)])<EOL>Yci = asarray([func(args[j]) for j in range(k)])<EOL>Ntot = sum(Ni, axis=<NUM_LIT:0>)<EOL>Zij = [abs(asarray(args[i]) - Yci[i]) for i in range(k)]<EOL>allZij = []<EOL>g = [<NUM_LIT:0>]<EOL>for i in range(k):<EOL><INDENT>allZij.extend(list(Zij[i]))<EOL>g.append(len(allZij))<EOL><DEDENT>ranks = stats.rankdata(allZij)<EOL>a = distributions.norm.ppf(ranks/(<NUM_LIT:2>*(Ntot + <NUM_LIT:1.0>)) + <NUM_LIT:0.5>)<EOL>Aibar = _apply_func(a, g, sum) / Ni<EOL>anbar = np.mean(a, axis=<NUM_LIT:0>)<EOL>varsq = np.var(a, axis=<NUM_LIT:0>, ddof=<NUM_LIT:1>)<EOL>Xsq = sum(Ni*(asarray(Aibar) - anbar)**<NUM_LIT>, axis=<NUM_LIT:0>)/varsq<EOL>pval = distributions.chi2.sf(Xsq, k - <NUM_LIT:1>)  <EOL>return Xsq, pval<EOL>

Perform Fligner's test for equal variances.

Fligner's test tests the null hypothesis that all input samples
are from populations with equal variances.  Fligner's test is
non-parametric in contrast to Bartlett's test `bartlett` and
Levene's test `levene`.

Parameters
----------
sample1, sample2, ... : array_like
    Arrays of sample data.  Need not be the same length.
center : {'mean', 'median', 'trimmed'}, optional
    Keyword argument controlling which function of the data is used in
    computing the test statistic.  The default is 'median'.
proportiontocut : float, optional
    When `center` is 'trimmed', this gives the proportion of data points
    to cut from each end. (See `scipy.stats.trim_mean`.)
    Default is 0.05.

Returns
-------
Xsq : float
    The test statistic.
p-value : float
    The p-value for the hypothesis test.

Notes
-----
As with Levene's test there are three variants of Fligner's test that
differ by the measure of central tendency used in the test.  See `levene`
for more information.

References
----------
.. [1] http://www.stat.psu.edu/~bgl/center/tr/TR993.ps

.. [2] Fligner, M.A. and Killeen, T.J. (1976). Distribution-free two-sample
       tests for scale. 'Journal of the American Statistical Association.'
       71(353), 210-213.


x = np.asarray(x, dtype=float)<EOL>y = np.asarray(y, dtype=float)<EOL>if axis is None:<EOL><INDENT>x = x.flatten()<EOL>y = y.flatten()<EOL>axis = <NUM_LIT:0><EOL><DEDENT>res_shape = tuple([x.shape[ax] for ax in range(len(x.shape)) if ax != axis])<EOL>if not (res_shape == tuple([y.shape[ax] for ax in range(len(y.shape)) if<EOL>ax != axis])):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>n = x.shape[axis]<EOL>m = y.shape[axis]<EOL>N = m + n<EOL>if N < <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>xy = np.concatenate((x, y), axis=axis)<EOL>if axis != <NUM_LIT:0>:<EOL><INDENT>xy = np.rollaxis(xy, axis)<EOL><DEDENT>xy = xy.reshape(xy.shape[<NUM_LIT:0>], -<NUM_LIT:1>)<EOL>all_ranks = np.zeros_like(xy)<EOL>for j in range(xy.shape[<NUM_LIT:1>]):<EOL><INDENT>all_ranks[:, j] = stats.rankdata(xy[:, j])<EOL><DEDENT>Ri = all_ranks[:n]<EOL>M = sum((Ri - (N + <NUM_LIT:1.0>) / <NUM_LIT:2>) ** <NUM_LIT:2>, axis=<NUM_LIT:0>)<EOL>mnM = n * (N * N - <NUM_LIT:1.0>) / <NUM_LIT:12><EOL>varM = m * n * (N + <NUM_LIT:1.0>) * (N + <NUM_LIT:2>) * (N - <NUM_LIT:2>) / <NUM_LIT><EOL>z = (M - mnM) / sqrt(varM)<EOL>z_pos = z > <NUM_LIT:0><EOL>pval = np.zeros_like(z)<EOL>pval[z_pos] = <NUM_LIT:2> * distributions.norm.sf(z[z_pos])<EOL>pval[~z_pos] = <NUM_LIT:2> * distributions.norm.cdf(z[~z_pos])<EOL>if res_shape == ():<EOL><INDENT>z = z[<NUM_LIT:0>]<EOL>pval = pval[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>z.shape = res_shape<EOL>pval.shape = res_shape<EOL><DEDENT>return z, pval<EOL>

Perform Mood's test for equal scale parameters.

Mood's two-sample test for scale parameters is a non-parametric
test for the null hypothesis that two samples are drawn from the
same distribution with the same scale parameter.

Parameters
----------
x, y : array_like
    Arrays of sample data.
axis: int, optional
    The axis along which the samples are tested.  `x` and `y` can be of
    different length along `axis`.
    If `axis` is None, `x` and `y` are flattened and the test is done on
    all values in the flattened arrays.

Returns
-------
z : scalar or ndarray
    The z-score for the hypothesis test.  For 1-D inputs a scalar is
    returned.
p-value : scalar ndarray
    The p-value for the hypothesis test.

See Also
--------
fligner : A non-parametric test for the equality of k variances
ansari : A non-parametric test for the equality of 2 variances
bartlett : A parametric test for equality of k variances in normal samples
levene : A parametric test for equality of k variances

Notes
-----
The data are assumed to be drawn from probability distributions ``f(x)``
and ``f(x/s) / s`` respectively, for some probability density function f.
The null hypothesis is that ``s == 1``.

For multi-dimensional arrays, if the inputs are of shapes
``(n0, n1, n2, n3)``  and ``(n0, m1, n2, n3)``, then if ``axis=1``, the
resulting z and p values will have shape ``(n0, n2, n3)``.  Note that
``n1`` and ``m1`` don't have to be equal, but the other dimensions do.

Examples
--------
>>> from scipy import stats
>>> x2 = np.random.randn(2, 45, 6, 7)
>>> x1 = np.random.randn(2, 30, 6, 7)
>>> z, p = stats.mood(x1, x2, axis=1)
>>> p.shape
(2, 6, 7)

Find the number of points where the difference in scale is not significant:

>>> (p > 0.1).sum()
74

Perform the test with different scales:

>>> x1 = np.random.randn(2, 30)
>>> x2 = np.random.randn(2, 35) * 10.0
>>> stats.mood(x1, x2, axis=1)
(array([-5.84332354, -5.6840814 ]), array([5.11694980e-09, 1.31517628e-08]))


def wilcoxon(x, y=None, zero_method="<STR_LIT>", correction=False):

if zero_method not in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if y is None:<EOL><INDENT>d = x<EOL><DEDENT>else:<EOL><INDENT>x, y = map(asarray, (x, y))<EOL>if len(x) != len(y):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>d = x-y<EOL><DEDENT>if zero_method == "<STR_LIT>":<EOL><INDENT>d = compress(not_equal(d, <NUM_LIT:0>), d, axis=-<NUM_LIT:1>)  <EOL><DEDENT>count = len(d)<EOL>if (count < <NUM_LIT:10>):<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT>r = stats.rankdata(abs(d))<EOL>r_plus = sum((d > <NUM_LIT:0>) * r, axis=<NUM_LIT:0>)<EOL>r_minus = sum((d < <NUM_LIT:0>) * r, axis=<NUM_LIT:0>)<EOL>if zero_method == "<STR_LIT>":<EOL><INDENT>r_zero = sum((d == <NUM_LIT:0>) * r, axis=<NUM_LIT:0>)<EOL>r_plus += r_zero / <NUM_LIT><EOL>r_minus += r_zero / <NUM_LIT><EOL><DEDENT>T = min(r_plus, r_minus)<EOL>mn = count*(count + <NUM_LIT:1.>) * <NUM_LIT><EOL>se = count*(count + <NUM_LIT:1.>) * (<NUM_LIT> * count + <NUM_LIT:1.>)<EOL>if zero_method == "<STR_LIT>":<EOL><INDENT>r = r[d != <NUM_LIT:0>]<EOL><DEDENT>replist, repnum = find_repeats(r)<EOL>if repnum.size != <NUM_LIT:0>:<EOL><INDENT>se -= <NUM_LIT:0.5> * (repnum * (repnum * repnum - <NUM_LIT:1>)).sum()<EOL><DEDENT>se = sqrt(se / <NUM_LIT>)<EOL>correction = <NUM_LIT:0.5> * int(bool(correction)) * np.sign(T - mn)<EOL>z = (T - mn - correction) / se<EOL>prob = <NUM_LIT> * distributions.norm.sf(abs(z))<EOL>return T, prob<EOL>

Calculate the Wilcoxon signed-rank test.

The Wilcoxon signed-rank test tests the null hypothesis that two
related paired samples come from the same distribution. In particular,
it tests whether the distribution of the differences x - y is symmetric
about zero. It is a non-parametric version of the paired T-test.

Parameters
----------
x : array_like
    The first set of measurements.
y : array_like, optional
    The second set of measurements.  If `y` is not given, then the `x`
    array is considered to be the differences between the two sets of
    measurements.
zero_method : string, {"pratt", "wilcox", "zsplit"}, optional
    "pratt":
        Pratt treatment: includes zero-differences in the ranking process
        (more conservative)
    "wilcox":
        Wilcox treatment: discards all zero-differences
    "zsplit":
        Zero rank split: just like Pratt, but spliting the zero rank
        between positive and negative ones
correction : bool, optional
    If True, apply continuity correction by adjusting the Wilcoxon rank
    statistic by 0.5 towards the mean value when computing the
    z-statistic.  Default is False.

Returns
-------
T : float
    The sum of the ranks of the differences above or below zero, whichever
    is smaller.
p-value : float
    The two-sided p-value for the test.

Notes
-----
Because the normal approximation is used for the calculations, the
samples used should be large.  A typical rule is to require that
n > 20.

References
----------
.. [1] http://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test


def circmean(samples, high=<NUM_LIT:2>*pi, low=<NUM_LIT:0>, axis=None):

samples, ang = _circfuncs_common(samples, high, low)<EOL>res = angle(np.mean(exp(<NUM_LIT>*ang), axis=axis))<EOL>mask = res < <NUM_LIT:0><EOL>if (mask.ndim > <NUM_LIT:0>):<EOL><INDENT>res[mask] += <NUM_LIT:2>*pi<EOL><DEDENT>elif mask:<EOL><INDENT>res = res + <NUM_LIT:2>*pi<EOL><DEDENT>return res*(high-low)/<NUM_LIT>/pi + low<EOL>

Compute the circular mean for samples in a range.

Parameters
----------
samples : array_like
    Input array.
high : float or int, optional
    High boundary for circular mean range.  Default is ``2*pi``.
low : float or int, optional
    Low boundary for circular mean range.  Default is 0.
axis : int, optional
    Axis along which means are computed.  The default is to compute
    the mean of the flattened array.

Returns
-------
circmean : float
    Circular mean.


def circvar(samples, high=<NUM_LIT:2>*pi, low=<NUM_LIT:0>, axis=None):

samples, ang = _circfuncs_common(samples, high, low)<EOL>res = np.mean(exp(<NUM_LIT>*ang), axis=axis)<EOL>R = abs(res)<EOL>return ((high-low)/<NUM_LIT>/pi)**<NUM_LIT:2> * <NUM_LIT:2> * log(<NUM_LIT:1>/R)<EOL>

Compute the circular variance for samples assumed to be in a range

Parameters
----------
samples : array_like
    Input array.
low : float or int, optional
    Low boundary for circular variance range.  Default is 0.
high : float or int, optional
    High boundary for circular variance range.  Default is ``2*pi``.
axis : int, optional
    Axis along which variances are computed.  The default is to compute
    the variance of the flattened array.

Returns
-------
circvar : float
    Circular variance.

Notes
-----
This uses a definition of circular variance that in the limit of small
angles returns a number close to the 'linear' variance.


def circstd(samples, high=<NUM_LIT:2>*pi, low=<NUM_LIT:0>, axis=None):

samples, ang = _circfuncs_common(samples, high, low)<EOL>res = np.mean(exp(<NUM_LIT>*ang), axis=axis)<EOL>R = abs(res)<EOL>return ((high-low)/<NUM_LIT>/pi) * sqrt(-<NUM_LIT:2>*log(R))<EOL>

Compute the circular standard deviation for samples assumed to be in the
range [low to high].

Parameters
----------
samples : array_like
    Input array.
low : float or int, optional
    Low boundary for circular standard deviation range.  Default is 0.
high : float or int, optional
    High boundary for circular standard deviation range.
    Default is ``2*pi``.
axis : int, optional
    Axis along which standard deviations are computed.  The default is
    to compute the standard deviation of the flattened array.

Returns
-------
circstd : float
    Circular standard deviation.

Notes
-----
This uses a definition of circular standard deviation that in the limit of
small angles returns a number close to the 'linear' standard deviation.


points = atleast_2d(points)<EOL>d, m = points.shape<EOL>if d != self.d:<EOL><INDENT>if d == <NUM_LIT:1> and m == self.d:<EOL><INDENT>points = reshape(points, (self.d, <NUM_LIT:1>))<EOL>m = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>" % (d,<EOL>self.d)<EOL>raise ValueError(msg)<EOL><DEDENT><DEDENT>result = zeros((m,), dtype=np.float)<EOL>if m >= self.n:<EOL><INDENT>for i in range(self.n):<EOL><INDENT>diff = self.dataset[:, i, newaxis] - points<EOL>tdiff = dot(self.inv_cov, diff)<EOL>energy = sum(diff*tdiff,axis=<NUM_LIT:0>) / <NUM_LIT><EOL>result = result + exp(-energy)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for i in range(m):<EOL><INDENT>diff = self.dataset - points[:, i, newaxis]<EOL>tdiff = dot(self.inv_cov, diff)<EOL>energy = sum(diff * tdiff, axis=<NUM_LIT:0>) / <NUM_LIT><EOL>result[i] = sum(exp(-energy), axis=<NUM_LIT:0>)<EOL><DEDENT><DEDENT>result = result / self._norm_factor<EOL>return result<EOL>

Evaluate the estimated pdf on a set of points.

        Parameters
        ----------
        points : (# of dimensions, # of points)-array
            Alternatively, a (# of dimensions,) vector can be passed in and
            treated as a single point.

        Returns
        -------
        values : (# of points,)-array
            The values at each point.

        Raises
        ------
        ValueError : if the dimensionality of the input points is different than
                     the dimensionality of the KDE.


def integrate_gaussian(self, mean, cov):

mean = atleast_1d(squeeze(mean))<EOL>cov = atleast_2d(cov)<EOL>if mean.shape != (self.d,):<EOL><INDENT>raise ValueError("<STR_LIT>" % self.d)<EOL><DEDENT>if cov.shape != (self.d, self.d):<EOL><INDENT>raise ValueError("<STR_LIT>" % self.d)<EOL><DEDENT>mean = mean[:, newaxis]<EOL>sum_cov = self.covariance + cov<EOL>diff = self.dataset - mean<EOL>tdiff = dot(linalg.inv(sum_cov), diff)<EOL>energies = sum(diff * tdiff, axis=<NUM_LIT:0>) / <NUM_LIT><EOL>result = sum(exp(-energies), axis=<NUM_LIT:0>) / sqrt(linalg.det(<NUM_LIT:2> * pi *<EOL>sum_cov)) / self.n<EOL>return result<EOL>

Multiply estimated density by a multivariate Gaussian and integrate
over the whole space.

Parameters
----------
mean : aray_like
    A 1-D array, specifying the mean of the Gaussian.
cov : array_like
    A 2-D array, specifying the covariance matrix of the Gaussian.

Returns
-------
result : scalar
    The value of the integral.

Raises
------
ValueError :
    If the mean or covariance of the input Gaussian differs from
    the KDE's dimensionality.


if self.d != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>stdev = ravel(sqrt(self.covariance))[<NUM_LIT:0>]<EOL>normalized_low = ravel((low - self.dataset) / stdev)<EOL>normalized_high = ravel((high - self.dataset) / stdev)<EOL>value = np.mean(special.ndtr(normalized_high) -<EOL>special.ndtr(normalized_low))<EOL>return value<EOL>

Computes the integral of a 1D pdf between two bounds.

Parameters
----------
low : scalar
    Lower bound of integration.
high : scalar
    Upper bound of integration.

Returns
-------
value : scalar
    The result of the integral.

Raises
------
ValueError
    If the KDE is over more than one dimension.


def integrate_box(self, low_bounds, high_bounds, maxpts=None):

if maxpts is not None:<EOL><INDENT>extra_kwds = {'<STR_LIT>': maxpts}<EOL><DEDENT>else:<EOL><INDENT>extra_kwds = {}<EOL><DEDENT>value, inform = mvn.mvnun(low_bounds, high_bounds, self.dataset,<EOL>self.covariance, **extra_kwds)<EOL>if inform:<EOL><INDENT>msg = ('<STR_LIT>' %<EOL>(self.d * <NUM_LIT:1000>))<EOL>warnings.warn(msg)<EOL><DEDENT>return value<EOL>

Computes the integral of a pdf over a rectangular interval.

        Parameters
        ----------
        low_bounds : array_like
            A 1-D array containing the lower bounds of integration.
        high_bounds : array_like
            A 1-D array containing the upper bounds of integration.
        maxpts : int, optional
            The maximum number of points to use for integration.

        Returns
        -------
        value : scalar
            The result of the integral.


if other.d != self.d:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if other.n < self.n:<EOL><INDENT>small = other<EOL>large = self<EOL><DEDENT>else:<EOL><INDENT>small = self<EOL>large = other<EOL><DEDENT>sum_cov = small.covariance + large.covariance<EOL>sum_cov_chol = linalg.cho_factor(sum_cov)<EOL>result = <NUM_LIT:0.0><EOL>for i in range(small.n):<EOL><INDENT>mean = small.dataset[:, i, newaxis]<EOL>diff = large.dataset - mean<EOL>tdiff = linalg.cho_solve(sum_cov_chol, diff)<EOL>energies = sum(diff * tdiff, axis=<NUM_LIT:0>) / <NUM_LIT><EOL>result += sum(exp(-energies), axis=<NUM_LIT:0>)<EOL><DEDENT>result /= sqrt(linalg.det(<NUM_LIT:2> * pi * sum_cov)) * large.n * small.n<EOL>return result<EOL>

Computes the integral of the product of this  kernel density estimate
with another.

Parameters
----------
other : gaussian_kde instance
    The other kde.

Returns
-------
value : scalar
    The result of the integral.

Raises
------
ValueError
    If the KDEs have different dimensionality.


if size is None:<EOL><INDENT>size = self.n<EOL><DEDENT>norm = transpose(multivariate_normal(zeros((self.d,), float),<EOL>self.covariance, size=size))<EOL>indices = randint(<NUM_LIT:0>, self.n, size=size)<EOL>means = self.dataset[:, indices]<EOL>return means + norm<EOL>

Randomly sample a dataset from the estimated pdf.

Parameters
----------
size : int, optional
    The number of samples to draw.  If not provided, then the size is
    the same as the underlying dataset.

Returns
-------
resample : (self.d, `size`) ndarray
    The sampled dataset.


if bw_method is None:<EOL><INDENT>pass<EOL><DEDENT>elif bw_method == '<STR_LIT>':<EOL><INDENT>self.covariance_factor = self.scotts_factor<EOL><DEDENT>elif bw_method == '<STR_LIT>':<EOL><INDENT>self.covariance_factor = self.silverman_factor<EOL><DEDENT>elif np.isscalar(bw_method) and not isinstance(bw_method, string_types):<EOL><INDENT>self._bw_method = '<STR_LIT>'<EOL>self.covariance_factor = lambda: bw_method<EOL><DEDENT>elif callable(bw_method):<EOL><INDENT>self._bw_method = bw_method<EOL>self.covariance_factor = lambda: self._bw_method(self)<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>""<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>self._compute_covariance()<EOL>

Compute the estimator bandwidth with given method.

        The new bandwidth calculated after a call to `set_bandwidth` is used
        for subsequent evaluations of the estimated density.

        Parameters
        ----------
        bw_method : str, scalar or callable, optional
            The method used to calculate the estimator bandwidth.  This can be
            'scott', 'silverman', a scalar constant or a callable.  If a
            scalar, this will be used directly as `kde.factor`.  If a callable,
            it should take a `gaussian_kde` instance as only parameter and
            return a scalar.  If None (default), nothing happens; the current
            `kde.covariance_factor` method is kept.

        Notes
        -----
        .. versionadded:: 0.11

        Examples
        --------
        >>> x1 = np.array([-7, -5, 1, 4, 5.])
        >>> kde = stats.gaussian_kde(x1)
        >>> xs = np.linspace(-10, 10, num=50)
        >>> y1 = kde(xs)
        >>> kde.set_bandwidth(bw_method='silverman')
        >>> y2 = kde(xs)
        >>> kde.set_bandwidth(bw_method=kde.factor / 3.)
        >>> y3 = kde(xs)

        >>> fig = plt.figure()
        >>> ax = fig.add_subplot(111)
        >>> ax.plot(x1, np.ones(x1.shape) / (4. * x1.size), 'bo',
        ...         label='Data points (rescaled)')
        >>> ax.plot(xs, y1, label='Scott (default)')
        >>> ax.plot(xs, y2, label='Silverman')
        >>> ax.plot(xs, y3, label='Const (1/3 * Silverman)')
        >>> ax.legend()
        >>> plt.show()


self.factor = self.covariance_factor()<EOL>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self._data_covariance = atleast_2d(np.cov(self.dataset, rowvar=<NUM_LIT:1>,<EOL>bias=False))<EOL>self._data_inv_cov = linalg.inv(self._data_covariance)<EOL><DEDENT>self.covariance = self._data_covariance * self.factor**<NUM_LIT:2><EOL>self.inv_cov = self._data_inv_cov / self.factor**<NUM_LIT:2><EOL>self._norm_factor = sqrt(linalg.det(<NUM_LIT:2>*pi*self.covariance)) * self.n<EOL>

Computes the covariance matrix for each Gaussian kernel using
        covariance_factor().


return self.evaluate(x)<EOL>

Evaluate the estimated pdf on a provided set of points.

Notes
-----
This is an alias for `gaussian_kde.evaluate`.  See the ``evaluate``
docstring for more details.


return np.log(self.evaluate(x))<EOL>

Evaluate the log of the estimated pdf on a provided set of points.

Notes
-----
See `gaussian_kde.evaluate` for more details; this method simply
returns ``np.log(gaussian_kde.evaluate(x))``.


v1,v2, n = futil.dfreps(arr)<EOL>return v1[:n],v2[:n]<EOL>

Find repeats and repeat counts.

Parameters
----------
arr : array_like
    Input array

Returns
-------
find_repeats : tuple
    Returns a tuple of two 1-D ndarrays.  The first ndarray are the repeats
    as sorted, unique values that are repeated in `arr`.  The second
    ndarray are the counts mapped one-to-one of the repeated values
    in the first ndarray.

Examples
--------
>>> import scipy.stats as stats
>>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5])
(array([ 2. ]), array([ 4 ], dtype=int32)

>>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]])
(array([ 4., 5.]), array([2, 2], dtype=int32))


x, axis = _chk_asarray(x, axis)<EOL>x = x.copy()<EOL>Norig = x.shape[axis]<EOL>mask = np.isnan(x)<EOL>factor = <NUM_LIT:1.0> - np.sum(mask, axis) / Norig<EOL>x[mask] = <NUM_LIT:0.0><EOL>return np.mean(x, axis) / factor<EOL>

Compute the mean over the given axis ignoring nans.

Parameters
----------
x : ndarray
    Input array.
axis : int, optional
    Axis along which the mean is computed. Default is 0, i.e. the
    first axis.

Returns
-------
m : float
    The mean of `x`, ignoring nans.

See Also
--------
nanstd, nanmedian

Examples
--------
>>> from scipy import stats
>>> a = np.linspace(0, 4, 3)
>>> a
array([ 0.,  2.,  4.])
>>> a[-1] = np.nan
>>> stats.nanmean(a)
1.0


@np.deprecate(message="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>def nanstd(x, axis=<NUM_LIT:0>, bias=False):

x, axis = _chk_asarray(x, axis)<EOL>x = x.copy()<EOL>Norig = x.shape[axis]<EOL>mask = np.isnan(x)<EOL>Nnan = np.sum(mask, axis) * <NUM_LIT:1.0><EOL>n = Norig - Nnan<EOL>x[mask] = <NUM_LIT:0.0><EOL>m1 = np.sum(x, axis) / n<EOL>if axis:<EOL><INDENT>d = x - np.expand_dims(m1, axis)<EOL><DEDENT>else:<EOL><INDENT>d = x - m1<EOL><DEDENT>d *= d<EOL>m2 = np.sum(d, axis) - m1 * m1 * Nnan<EOL>if bias:<EOL><INDENT>m2c = m2 / n<EOL><DEDENT>else:<EOL><INDENT>m2c = m2 / (n - <NUM_LIT:1.0>)<EOL><DEDENT>return np.sqrt(m2c)<EOL>

Compute the standard deviation over the given axis, ignoring nans.

Parameters
----------
x : array_like
    Input array.
axis : int or None, optional
    Axis along which the standard deviation is computed. Default is 0.
    If None, compute over the whole array `x`.
bias : bool, optional
    If True, the biased (normalized by N) definition is used. If False
    (default), the unbiased definition is used.

Returns
-------
s : float
    The standard deviation.

See Also
--------
nanmean, nanmedian

Examples
--------
>>> from scipy import stats
>>> a = np.arange(10, dtype=float)
>>> a[1:3] = np.nan
>>> np.std(a)
nan
>>> stats.nanstd(a)
2.9154759474226504
>>> stats.nanstd(a.reshape(2, 5), axis=1)
array([ 2.0817,  1.5811])
>>> stats.nanstd(a.reshape(2, 5), axis=None)
2.9154759474226504


x = arr1d.copy()<EOL>c = np.isnan(x)<EOL>s = np.where(c)[<NUM_LIT:0>]<EOL>if s.size == x.size:<EOL><INDENT>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL>return np.nan<EOL><DEDENT>elif s.size != <NUM_LIT:0>:<EOL><INDENT>enonan = x[-s.size:][~c[-s.size:]]<EOL>x[s[:enonan.size]] = enonan<EOL>x = x[:-s.size]<EOL><DEDENT>return np.median(x, overwrite_input=True)<EOL>

Private function for rank a arrays. Compute the median ignoring Nan.

    Parameters
    ----------
    arr1d : ndarray
        Input array, of rank 1.

    Results
    -------
    m : float
        The median.


x, axis = _chk_asarray(x, axis)<EOL>if x.ndim == <NUM_LIT:0>:<EOL><INDENT>return float(x.item())<EOL><DEDENT>if hasattr(np, '<STR_LIT>'):  <EOL><INDENT>return np.nanmedian(x, axis)<EOL><DEDENT>x = np.apply_along_axis(_nanmedian, axis, x)<EOL>if x.ndim == <NUM_LIT:0>:<EOL><INDENT>x = float(x.item())<EOL><DEDENT>return x<EOL>

Compute the median along the given axis ignoring nan values.

Parameters
----------
x : array_like
    Input array.
axis : int, optional
    Axis along which the median is computed. Default is 0, i.e. the
    first axis.

Returns
-------
m : float
    The median of `x` along `axis`.

See Also
--------
nanstd, nanmean, numpy.nanmedian

Examples
--------
>>> from scipy import stats
>>> a = np.array([0, 3, 1, 5, 5, np.nan])
>>> stats.nanmedian(a)
array(3.0)

>>> b = np.array([0, 3, 1, 5, 5, np.nan, 5])
>>> stats.nanmedian(b)
array(4.0)

Example with axis:

>>> c = np.arange(30.).reshape(5,6)
>>> idx = np.array([False, False, False, True, False] * 6).reshape(5,6)
>>> c[idx] = np.nan
>>> c
array([[  0.,   1.,   2.,  nan,   4.,   5.],
       [  6.,   7.,  nan,   9.,  10.,  11.],
       [ 12.,  nan,  14.,  15.,  16.,  17.],
       [ nan,  19.,  20.,  21.,  22.,  nan],
       [ 24.,  25.,  26.,  27.,  nan,  29.]])
>>> stats.nanmedian(c, axis=1)
array([  2. ,   9. ,  15. ,  20.5,  26. ])