示例#1
0
    def plot_pdf_fit(self, label=None):
        import matplotlib.pyplot as plt
        from scipy.stats import exponweib, rayleigh
        from scipy import linspace, diff

        plt.bar(self.pdf[1][:len(self.pdf[0])],
                self.pdf[0],
                width=diff(self.pdf[1]),
                label=label,
                alpha=0.5,
                color='k')

        x = linspace(0, 50, 1000)

        plt.plot(x,
                 exponweib.pdf(x,
                               a=self.weibull_params[0],
                               c=self.weibull_params[1],
                               scale=self.weibull_params[3]),
                 'b--',
                 label='Exponential Weibull pdf')
        plt.plot(x,
                 rayleigh.pdf(x, scale=self.rayleigh_params[1]),
                 'r--',
                 label='Rayleigh pdf')

        plt.title('Normalized distribution of wind speeds')
        plt.grid()
        plt.legend()
示例#2
0
def expectatedCapacityFactorFromWeibull(powerCurve,
                                        meanWindspeed=5,
                                        weibullShape=2):
    """Computes the expected capacity factor of a wind turbine based on an assumed Weibull distribution of observed wind speeds
    """
    from scipy.special import gamma
    from scipy.stats import exponweib

    # Get windspeed distribution
    lam = meanWindspeed / gamma(1 + 1 / weibullShape)
    dws = 0.001
    ws = np.arange(0, 40, dws)
    pdf = exponweib.pdf(ws, 1, weibullShape, scale=lam)

    # Estimate generation
    powerCurveInterp = splrep(powerCurve.ws, powerCurve.cf)
    gen = splev(ws, powerCurveInterp)

    # Do some "just in case" clean-up
    cutin = powerCurve.ws.min(
    )  # use the first defined windspeed as the cut in
    cutout = powerCurve.ws.max(
    )  # use the last defined windspeed as the cut out

    gen[gen < 0] = 0  # floor to zero

    gen[ws < cutin] = 0  # Drop power to zero before cutin
    gen[ws > cutout] = 0  # Drop power to zero after cutout

    # Done
    totalGen = (gen * pdf).sum() * dws
    return totalGen
示例#3
0
    def returnDistData(cls, self):
        gammaParam = gamma.fit(10**(self.data / 10))
        gammaDist = gamma.pdf(self.data, *gammaParam)

        rayleighParam = rayleigh.fit(self.data)
        rayleighDist = rayleigh.pdf(self.data, *rayleighParam)

        normParam = norm.fit(self.data)
        normDist = norm.pdf(self.data, *normParam)

        logNormParam = lognorm.fit(self.data)
        lognormDist = lognorm.pdf(self.data, *logNormParam)

        nakagamiParam = nakagami.fit(self.data)
        nakagamiDist = nakagami.pdf(self.data, *nakagamiParam)

        exponParam = expon.fit(self.data)
        exponDist = expon.pdf(self.data, *exponParam)

        exponweibParam = exponweib.fit(self.data)
        weibDist = exponweib.pdf(self.data, *exponweibParam)

        distDF = pd.DataFrame(np.column_stack([
            gammaDist, rayleighDist, normDist, lognormDist, nakagamiDist,
            exponDist, weibDist
        ]),
                              columns=[
                                  'gammaDist', 'rayleighDist', 'normDist',
                                  'lognormDist', 'nakagamiDist', 'exponDist',
                                  'weibDist'
                              ])
        self.distDF = distDF
示例#4
0
def fit_tests(features, ind=True, q=0.90, verbose=False):
    """

        Input:
          features: a dictionary like with the numerical results from the
              QC tests. For example, the gradient test values, not the
              flags, but the floats itself, like
              {'gradient': ma.array([.23, .12, .08]), 'spike': ...}
          ind: The features values positions to be considered in the fit.
              It's usefull to eliminate out of range data, or to
              restrict to a subset of the data, like in the calibration
              procedure.
          q: The lowest percentile to be considered. For example, .90
              means that only the top 10% data (i.e. percentiles higher
              than .90) are considered in the fitting.
    """
    output = {}
    for test in features:
        samp = features[test][ind & np.isfinite(features[test])]
        ind_top = samp > samp.quantile(q)
        if ind_top.any():
            param = exponweib.fit(samp[ind_top])
            output[test] = {'param': param,
                    'qlimit': samp.quantile(q)}

        if verbose is True:
            import pylab
            x = np.linspace(samp[ind_top].min(), samp[ind_top].max(), 100)
            pdf_fitted = exponweib.pdf(x, *param[:-2], loc=param[-2], scale=param[-1])
            pylab.plot(x, pdf_fitted, 'b-')
            pylab.hist(ma.array(samp[ind_top]), 100, normed=1, alpha=.3)
            pylab.title(test)
            pylab.show()

    return output
示例#5
0
    def score(x):
        """ 
    
        DOCSTRING NEEDED
        
        """
        c, r, h = unpack(x)
        s = np.log(h / roughness) / _s
        pdf = exponweib.pdf(ws, a=1, c=weibK, loc=0, scale=weibL * s)

        pc = SyntheticPowerCurve(capacity=c, rotordiam=r)
        cf = np.interp(ws, pc.ws, pc.cf)

        expectedCapFac = (cf * pdf).sum() * dws
        capex = costModel(capacity=c, hubHeight=h, rotordiam=r)
        lcoe = simpleLCOE(capex, expectedCapFac * 8760 * c)

        # Dissuade against too low specific-capacity values
        if not minSpecificCapacity is None:
            specificCapacity = 1000 * c / (np.pi * r * r / 4)
            if specificCapacity < minSpecificCapacity:
                lcoe += np.power(minSpecificCapacity - specificCapacity, 3)

        # Dissuade against too-low hub height compared to the rotor diameter
        tmp = (groundClearance + r / 2) - h
        if tmp > 0: lcoe += np.power(tmp, 3)

        # Done!
        return lcoe
示例#6
0
 def test_with_scipy(self):
     if not SP:
         raise nose.SkipTest("SciPy not installed.")
     parameters = {"alpha": 2, "k": 0.3, "loc": 1, "scale": 3}
     r = rexponweib(size=10, **parameters)
     a = exponweib.pdf(r, 2, 0.3, 1, 3)
     b = exponweib_like(r, **parameters)
     assert_almost_equal(log(a).sum(), b, 5)
	def Likelihood(self, data, hypo):
		age, alive = data
		k, lam = hypo
		if alive:
			prob = 1-exponweib.cdf(age, k, lam)
		else:
			prob = exponweib.pdf(age, k, lam)
		return prob
 def Likelihood(self, data, hypo):
     age, alive = data
     k, lam = hypo
     if alive:
         prob = 1 - exponweib.cdf(age, k, lam)
     else:
         prob = exponweib.pdf(age, k, lam)
     return prob
示例#9
0
 def test_with_scipy(self):
     if not SP:
         raise nose.SkipTest("SciPy not installed.")
     parameters = {'alpha': 2, 'k': .3, 'loc': 1, 'scale': 3}
     r = rexponweib(size=10, **parameters)
     a = exponweib.pdf(r, 2, .3, 1, 3)
     b = exponweib_like(r, **parameters)
     assert_almost_equal(log(a).sum(), b, 5)
示例#10
0
 def test_with_scipy(self):
     if not SP:
         raise nose.SkipTest("SciPy not installed.")
     parameters = {'alpha': 2, 'k': .3, 'loc': 1, 'scale': 3}
     r = rexponweib(size=10, **parameters)
     a = exponweib.pdf(r, 2, .3, 1, 3)
     b = exponweib_like(r, **parameters)
     assert_almost_equal(log(a).sum(), b, 5)
示例#11
0
 def Likelihood(self, data, hypo):
     """Determines how well a given k and lam predict the life/death of a character """
     age, alive = data
     k, lam = hypo
     if alive:
         prob = 1 - exponweib.cdf(age, k, lam)
     else:
         prob = exponweib.pdf(age, k, lam)
     return prob
	def Likelihood(self, data, hypo):
		"""Determines how well a given k and lam predict the life/death of a character """
		age, alive = data
		k, lam = hypo
		if alive:
			prob = 1-exponweib.cdf(age, k, lam)
		else:
			prob = exponweib.pdf(age, k, lam)
		return prob
示例#13
0
def test_fit_weibull(y):
    """The PDF really doesn't look like the data. Might the parameters be wrong?
    """
    a, b, loc, scale = exponweib.fit(y)
    x = linspace(0, y.max())
    pdf_fitted = exponweib.pdf(x, a, b, loc, scale)

    title("Weibull distribution: (a=%.2f,b=%.2f) loc = %.2f,  scale = %.2f" %
          (a, b, loc, scale))
    plot(x, pdf_fitted, 'r-')
    hist(y, normed=1, alpha=.3, bins=int(y.max()))
    show()
    return a, b, loc, scale
示例#14
0
def fit_weib2():
    # 生成韦伯分布数据
    sample = exponweib.rvs(a=10, c=1, scale=3, loc=0, size=1000)

    x = np.linspace(0, np.max(sample), 100)
    #拟合
    a, c, loc, scale = exponweib.fit(sample, floc=0, fa=1)
    print(a, c, loc, scale)
    y = exponweib.pdf(x, a, c, loc, scale)
    for x1, y1 in zip(x, y):
        print(x1, y1)
    plt.plot(x, y)
    plt.show()
示例#15
0
    def expected_capacity_factor_from_weibull(self,
                                              mean_wind_speed=5,
                                              weibull_shape=2):
        """
        Computes the expected average capacity factor of a wind turbine based on a Weibull distribution of wind speeds.

        Parameters
        ----------
        mean_wind_speed : int, optional
            mean wind speed at the location in m/s, by default 5

        weibull_shape : int, optional
            Weibull shape parameter, by default 2

        Returns
        -------
        numeric
            Average capacity factor

        See also
        -------
            PowerCurve.expected_capacity_factor_from_distribution

        """
        from scipy.special import gamma
        from scipy.stats import exponweib

        # Get windspeed distribution
        lam = mean_wind_speed / gamma(1 + 1 / weibull_shape)
        dws = 0.001
        ws = np.arange(0, 40, dws)
        pdf = exponweib.pdf(ws, 1, weibull_shape, scale=lam)

        # Estimate generation
        power_curveInterp = splrep(self.wind_speed, self.capacity_factor)
        gen = splev(ws, power_curveInterp)

        # Do some "just in case" clean-up
        cutin = self.wind_speed.min(
        )  # use the first defined windspeed as the cut in
        cutout = self.wind_speed.max(
        )  # use the last defined windspeed as the cut out

        gen[gen < 0] = 0  # floor to zero

        gen[ws < cutin] = 0  # Drop power to zero before cutin
        gen[ws > cutout] = 0  # Drop power to zero after cutout

        # Done
        meanCapFac = (gen * pdf).sum() * dws
        return meanCapFac
示例#16
0
    def plot_pdf_fit(self, label=None):
        import matplotlib.pyplot as plt
        from scipy.stats import exponweib, rayleigh
        from scipy import linspace, diff

        plt.bar(self.pdf[1][:len(self.pdf[0])], self.pdf[0], width=diff(self.pdf[1]), label=label, alpha=0.5, color='k')

        x = linspace(0, 50, 1000)

        plt.plot(x, exponweib.pdf(x, a=self.weibull_params[0], c=self.weibull_params[1], scale=self.weibull_params[3]),
                 'b--', label='Exponential Weibull pdf')
        plt.plot(x, rayleigh.pdf(x, scale=self.rayleigh_params[1]), 'r--', label='Rayleigh pdf')

        plt.title('Normalized distribution of wind speeds')
        plt.grid()
        plt.legend()
示例#17
0
def example_4():
    a, c = 3, 1
    data = exponweib.rvs(a, c, size=1000)
    pf = lambda ah, ch=c, d=data: -np.sum(np.log(exponweib.pdf(data, ah, ch)))
    x0 = 2
    sols = {}
    methods = ["nelder-mead", "powell", "Anneal", "BFGS", "TNC", "L-BFGS-B", "SLSQP"]
    for method in sorted(methods):
        th = {'success': False}
        while not th['success']:
            th = minimizer(x0, pf, method)
            print '{0} ({1}): {2}'.format(method, x0, th['message'])
            x0 = np.random.uniform(0, 10)
        sols[method] = th['x']
    for i, (method, sol) in enumerate(sols.iteritems()):
        print '{0}: {1}'.format(method, sol)
示例#18
0
def example_1():
    a, c = 3, 1
    xs = np.linspace(exponweib.ppf(0.01, a, c), exponweib.ppf(0.99, a, c), 100)
    l = round(max(xs) - min(xs))
    pf = lambda x: exponweib.pdf(x, a, c)

    e = 1 # step size of random-walk
    qrf = lambda x: norm.rvs(x, e)
    x0 = 2
    xhs0 = metropolis_hastings(x0, 100000, pf, qrf, None, None, False)
    xhs = prune(xhs0, l, e)

    plt.plot(xs, pf(xs), color='b', label='actual posterior')
    plt.hist(xhs, 100, color='c', normed=True, label='pruned m-h samples')
    plt.xlabel('x')
    plt.ylabel('normalized count')
    plt.legend()
    # plt.savefig('../img/example-1.png')
    plt.show()
示例#19
0
def fit_distribution(data, fit_type, x_min, x_max, n_points=1000):
    # Initialization of the variables
    param, x, cdf, pdf = [-1, -1, -1, -1]

    if fit_type == 'exponweib':
        x = np.linspace(x_min, x_max, n_points)

        # Fit data to the theoretical distribution
        param = exponweib.fit(data, 1, 1, scale=02, loc=0)
        # param = exponweib.fit(data, fa=1, floc=0)
        # param = exponweib.fit(data)

        cdf = exponweib.cdf(x, param[0], param[1], param[2], param[3])
        pdf = exponweib.pdf(x, param[0], param[1], param[2], param[3])

    elif fit_type == 'lognorm':
        x = np.linspace(x_min, x_max, n_points)

        # Fit data to the theoretical distribution
        param = lognorm.fit(data, loc=0)

        cdf = lognorm.cdf(x, param[0], param[1], param[2])
        pdf = lognorm.pdf(x, param[0], param[1], param[2])

    elif fit_type == 'norm':
        x = np.linspace(x_min, x_max, n_points)

        # Fit data to the theoretical distribution
        param = norm.fit(data, loc=0)

        cdf = norm.cdf(x, param[0], param[1])
        pdf = norm.pdf(x, param[0], param[1])

    elif fit_type == 'weibull_min':
        x = np.linspace(x_min, x_max, n_points)

        # Fit data to the theoretical distribution
        param = weibull_min.fit(data, floc=0)

        cdf = weibull_min.cdf(x, param[0], param[1], param[2])
        pdf = weibull_min.pdf(x, param[0], param[1], param[2])

    return param, x, cdf, pdf
示例#20
0
def example_2():
    a, c = 3, 1
    data = exponweib.rvs(a, c, size=1000)
    l = round(max(data) - min(data))
    pf = lambda ah, ch=c, d=data: np.sum(np.log(exponweib.pdf(data, ah, ch)))

    e = 1 # step size of random-walk
    qrf = lambda x, e=e: norm.rvs(x, e)
    x0 = 2
    ahs0 = metropolis_hastings(x0, 100000, pf, qrf)
    # ahs = ahs0
    ahs = prune(ahs0, l, e)
    print 'Generated {0} samples after pruning from {1}.'.format(len(ahs), len(ahs0))
    print min(ahs), max(ahs)

    plt.axvline(a, label='theta', color='b', linestyle='--')
    plt.hist(ahs, 100, normed=True, label='pruned m-h samples')
    plt.legend()
    # plt.savefig('../img/example-2.png')
    plt.show()
示例#21
0
def fit_tests(features, q=0.90, verbose=False):
    """

        Input:
          features: a dictionary like with the numerical results from the
              QC tests. For example, the gradient test values, not the
              flags, but the floats itself, like
              {'gradient': ma.array([.23, .12, .08]), 'spike': ...}
              It also works with a pandas.DataFrame()

          q: The lowest percentile to be considered. For example, .90
              means that only the top 10% data (i.e. percentiles higher
              than .90) are considered in the fitting.
    """
    assert (q >= 0) & (q < 1), "q must be in [0, 1)"

    output = {}
    for f in features:
        # Sample only valid values
        samp = ma.compressed(features[f][np.isfinite(features[f])])
        # Identify the percentile q
        qlimit = np.percentile(samp, 1e2 * q)
        # Restricts to the top q values
        samp = samp[samp > qlimit]
        if samp.any():
            param = exponweib.fit(samp)
            output[f] = {'param': param, 'qlimit': qlimit}

        if verbose is True:
            import pylab
            x = np.linspace(samp.min(), samp.max(), 100)
            pdf_fitted = exponweib.pdf(x,
                                       *param[:-2],
                                       loc=param[-2],
                                       scale=param[-1])
            pylab.plot(x, pdf_fitted, 'b-')
            pylab.hist(ma.array(samp), 100, normed=1, alpha=.3)
            pylab.title(f)
            pylab.show()

    return output
示例#22
0
def example_3():
    a, c = 3, 1
    data = exponweib.rvs(a, c, size=1000)
    l = round(max(data) - min(data))
    pf = lambda ah, ch=c, d=data: np.sum(np.log(exponweib.pdf(data, ah, ch)))

    d = 1.0
    Tf = lambda i: d/np.log(i+2) # cooling function

    e = 1 # step size of random-walk
    qrf = lambda x, e=e: norm.rvs(x, e)
    x0 = 2
    ahs0 = simulated_annealing(x0, 100000, pf, qrf, Tf)
    print 'Generated {0} samples. MAP estimate is {1}'.format(len(ahs0), ahs0[-1])

    plt.hist(ahs0, 100, normed=True, label='samples')
    plt.axvline(a, label='theta', color='b', linestyle='--')
    plt.axvline(ahs0[-1], label='theta-hat', color='c', linestyle='--')
    plt.xlim([2.8, 3.4])
    plt.legend()
    # plt.savefig('../img/example-3.png')
    plt.show()
示例#23
0
def fit_tests(features, ind=True, q=0.90, verbose=False):
    """

        Input:
          features: a dictionary like with the numerical results from the
              QC tests. For example, the gradient test values, not the
              flags, but the floats itself, like
              {'gradient': ma.array([.23, .12, .08]), 'spike': ...}
          ind: The features values positions to be considered in the fit.
              It's usefull to eliminate out of range data, or to
              restrict to a subset of the data, like in the calibration
              procedure.
          q: The lowest percentile to be considered. For example, .90
              means that only the top 10% data (i.e. percentiles higher
              than .90) are considered in the fitting.
    """
    output = {}
    for test in features:
        samp = features[test][ind & np.isfinite(features[test])]
        ind_top = samp > samp.quantile(q)
        if ind_top.any():
            param = exponweib.fit(samp[ind_top])
            output[test] = {'param': param, 'qlimit': samp.quantile(q)}

        if verbose is True:
            import pylab
            x = np.linspace(samp[ind_top].min(), samp[ind_top].max(), 100)
            pdf_fitted = exponweib.pdf(x,
                                       *param[:-2],
                                       loc=param[-2],
                                       scale=param[-1])
            pylab.plot(x, pdf_fitted, 'b-')
            pylab.hist(ma.array(samp[ind_top]), 100, normed=1, alpha=.3)
            pylab.title(test)
            pylab.show()

    return output
示例#24
0
from scipy.stats import exponweib
print(exponweib.pdf(2,1,3,0,4))
 def optfun(theta):
    return -np.sum(np.log(exponweib.pdf(x, 1, theta[0], scale = theta[1], loc = 0)))
示例#26
0
def fexpweib(x,a,c,s,l):
	return exponweib.pdf(x,a,c,loc=l,scale=s);
示例#27
0
#for a in np.arange(1.0,1, 1.0):
a = 1.0;
#cvals = np.linspace(1.0,3.14,10)
cvals = [1.0,1.5,1.8,2.1,3.34]
scvals = np.linspace(50.0,50.0,1)
cmapp = np.linspace(0.0,1.0,len(scvals));
colors = [ cm.jet(x) for x in cmapp ]


for i in range(len(scvals)): #np.arange(1.0,5.1, 0.5):
	sc = scvals[i]
	color = colors[i]
	for j in range(len(cvals)):
		c = cvals[j]
		x = np.linspace(0, exponweib.ppf(0.9999,a,c,scale=sc),1000)
		plt.plot(x,exponweib.pdf(x,a,c,scale=sc),color=color,alpha=0.5,label=str(c))

plt.ylim((0.0,0.028))
plt.xlim((0.0,200.0))
plt.legend();
plt.show()

exit()

def fexpweib(x,a,c,s,l):
	return exponweib.pdf(x,a,c,loc=l,scale=s);


bins = 1000;

示例#28
0
    def fitDist(self):

        n = len(self.data)

        # gamma distribution
        gammaParam = gamma.fit(self.data)
        gammaNumPar = len(gammaParam)
        gammaSum = -1 * np.sum(np.log(gamma.pdf(self.data, *gammaParam)))
        aicGamma = 2 * gammaNumPar + 2 * gammaSum + (2 * gammaNumPar *
                                                     (gammaNumPar + 1) /
                                                     (n - gammaNumPar - 1))

        # rayleigh distribution
        rayleighParam = rayleigh.fit(self.data)
        rayleighNumPar = len(rayleighParam)
        rayleighSum = -1 * np.sum(
            np.log(rayleigh.pdf(self.data, *rayleighParam)))
        aicRayleigh = 2 * rayleighNumPar + 2 * rayleighSum + (
            2 * rayleighNumPar * (rayleighNumPar + 1) /
            (n - rayleighNumPar - 1))

        # normal distribution
        normParam = norm.fit(self.data)
        normNumPar = len(normParam)
        normSum = -1 * np.sum(np.log(norm.pdf(self.data, *normParam)))
        aicNorm = 2 * normNumPar + 2 * normSum + (2 * normNumPar *
                                                  (normNumPar + 1) /
                                                  (n - normNumPar - 1))

        # LogNormal distribution
        logNormParam = lognorm.fit(self.data)
        logNormNumPar = len(logNormParam)
        logNormSum = -1 * np.sum(np.log(lognorm.pdf(self.data, *logNormParam)))
        aicLogNorm = 2 * logNormNumPar + 2 * logNormSum + (
            2 * logNormNumPar * (logNormNumPar + 1) / (n - logNormNumPar - 1))

        # Nakagami distribution
        nakagamiParam = nakagami.fit(self.data)
        nakagamiNumPar = len(nakagamiParam)
        nakagamiSum = -1 * np.sum(
            np.log(nakagami.pdf(self.data, *nakagamiParam)))
        aicNakagami = 2 * nakagamiNumPar + 2 * nakagamiSum + (
            2 * nakagamiNumPar * (nakagamiNumPar + 1) /
            (n - nakagamiNumPar - 1))

        # exponential distribution
        exponParam = expon.fit(self.data)
        exponNumPar = len(exponParam)
        exponSum = -1 * np.sum(np.log(expon.pdf(self.data, *exponParam)))
        aicExpon = 2 * exponNumPar + 2 * exponSum + (2 * exponNumPar *
                                                     (exponNumPar + 1) /
                                                     (n - exponNumPar - 1))

        # weibul distribution
        exponweibParam = exponweib.fit(self.data)
        exponweibNumPar = len(exponweibParam)
        exponweibSum = -1 * np.sum(
            np.log(exponweib.pdf(self.data, *exponweibParam)))
        aicExpWeib = 2 * exponweibNumPar + 2 * exponweibSum + (
            2 * exponweibNumPar * (exponweibNumPar + 1) /
            (n - exponweibNumPar - 1))

        return (aicGamma, aicRayleigh, aicNorm, aicLogNorm, aicNakagami,
                aicExpon, aicExpWeib)
示例#29
0
# start tensorboard
# tb = program.TensorBoard()
# tb.configure(argv=[None, '--logdir', 'checkpoints'])
# url = tb.launch()
# webbrowser.open(url)

# plot empirical distributions of MNIST and Fashion-MNIST
plot_mnist_dist()
plot_alt_dist()

# plot exemplary marginal gaussianization
# ToDo: plot_marginal_gauss causes error in gaussian_mixture_generate
if not exists(config('PATHS')['marginal_gauss']):
    x1 = np.arange(0, 3, .01)
    x2 = np.arange(-3, 3, .01)
    pdf = exponweib.pdf(
        x1, 2, 2) + randn(len(x1)) * norm.pdf(x1, loc=1, scale=.5) / 20
    pdf = (pdf - min(pdf))
    pdf /= np.sum(np.abs(pdf))
    emp = empiric(values=(x1, pdf), reconstruct=True)
    plot_marginal_gauss((x1, x2), (emp, norm), 1.5,
                        config('PATHS')['marginal_gauss'])

# prepare data
file = config('DATA')['normal_samples']
if not exists(file):
    seed(randint(10**9))
    prepare_z(file, samples=60000, dim=10)
file = config('DATA')['gaussian_mixture']
if not exists(file):
    seed(randint(10**9))
    # ToDo: numpy.linalg.LinAlgError: SVD did not converge
示例#30
0
def fit_weibull_distribution_sp(data, init_a=1, init_c=1, scale=1, loc=0):
    vals = exponweib.fit(data, init_a, init_c, scale=scale, loc=loc)
    return vals, data, exponweib.pdf(data, *vals)
def plot_fall_distributions(fallScores):

    plt.rcParams.update({'font.size': 26})
    plt.rcParams['text.usetex'] = True
    plt.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}']
    fig, axs = plt.subplots(5, 1)
    fig.set_size_inches(10, 20)
    lines = []
    bins = [[], [], [], [], []]
    y = [[], [], [], [], []]
    y2 = [[], [], [], [], []]
    fallScores[4] = [fallScores[4][i] / 0.8 for i in range(len(fallScores[4]))]

    labels = [
        r'$\mathrm{Deterministic}$', r'$\mathrm{Probabilistic-CVaR~Cost}$',
        r'$\mathrm{Probabilistic-Expected+CVaR~Cost}$',
        r'$\mathrm{Probabilistic-Expected~Cost}$',
        r'$\mathrm{No~Intervention}$'
    ]

    for i in range(5):
        # (mu, sigma) = rayleigh.fit(fallScores[i])
        prameters = exponweib.fit(fallScores[i], floc=0)
        # print(mu,sigma)
        n, bins[i], patches = axs[i].hist(fallScores[i],
                                          density=True,
                                          stacked=True,
                                          color="royalblue",
                                          bins=40,
                                          alpha=1)
        # y[i] = rayleigh.pdf(bins[i], mu, sigma)
        y2[i] = exponweib.pdf(bins[i], *prameters)
        # axs[i].plot(bins[i], y[i], "red", linewidth=3)
        axs[i].plot(bins[i], y2[i], "black", linewidth=3)

        axs[i].grid(True)
        axs[i].set_xlim(0, 17)
        axs[i].set_ylim(0, 1)
        axs[i].set_xticklabels([])
        axs[i].set_yticklabels(
            [r'$\mathrm{0.0}$', r'$\mathrm{0.5}$', r'$\mathrm{1.0}$'],
            fontsize=20)
        props = dict(boxstyle='round', facecolor='white', alpha=1)
        axs[i].text(0.7,
                    0.9,
                    labels[i],
                    transform=axs[i].transAxes,
                    fontsize=14,
                    verticalalignment='top',
                    bbox=props,
                    ha='center')

    axs[4].set_xticklabels([
        r'$\mathrm{0}$', r'$\mathrm{2.5}$', r'$\mathrm{5.0}$',
        r'$\mathrm{7.5}$', r'$\mathrm{10.0}$', r'$\mathrm{12.5}$',
        r'$\mathrm{15}$'
    ],
                           fontsize=20)
    axs[4].set_xlabel(r'$\mathrm{Fall~Score}$', fontsize=20)
    axs[2].set_ylabel(r'$\mathrm{Density}$', fontsize=20)

    plt.show()

    fig5, ax6 = plt.subplots()
    fig5.set_size_inches(15, 10)
    labels = [
        r'$\mathrm{Deterministic}$', r'$\mathrm{Probabilistic-CVaR~Cost}$',
        r'$\mathrm{Probabilistic-Expected+CVaR~Cost}$',
        r'$\mathrm{Probabilistic-Expected~Cost}$',
        r'$\mathrm{No~Intervention}$'
    ]
    colors = ['k-.', 'b--', 'r', 'b:', "k"]

    for i in range(5):
        lines.append(
            ax6.plot(bins[i], y2[i], colors[i], linewidth=3, label=labels[i]))

    # Add labels
    ax6.set_xticklabels([
        r'$\mathrm{}$', r'$\mathrm{2}$', r'$\mathrm{4}$', r'$\mathrm{6}$',
        r'$\mathrm{8}$', r'$\mathrm{10}$', r'$\mathrm{12}$', r'$\mathrm{14}$',
        r'$\mathrm{16}$'
    ],
                        fontsize=20)
    ax6.set_yticklabels([
        r'$\mathrm{0.00}$', r'$\mathrm{0.05}$', r'$\mathrm{0.10}$',
        r'$\mathrm{0.15}$', r'$\mathrm{0.20}$', r'$\mathrm{0.25}$',
        r'$\mathrm{0.30}$'
    ],
                        fontsize=20)

    ax6.set_xlabel(r'$\mathrm{Fall~Score}$', fontsize=20)
    ax6.set_ylabel(r'$\mathrm{Density}$', fontsize=20)
    ax6.legend(fontsize=20)
    ax6.grid(True)

    plt.show()
示例#32
0
def distribution(data, column, norm=True, plotWeibull=False, upperLimit=1.0, title=''):
    x = np.linspace(data[column].min(), data[column].max(), 1000)
    if plotWeibull:
        plt.plot(x, exponweib.pdf(x, *exponweib.fit(data[column], 1, 1)))
    plt.title(title)
    return plt.hist(data[column], bins=np.linspace(0, upperLimit), normed=norm, alpha=0.5);
示例#33
0
def downtime_accepted_models(D=list(), alpha=.05):
    params = list()
    params.append(uniform.fit(D))
    params.append(expon.fit(D))
    params.append(rayleigh.fit(D))
    params.append(weibull_min.fit(D))
    params.append(gamma.fit(D))
    params.append(gengamma.fit(D))
    params.append(invgamma.fit(D))
    params.append(gompertz.fit(D))
    params.append(lognorm.fit(D))
    params.append(exponweib.fit(D))

    llf_value = list()
    llf_value.append(log(product(uniform.pdf(D, *params[0]))))
    llf_value.append(log(product(expon.pdf(D, *params[1]))))
    llf_value.append(log(product(rayleigh.pdf(D, *params[2]))))
    llf_value.append(log(product(weibull_min.pdf(D, *params[3]))))
    llf_value.append(log(product(gamma.pdf(D, *params[4]))))
    llf_value.append(log(product(gengamma.pdf(D, *params[5]))))
    llf_value.append(log(product(invgamma.pdf(D, *params[6]))))
    llf_value.append(log(product(gompertz.pdf(D, *params[7]))))
    llf_value.append(log(product(lognorm.pdf(D, *params[8]))))
    llf_value.append(log(product(exponweib.pdf(D, *params[9]))))

    AIC = list()
    AIC.append(2 * len(params[0]) - 2 * llf_value[0])
    AIC.append(2 * len(params[1]) - 2 * llf_value[1])
    AIC.append(2 * len(params[2]) - 2 * llf_value[2])
    AIC.append(2 * len(params[3]) - 2 * llf_value[3])
    AIC.append(2 * len(params[4]) - 2 * llf_value[4])
    AIC.append(2 * len(params[5]) - 2 * llf_value[5])
    AIC.append(2 * len(params[6]) - 2 * llf_value[6])
    AIC.append(2 * len(params[7]) - 2 * llf_value[7])
    AIC.append(2 * len(params[8]) - 2 * llf_value[8])
    AIC.append(2 * len(params[9]) - 2 * llf_value[9])

    model = list()
    model.append(
        ["uniform", params[0],
         kstest(D, "uniform", params[0])[1], AIC[0]])
    model.append(
        ["expon", params[1],
         kstest(D, "expon", params[1])[1], AIC[1]])
    model.append(
        ["rayleigh", params[2],
         kstest(D, "rayleigh", params[2])[1], AIC[2]])
    model.append([
        "weibull_min", params[3],
        kstest(D, "weibull_min", params[3])[1], AIC[3]
    ])
    model.append(
        ["gamma", params[4],
         kstest(D, "gamma", params[4])[1], AIC[4]])
    model.append(
        ["gengamma", params[5],
         kstest(D, "gengamma", params[5])[1], AIC[5]])
    model.append(
        ["invgamma", params[6],
         kstest(D, "invgamma", params[6])[1], AIC[6]])
    model.append(
        ["gompertz", params[7],
         kstest(D, "gompertz", params[7])[1], AIC[7]])
    model.append(
        ["lognorm", params[8],
         kstest(D, "lognorm", params[8])[1], AIC[8]])
    model.append(
        ["exponweib", params[9],
         kstest(D, "exponweib", params[9])[1], AIC[9]])

    accepted_models = [i for i in model if i[2] > alpha]

    if accepted_models:
        aic_values = [i[3] for i in accepted_models]
        final_model = min(range(len(aic_values)), key=aic_values.__getitem__)
        return accepted_models, accepted_models[final_model]
    elif not accepted_models:
        aic_values = [i[3] for i in model]
        final_model = min(range(len(aic_values)), key=aic_values.__getitem__)
        return model, model[final_model]
示例#34
0
from scipy.stats import exponweib
print(exponweib.pdf(2, 1, 3, 0, 4))
示例#35
0
import scipy.stats as stat
import numpy as np
from matplotlib import pyplot as plt
"""x = np.linspace(-1, 3000, 5000)
#y = stat.norm.pdf(x)
y = stat.exponweib.pdf(x, 1.74, 500)

plt.plot(x, y, linewidth=2)
#plt.xlim(-3, 3)
#plt.ylim(-0.2, 0.7)
plt.show()

"""
from scipy.stats import exponweib

fig, ax = plt.subplots(1, 1)
a, c = 1, 1.35
mean, var, skew, kurt = exponweib.stats(a, c, moments='mvsk')
x = np.linspace(exponweib.ppf(0.01, a, c), exponweib.ppf(0.99, a, c), 100)
ax.plot(x,
        exponweib.pdf(x, a, c),
        'r-',
        lw=5,
        alpha=0.6,
        label='exponweib pdf')

plt.show()