Exemplo n.º 1
0
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 *
 * If you have any problem about this python version code, please contact: Rong Gong
 * [email protected]
 *
 *
 * If you want to refer this code, please use this article:
 *
'''

from scipy.stats import gengamma
import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 1)

a, c = 4.41623854294, 3.11930916792

r = gengamma.rvs(a, c, size=10000)

o1, o2, c1, a1 = gengamma.fit(r)

x = np.linspace(gengamma.ppf(0.01, a1, c1), gengamma.ppf(0.99, a1, c1), 100)

rv = gengamma(a1, c1)

ax.hist(r, normed=True, histtype='stepfilled', alpha=0.2)

ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')

plt.show()
Exemplo n.º 2
0
def percentile_3_moments(trA, trAsq, trAcub, proba, MaxFunEvals):
    """ percentile_3_moments returns the approximate percentiles of a normal form x'*A*x (where x is a multivariate standard normal distribution and A is a real symmetric matrix) by conserving its first 3 moments. The normal form is approximated with a generalized gamma distribution (which has 3 parameters).
		Inputs:
		- trA [1-dim numpy array of floats]: Trace of Matrix A. Several values are allowed (put them in a vector) in order to compute the percentiles of several normal forms.
		- trAsq [1-dim numpy array of floats - size=trA.size]: Trace of A^2. 
		- trAcub [1-dim numpy array of floats - size=trA.size]: Trace of A^3.
		N.B.: Remember that tr(A)=sum of the eigenvalues - Tr(A^2)=sum of squared eigenvalues - etc. It is usually quicker to compute trA, trAsq and trAcub from the eigenvalues of A.
		- proba [1-dim numpy array of floats]: the percentage at which the percentile is computed (for ex. 0.95) -> 0<=proba<=1. Several values are allowed (put them in a vector) in order to compute the percentiles at different percentages.
		- MaxFunEvals: "max_nfev" option for "least_squares" - see python help of "scipy.optimize.least_squares"
		Outputs:
		- alpha [numpy array of floats - size=trA.size] 
		- beta [numpy array of floats - size=trA.size]
		- delta [numpy array of floats - size=trA.size]
		alpha, beta and delta are the parameters of the generalized gamma distribution. More details in:
		'A General Theory on Spectral Analysis for Irregularly Sampled Time Series. I. Frequency Analysis', G. Lenoir and M. Crucifix
		- percentile [numpy array of floats - dim=(trA.size,proba.size)]: the percentiles.
		-----------------------------
		WARNING FOR EXTRA USES:
		If TrA, trAsq and trAcub are vectors, the parameters alpha, beta and delta of the generalized gamma distribution are determined for the first entry of those vectors. They are then used as a first guess for the next entry of trA, trAsq and trAcub to determine the new values of alpha, beta and delta. Etc. We thus implicitely guess that alpha, beta and delta are changing slowly when going through the values of trA, trAsq and trAcub, which is quite realistic in our case (the confidence levels slowly vary along a frequency (periodogram) or along the translation time (scalogram)).
		-----------------------------
		This is part of WAVEPAL
		(C) 2016 G. Lenoir"""

    m = trA.size
    nproba = proba.size
    percentile = np.zeros((m, nproba))
    l = 0
    while (trA[l] == 0. and trAsq[l] == 0. and trAcub[l] == 0.):
        l += 1
    g = trAsq[l] / trA[l]
    R = trA[l]**2 / trAsq[l]
    alpha0, beta0, delta0 = percentile_3_moments_first_guess(g, R)
    c0 = np.zeros(3)
    c0[0] = alpha0
    c0[1] = beta0
    c0[2] = delta0  # first guess for the first frequency
    alpha = np.zeros(m)
    beta = np.zeros(m)
    delta = np.zeros(m)
    myfun1 = lambda x: x[1] * gamma(x[0] + 1.0 / x[2]) / gamma(x[0])
    myfun2 = lambda x: x[1]**2 * gamma(x[0] + 2.0 / x[2]) / gamma(x[0])
    myfun3 = lambda x: x[1]**3 * gamma(x[0] + 3.0 / x[2]) / gamma(x[0])
    print "Root-searching for the coefficients of the generalized gamma distribution:"
    for k in trange(m):
        if (trA[k] == 0. and trAsq[k] == 0. and trAcub[k] == 0.):
            continue
        else:
            moment1 = trA[k]
            moment2 = 2.0 * trAsq[k] + trA[k]**2
            moment3 = 8.0 * trAcub[k] + 6.0 * trA[k] * trAsq[k] + trA[k]**3
            # NOTE: I must use a method which does not give negative parameters as a solution
            # => "least_squares" is suitable for that, because It allows the user to provide bounds on the parameter values
            # !!! absolute() for use with least_squares (don't forget we look for the zeros)
            F = lambda x: [
                np.absolute(myfun1(x) - moment1),
                np.absolute(myfun2(x) - moment2),
                np.absolute(myfun3(x) - moment3)
            ]
            answ = least_squares(F,
                                 c0,
                                 bounds=(0.0 * c0, 1000.0 * c0),
                                 ftol=1.e-15,
                                 xtol=1.e-09,
                                 max_nfev=MaxFunEvals)
            try:
                assert answ.status > 0
            except AssertionError:
                print "Error in percentile_3_moments.py with function least_squares"
                sys.exit(1)
            alphak = answ.x[0]
            betak = answ.x[1]
            deltak = answ.x[2]
            c0 = answ.x  # first guess for the next frequency (whose solution should be close to the current one)
            percentile[k, :] = gengamma.ppf(proba, alphak, deltak, scale=betak)
            alpha[k] = alphak
            beta[k] = betak
            delta[k] = deltak

    return alpha, beta, delta, percentile
Exemplo n.º 3
0
from scipy.stats import gengamma
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)

# Calculate a few first moments:

a, c = 4.42, -3.12
mean, var, skew, kurt = gengamma.stats(a, c, moments='mvsk')

# Display the probability density function (``pdf``):

x = np.linspace(gengamma.ppf(0.01, a, c),
                gengamma.ppf(0.99, a, c), 100)
ax.plot(x, gengamma.pdf(x, a, c),
       'r-', lw=5, alpha=0.6, label='gengamma pdf')

# Alternatively, the distribution object can be called (as a function)
# to fix the shape, location and scale parameters. This returns a "frozen"
# RV object holding the given parameters fixed.

# Freeze the distribution and display the frozen ``pdf``:

rv = gengamma(a, c)
ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')

# Check accuracy of ``cdf`` and ``ppf``:

vals = gengamma.ppf([0.001, 0.5, 0.999], a, c)
np.allclose([0.001, 0.5, 0.999], gengamma.cdf(vals, a, c))
# True
Exemplo n.º 4
0

if False or redoall:
    from scipy.stats import gengamma

    fig, axes = plt.subplots(ncols=nsamples, figsize=(_width, 0.4 * _height))

    for sample, ax in zip(samples, axes):
        vn, cent = sample

        params = np.loadtxt(datadir + "v{}params-cent_{}.dat".format(vn, cent))
        params = np.delete(params, params[:, 3].argmin(), 0)

        expparams = expvnparams(vn, cent)

        xmax = 1.3 * gengamma.ppf(0.999, *expparams)
        X = np.linspace(1e-10, xmax, 200)

        for p in params:
            ax.plot(X, gengamma.pdf(X, *p), lw=0.2, alpha=0.3)

        ax.plot(X, gengamma.pdf(X, *expparams), "k", lw=1)

        ax.xaxis.set_minor_locator(AutoMinorLocator(2))
        ax.yaxis.set_minor_locator(AutoMinorLocator(2))

        ax.set_xlim(xmax=xmax)
        if ax.is_first_col():
            ax.set_ylabel("$P(v_2)$".format(vn))
            ax.annotate("thick black line = ATLAS\nthin colored lines = model", (0.33, 0.75), xycoords="axes fraction")
 *
 * If you have any problem about this python version code, please contact: Rong Gong
 * [email protected]
 *
 *
 * If you want to refer this code, please use this article:
 *
'''

from scipy.stats import gengamma
import numpy as np
import matplotlib.pyplot as plt


fig, ax = plt.subplots(1, 1)

a, c = 4.41623854294, 3.11930916792

r = gengamma.rvs(a, c, size=10000)

o1,o2,c1,a1 = gengamma.fit(r)

x = np.linspace(gengamma.ppf(0.01, a1, c1),gengamma.ppf(0.99, a1, c1), 100)

rv = gengamma(a1, c1)

ax.hist(r, normed=True, histtype='stepfilled', alpha=0.2)

ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')

plt.show()