예제 #1
0
 def T_effect():
     strength_CB = []
     strength_MC = []
     m_arr = np.linspace(.5, 5., 30)
     for m in m_arr:
         # strengths.append(sigmac_max(l)[0])
         # print 'strentgth = ', strengths[-1]
         w_CB = np.linspace(0.0, .5, 100)
         w_MC = np.linspace(0.0, .03, 100)
         sigma_c_CB = -sigmac(
             w_CB, 1000., RV('weibull_min', shape=m, scale=0.1, loc=0.0),
             5.0)
         sigma_c_MC = -sigmac(
             w_MC, 1.0, RV('weibull_min', shape=m, scale=0.1, loc=0.0), 5.0)
         strength_CB.append(np.max(sigma_c_CB))
         strength_MC.append(np.max(sigma_c_MC))
 #         plt.plot(w_CB, sigma_c_CB, label='CB')
 #         plt.plot(w_CB, sigma_c_MC, label='MC')
 #         plt.show()
     COV = [
         np.sqrt(weibull_min(m, scale=0.1).var()) /
         weibull_min(m, scale=0.1).mean() for m in m_arr
     ]
     CB_arr = np.ones_like(np.array([strength_CB]))
     MC_arr = np.array([strength_MC]) / np.array([strength_CB])
     plt.plot(COV, CB_arr.flatten())
     plt.plot(COV, MC_arr.flatten())
     plt.ylim(0)
     plt.show()
예제 #2
0
def plotQQBivariate(vData, dPar1, dPar2, sDistribution):
    if(sDistribution == 'Weibull'):
        st.probplot(vData, dist=st.weibull_min(dPar1,dPar2), plot=plt)
    elif(sDistribution == 'Gamma'):
        st.probplot(vData, dist=st.weibull_min(dPar1,dPar2), plot=plt)
    elif(sDistribution == 'Lognormal'):
        st.probplot(vData, dist=st.lognorm(dPar2,scale=np.exp(dPar1)), plot=plt)
예제 #3
0
def filaments_ld():
    eps_fu = weibull_min(m, scale=s).ppf(np.linspace(0.001, 0.999, 50))
    for eps in eps_fu:
        plt.plot([0, eps, eps], [0, eps * Ef, 0], color='grey')
    mu_eps = weibull_min(m, scale=s).stats('m')
    plt.plot([0, mu_eps, mu_eps], [0, mu_eps * Ef, 0],
             color='black',
             lw=3,
             ls='dashed')
 def choose(self):
     if self.user_class == 'HF':
         self.name = "Log-norm"
         peak_hours_for_iat_hf = [1, 2, 3, 4, 5, 6]
         if self.hour in peak_hours_for_iat_hf:
             lognorm_shape, lognorm_scale, lognorm_location = 4.09174469261446, 1.12850165892419, 4.6875
         else:
             lognorm_shape, lognorm_scale, lognorm_location = 3.93740014906562, 0.982210300411203, 3
         return lognorm(lognorm_shape, loc=lognorm_location, scale=lognorm_scale)
     elif self.user_class == 'HO':
         self.name = "Gamma"
         peak_hours_for_iat_ho = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
         if self.hour in peak_hours_for_iat_ho:
             gamma_shape, gamma_rate, gamma_location = 1.25170029089175, 0.00178381168026473, 0.5
         else:
             gamma_shape, gamma_rate, gamma_location = 1.20448161464647, 0.00177591076721503, 0.5
         return gamma(gamma_shape, loc=gamma_location, scale=1. / gamma_rate)
     elif self.user_class == 'MF':
         self.name = "Gamma"
         peak_hours_for_iat_mf = [1, 2, 3, 4, 5, 6, 7, 22, 23]
         if self.hour in peak_hours_for_iat_mf:
             gamma_shape, gamma_rate, gamma_location = 2.20816848575484, 0.00343216949000565, 1
         else:
             gamma_shape, gamma_rate, gamma_location = 2.03011412986896, 0.00342699308280547, 1
         return gamma(gamma_shape, loc=gamma_location, scale=1. / gamma_rate)
     elif self.user_class == 'MO':
         self.name = "Gamma"
         peak_hours_for_iat_mo = [1, 2, 3, 4, 5, 6]
         if self.hour in peak_hours_for_iat_mo:
             gamma_shape, gamma_rate, gamma_location = 1.29908195595742, 0.00163527376977441, 0.5
         else:
             gamma_shape, gamma_rate, gamma_location = 1.19210494792398, 0.00170354443324898, 0.5
         return gamma(gamma_shape, loc=gamma_location, scale=1. / gamma_rate)
     elif self.user_class == 'LF':
         peak_hours_for_iat_lf = [1, 2, 3, 4, 5, 6, 7]
         if self.hour in peak_hours_for_iat_lf:
             self.name = "Gamma"
             gamma_shape, gamma_rate, gamma_location = 1.79297773527656, 0.00191590321039876, 2
             return gamma(gamma_shape, loc=gamma_location, scale=1. / gamma_rate)
         else:
             self.name = "Weibull"
             weibull_c_shape, weibull_scale, weibull_location = 1.1988117443903, 827.961760834184, 1
             return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
     elif self.user_class == 'LO':
         peak_hours_for_iat_lo = [2, 3, 4, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20]
         if self.hour in peak_hours_for_iat_lo:
             self.name = "Weibull"
             weibull_c_shape, weibull_scale, weibull_location = 0.850890858519732, 548.241539446292, 1
             return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
         else:
             self.name = "Gamma"
             gamma_shape, gamma_rate, gamma_location = 0.707816241615835, 0.00135537879658998, 1
             return gamma(gamma_shape, loc=gamma_location, scale=1. / gamma_rate)
     else:
         raise Exception('The user class %s does not exist' % self.user_class)
 def choose(self):
   if self.user_class == 'HF':
     self.name = "Log-norm"
     peak_hours_for_iat_hf = [1, 2, 3, 4, 5, 6]
     if self.hour in peak_hours_for_iat_hf:
       lognorm_shape, lognorm_scale, lognorm_location = 4.09174469261446, 1.12850165892419, 4.6875
     else:
       lognorm_shape, lognorm_scale, lognorm_location = 3.93740014906562, 0.982210300411203, 3
     return lognorm(lognorm_shape, loc = lognorm_location, scale = lognorm_scale)
   elif self.user_class == 'HO':
     self.name = "Gamma"
     peak_hours_for_iat_ho = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
     if self.hour in peak_hours_for_iat_ho:
       gamma_shape, gamma_rate, gamma_location = 1.25170029089175, 0.00178381168026473, 0.5
     else:
       gamma_shape, gamma_rate, gamma_location = 1.20448161464647, 0.00177591076721503, 0.5
     return gamma(gamma_shape, loc = gamma_location, scale = 1./gamma_rate)
   elif self.user_class == 'MF':
     self.name = "Gamma"
     peak_hours_for_iat_mf = [1, 2, 3, 4, 5, 6, 7, 22, 23]
     if self.hour in peak_hours_for_iat_mf:
       gamma_shape, gamma_rate, gamma_location = 2.20816848575484, 0.00343216949000565, 1
     else:
       gamma_shape, gamma_rate, gamma_location = 2.03011412986896, 0.00342699308280547, 1
     return gamma(gamma_shape, loc = gamma_location, scale = 1./gamma_rate)
   elif self.user_class == 'MO':
     self.name = "Gamma"
     peak_hours_for_iat_mo = [1, 2, 3, 4, 5, 6]
     if self.hour in peak_hours_for_iat_mo:
       gamma_shape, gamma_rate, gamma_location = 1.29908195595742, 0.00163527376977441, 0.5
     else:
       gamma_shape, gamma_rate, gamma_location = 1.19210494792398, 0.00170354443324898, 0.5
     return gamma(gamma_shape, loc = gamma_location, scale = 1./gamma_rate)
   elif self.user_class == 'LF':
     peak_hours_for_iat_lf = [1, 2, 3, 4, 5, 6, 7]
     if self.hour in peak_hours_for_iat_lf:
       self.name = "Gamma"
       gamma_shape, gamma_rate, gamma_location = 1.79297773527656, 0.00191590321039876, 2
       return gamma(gamma_shape, loc = gamma_location, scale = 1./gamma_rate)
     else:
       self.name = "Weibull"
       weibull_c_shape, weibull_scale, weibull_location = 1.1988117443903, 827.961760834184, 1
       return weibull_min(weibull_c_shape, loc = weibull_location, scale = weibull_scale)
   elif self.user_class == 'LO':
     peak_hours_for_iat_lo = [2, 3, 4, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20]
     if self.hour in peak_hours_for_iat_lo:
       self.name = "Weibull"
       weibull_c_shape, weibull_scale, weibull_location = 0.850890858519732, 548.241539446292, 1
       return weibull_min(weibull_c_shape, loc = weibull_location, scale = weibull_scale)
     else:
       self.name = "Gamma"
       gamma_shape, gamma_rate, gamma_location = 0.707816241615835, 0.00135537879658998, 1
       return gamma(gamma_shape, loc = gamma_location, scale = 1./gamma_rate)
   else:
     raise Exception('The user class %s does not exist' % self.user_class)
예제 #6
0
def show_continuous():
    """Show a variety of continuous distributions"""

    x = linspace(-10, 10, 201)

    # Normal distribution
    showDistribution(x, stats.norm, stats.norm(loc=2, scale=4), "Normal Distribution", "Z", "P(Z)", "")

    # Exponential distribution
    showDistribution(x, stats.expon, stats.expon(loc=-2, scale=4), "Exponential Distribution", "X", "P(X)", "")

    # Students' T-distribution
    # ... with 4, and with 10 degrees of freedom (DOF)
    plot(x, stats.norm.pdf(x), "g")
    hold(True)
    showDistribution(x, stats.t(4), stats.t(10), "T-Distribution", "X", "P(X)", ["normal", "t=4", "t=10"])

    # F-distribution
    # ... with (3,4) and (10,15) DOF
    showDistribution(x, stats.f(3, 4), stats.f(10, 15), "F-Distribution", "F", "P(F)", ["(3,4) DOF", "(10,15) DOF"])

    # Weibull distribution
    # ... with the shape parameter set to 1 and 2
    # Don't worry that in Python it is called "weibull_min": the "weibull_max" is
    # simply mirrored about the origin.
    showDistribution(
        arange(0, 5, 0.02),
        stats.weibull_min(1),
        stats.weibull_min(2),
        "Weibull Distribution",
        "X",
        "P(X)",
        ["k=1", "k=2"],
        xmin=0,
        xmax=4,
    )

    # Uniform distribution
    showDistribution(x, stats.uniform, "", "Uniform Distribution", "X", "P(X)", "")

    # Logistic distribution
    showDistribution(x, stats.norm, stats.logistic, "Logistic Distribution", "X", "P(X)", ["Normal", "Logistic"])

    # Lognormal distribution
    x = logspace(-9, 1, 1001) + 1e-9
    showDistribution(x, stats.lognorm(2), "", "Lognormal Distribution", "X", "lognorm(X)", "", xmin=-0.1)

    # The log-lin plot has to be done by hand:
    plot(log(x), stats.lognorm.pdf(x, 2))
    xlim(-10, 4)
    title("Lognormal Distribution")
    xlabel("log(X)")
    ylabel("lognorm(X)")
    show()
예제 #7
0
def show_continuous():
    """Show a variety of continuous distributions"""
        
    x = linspace(-10,10,201)
    
    # Normal distribution
    showDistribution(x, stats.norm, stats.norm(loc=2, scale=4),
                     'Normal Distribution', 'Z', 'P(Z)','')
    
    # Exponential distribution
    showDistribution(x, stats.expon, stats.expon(loc=-2, scale=4),
                     'Exponential Distribution', 'X', 'P(X)','')
    
    # Students' T-distribution
    # ... with 4, and with 10 degrees of freedom (DOF)
    plot(x, stats.norm.pdf(x), 'g-.')
    hold(True)
    showDistribution(x, stats.t(4), stats.t(10),
                     'T-Distribution', 'X', 'P(X)',['normal', 't=4', 't=10'])
    
    # F-distribution
    # ... with (3,4) and (10,15) DOF
    showDistribution(x, stats.f(3,4), stats.f(10,15),
                     'F-Distribution', 'F', 'P(F)',['(3,4) DOF', '(10,15) DOF'])
    
    # Weibull distribution
    # ... with the shape parameter set to 1 and 2
    # Don't worry that in Python it is called "weibull_min": the "weibull_max" is
    # simply mirrored about the origin.
    showDistribution(arange(0,5,0.02), stats.weibull_min(1), stats.weibull_min(2),
                     'Weibull Distribution', 'X', 'P(X)',['k=1', 'k=2'], xmin=0, xmax=4)
    
    # Uniform distribution
    showDistribution(x, stats.uniform,'' ,
                     'Uniform Distribution', 'X', 'P(X)','')
    
    # Logistic distribution
    showDistribution(x, stats.norm, stats.logistic,
                     'Logistic Distribution', 'X', 'P(X)',['Normal', 'Logistic'])
    
    # Lognormal distribution
    x = logspace(-9,1,1001)+1e-9
    showDistribution(x, stats.lognorm(2), '',
                     'Lognormal Distribution', 'X', 'lognorm(X)','', xmin=-0.1)
    
    # The log-lin plot has to be done by hand:
    plot(log(x), stats.lognorm.pdf(x,2))
    xlim(-10, 4)
    title('Lognormal Distribution')
    xlabel('log(X)')
    ylabel('lognorm(X)')
    show()
예제 #8
0
def show_continuous():
    """Show a variety of continuous distributions"""
        
    x = np.linspace(-10,10,201)
    
    # Normal distribution
    showDistribution(x, stats.norm, stats.norm(loc=2, scale=4),
                     'Normal Distribution', 'Z', 'P(Z)','')
    
    # Exponential distribution
    showDistribution(x, stats.expon, stats.expon(loc=-2, scale=4),
                     'Exponential Distribution', 'X', 'P(X)','')
    
    # Students' T-distribution
    # ... with 4, and with 10 degrees of freedom (DOF)
    plt.plot(x, stats.norm.pdf(x), 'g-.')
    plt.hold(True)
    showDistribution(x, stats.t(4), stats.t(10),
                     'T-Distribution', 'X', 'P(X)',['normal', 't=4', 't=10'])
    
    # F-distribution
    # ... with (3,4) and (10,15) DOF
    showDistribution(x, stats.f(3,4), stats.f(10,15),
                     'F-Distribution', 'F', 'P(F)',['(3,4) DOF', '(10,15) DOF'])
    
    # Weibull distribution
    # ... with the shape parameter set to 1 and 2
    # Don't worry that in Python it is called "weibull_min": the "weibull_max" is
    # simply mirrored about the origin.
    showDistribution(np.arange(0,5,0.02), stats.weibull_min(1), stats.weibull_min(2),
                     'Weibull Distribution', 'X', 'P(X)',['k=1', 'k=2'], xmin=0, xmax=4)
    
    # Uniform distribution
    showDistribution(x, stats.uniform,'' ,
                     'Uniform Distribution', 'X', 'P(X)','')
    
    # Logistic distribution
    showDistribution(x, stats.norm, stats.logistic,
                     'Logistic Distribution', 'X', 'P(X)',['Normal', 'Logistic'])
    
    # Lognormal distribution
    x = np.logspace(-9,1,1001)+1e-9
    showDistribution(x, stats.lognorm(2), '',
                     'Lognormal Distribution', 'X', 'lognorm(X)','', xmin=-0.1)
    
    # The log-lin plot has to be done by hand:
    plt.plot(np.log(x), stats.lognorm.pdf(x,2))
    plt.xlim(-10, 4)
    plt.title('Lognormal Distribution')
    plt.xlabel('log(X)')
    plt.ylabel('lognorm(X)')
    plt.show()
예제 #9
0
def getMargin(comps):
    # this implementation: only Beta, Weibull and Multinomial (cat)
    mtype = comps['mtype']
    params = comps['params']
    c_nr = comps['comps_nr']
    if mtype == 'Beta':
        dists = []
        for c_id in range(c_nr):
            #labels = ['a','b']
            param = params[c_id][:2]
            dist = stt.beta(a=param[0], b=param[1])
            dists.append(dist)
    elif mtype == 'Weibull':
        dists = []
        for c_id in range(comps['comps_nr']):
            #labels = ['c','scale']
            param = [params[(p_id * c_nr) + c_id] for p_id in range(2)]
            dist = stt.weibull_min(param[0], 0., param[1])
            dists.append(dist)
    elif mtype == 'Multinomial':
        # IMPLEMENTAR
        dists = [stt.multinomial(1, params)]
    try:
        dists[0].interval(1.)
    except:
        domain = []
    else:
        domains = np.array(
            [dists[d_id].interval(1.) for d_id in range(len(dists))])
        domain_raw = [domains[:, 0].max(), domains[:, 1].min()]
        delta = 0.001 * (domain_raw[1] - domain_raw[0])
        domain = [domain_raw[0] + delta, domain_raw[1] - delta]
    return dists, domain
예제 #10
0
    def _get_weibull_dist(self, qty, mean=None, std=None, scale=1.0, shape=5.0):

        x_line = np.arange(mean - std * 4.0, mean + std * 5.0, 1 * std)

        if self.weibull_dist_method == 'double':
            _data = dweibull(shape, loc=mean, scale=std)
            y_line = _data.pdf(x_line) * qty

        if self.weibull_dist_method == 'inverted':
            _data = invweibull(shape, loc=mean, scale=std)
            y_line = _data.pdf(x_line) * qty

        if self.weibull_dist_method == 'exponential':
            _data = exponweib(scale, shape, loc=mean, scale=std)
            y_line = _data.pdf(x_line) * qty

        if self.weibull_dist_method == 'min':
            _data = weibull_min(shape, loc=mean, scale=std)
            y_line = _data.pdf(x_line) * qty

        if self.weibull_dist_method == 'max':
            _data = weibull_max(shape, loc=mean, scale=std)
            y_line = _data.pdf(x_line) * qty

        line = Line(width=1280, height=600)
        line.add(u'{0}'.format(self.spc_target), x_line, y_line, xaxis_name=u'{0}'.format(self.spc_target),
                 yaxis_name=u'数量(Quantity)',
                 line_color='rgba(0 ,255 ,127,0.5)', legend_pos='center',
                 is_smooth=True, line_width=2,
                 tooltip_tragger='axis', is_fill=True, area_color='#20B2AA', area_opacity=0.4)
        pyecharts.configure(force_js_embed=True)
        return line.render_embed()
예제 #11
0
    def bundle_comparison(w_arr, L, shape, scale, E):
        '''bundle (Weibull fibers) response for comparison with the CB model'''
        from scipy.stats import weibull_min
        sV0 = scale * (3.14159 * 0.00345**2 * L)**(1 / shape)
        eps = w_arr / L * (1. - weibull_min(shape, scale=scale).cdf(w_arr / L))
        plt.plot(w_arr / L,
                 eps * E,
                 lw=4,
                 color='red',
                 ls='dashed',
                 label='FB model')

        bundle = Reinforcement(r=0.00345,
                               tau=0.00001,
                               V_f=0.9999,
                               E_f=E,
                               xi=WeibullFibers(shape=shape, sV0=sV0),
                               n_int=50)
        ccb = CompositeCrackBridge(E_m=25e3,
                                   reinforcement_lst=[bundle],
                                   Ll=L / 2.,
                                   Lr=L / 2.)
        ccb_view.model = ccb
        eps = []
        for w in w_arr:
            ccb.w = w
            eps.append(ccb_view.sigma_c / E)
        plt.plot(w_arr / L,
                 np.array(eps) * E,
                 color='blue',
                 lw=2,
                 label='CB model')
        plt.legend(loc='best')
예제 #12
0
 def _get_random_field(self):
     if self.seed == True:
         np.random.seed(101)
     '''simulates the Gaussian random field'''
     # evaluate the eigenvalues and eigenvectors of the autocorrelation
     # matrix
     _lambda, phi = self.eigenvalues
     # simulation points from 0 to 1 with an equidistant step for the LHS
     randsim = linspace(0, 1, len(self.xgrid) + 1) - 0.5 / (len(self.xgrid))
     randsim = randsim[1:]
     # shuffling points for the simulation
     shuffle(randsim)
     # matrix containing standard Gauss distributed random numbers
     xi = transpose(
         ones((self.nsim, len(self.xgrid))) * array([norm().ppf(randsim)]))
     # eigenvalue matrix
     LAMBDA = eye(len(self.xgrid)) * _lambda
     # cutting out the real part
     ydata = dot(dot(phi, (LAMBDA) ** 0.5), xi).real
     if self.distr_type == 'Gauss':
         # scaling the std. distribution
         scaled_ydata = ydata * self.stdev + self.mean
     elif self.distr_type == 'Weibull':
         # setting Weibull params
         Pf = norm().cdf(ydata)
         scaled_ydata = weibull_min(
             self.shape, scale=self.scale, loc=self.loc).ppf(Pf)
     self.reevaluate = False
     rf = reshape(scaled_ydata, len(self.xgrid))
     if self.non_negative_check == True:
         if (rf < 0).any():
             raise ValueError, 'negative value(s) in random field'
     return rf
예제 #13
0
def plot_weibull_fit(data,
                     fit_results,
                     title=None,
                     x_label=None,
                     x_range=None,
                     y_range=None,
                     fig_size=(6, 5),
                     bin_width=None,
                     filename=None):
    """
    :param data: (numpy.array) observations
    :param fit_results: dictionary with keys "c", "scale" and "loc"
    :param title: title of the figure
    :param x_label: label to show on the x-axis of the histogram
    :param x_range: (tuple) x range
    :param y_range: (tuple) y range
        (the histogram shows the probability density so the upper value of y_range should be 1).
    :param fig_size: int, specify the figure size
    :param bin_width: bin width
    :param filename: filename to save the figure as
    """

    plot_fit_continuous(data=data,
                        dist=stat.weibull_min(c=fit_results['c'],
                                              scale=fit_results['scale'],
                                              loc=fit_results['loc']),
                        label='Weibull',
                        bin_width=bin_width,
                        title=title,
                        x_label=x_label,
                        x_range=x_range,
                        y_range=y_range,
                        fig_size=fig_size,
                        filename=filename)
예제 #14
0
 def weibull():
     sigma = linspace( 0, 2300., 300 )
     CDF = weibull_min( se.m_f, scale = se.s( 0.2 ) ).cdf( sigma )
     plt.plot( sigma, CDF, lw = 2, color = 'black', label = 'filament: Weibull min. distr.' )
     plt.xlabel( 'stress [$\mathrm{N/mm^2}$]', size = 'large' )
     plt.ylabel( 'prob. of failure', size = 'large' )
     plt.title( 'CDF at gauge length 200 mm', fontsize = 20 )
예제 #15
0
    def interpolate_rf(self, coords):
        '''interpolate RF values using the EOLE method
        coords = list of 1d arrays of coordinates'''
        # check consistency of dimensions
        if len(coords) != len(self.nDgrid):
            raise ValueError('point dimension differs from random field dimension')
        # create the covariance matrix
        C_matrices = [self.acor(coords_i.reshape(1, len(coords_i)) - self.nDgrid[i].reshape(len(self.nDgrid[i]),1), self.lacor_arr[i]) for i, coords_i in enumerate(coords)]
        
        C_u = 1.0
        for i, C_ui in enumerate(C_matrices):
            if i == 0:
                C_u *= C_ui
            else:
                C_u = C_u.reshape(C_u.shape[0], 1, C_u.shape[1]) * C_ui
            grid_size = 1.0
            for j in np.arange(i+1):
                grid_size *= len(self.nDgrid[j])
            C_u = C_u.reshape(grid_size,len(coords[0]))

        Lambda_Cx, Phi_Cx = self.eigenvalues
        # values interpolated in the standardized Gaussian rf 
        u = np.sum(self.generated_random_vector / np.diag(Lambda_Cx) ** 0.5 * np.dot(C_u.T, Phi_Cx), axis=1)
        if self.distr_type == 'Gauss':
            scaled_u = u * self.stdev + self.mean
        elif self.distr_type == 'Weibull':
            Pf = norm().cdf(u)
            scaled_u = weibull_min(self.shape, scale=self.scale, loc=self.loc).ppf(Pf)
        return scaled_u
예제 #16
0
def bundle_ld():
    e = np.linspace(0.0, 1.5 * s, 1000)
    plt.plot(e,
             e * Ef * (1 - weibull_min(m, scale=s).cdf(e)),
             color='black',
             lw=3)
    plt.xlim(0, 1.6 * s)
예제 #17
0
 def _get_random_field(self):
     if self.seed == True:
         np.random.seed(101)
     '''simulates the Gaussian random field'''
     # evaluate the eigenvalues and eigenvectors of the autocorrelation
     # matrix
     _lambda, phi = self.eigenvalues
     # simulation points from 0 to 1 with an equidistant step for the LHS
     randsim = linspace(0, 1, len(self.xgrid) + 1) - 0.5 / (len(self.xgrid))
     randsim = randsim[1:]
     # shuffling points for the simulation
     shuffle(randsim)
     # matrix containing standard Gauss distributed random numbers
     xi = transpose(
         ones((self.nsim, len(self.xgrid))) * array([norm().ppf(randsim)]))
     # eigenvalue matrix
     LAMBDA = eye(len(self.xgrid)) * _lambda
     # cutting out the real part
     ydata = dot(dot(phi, (LAMBDA) ** 0.5), xi).real
     if self.distr_type == 'Gauss':
         # scaling the std. distribution
         scaled_ydata = ydata * self.stdev + self.mean
     elif self.distr_type == 'Weibull':
         # setting Weibull params
         Pf = norm().cdf(ydata)
         scaled_ydata = weibull_min(
             self.shape, scale=self.scale, loc=self.loc).ppf(Pf)
     self.reevaluate = False
     rf = reshape(scaled_ydata, len(self.xgrid))
     if self.non_negative_check == True:
         if (rf < 0).any():
             raise ValueError('negative value(s) in random field')
     return rf
예제 #18
0
    def setDistObj(self):
        """ create and freeze the distribution object from the stats module with the current scale, locationa nd shape parameters """
        if self.type == 'normal':
            self.distObj = stats.norm(loc=self.loc, scale=self.scale)

        elif self.type == 'lognormal':
            self.distObj = stats.lognorm(s=self.shape,
                                         loc=self.loc,
                                         scale=self.scale)

        elif self.type == 'weibull':
            self.distObj = stats.weibull_min(c=self.shape,
                                             loc=self.loc,
                                             scale=self.scale)

        elif self.type == 'exponential':
            self.distObj = stats.expon(loc=self.loc, scale=self.scale)

        elif self.type == 'triangular':
            self.distObj = stats.triang(c=self.shape,
                                        loc=self.loc,
                                        scale=self.scale)

        elif self.type == 'uniform':
            self.distObj = stats.uniform(loc=self.loc, scale=self.scale)

        elif self.type == 'gamma':
            self.distObj = stats.gamma(a=self.shape,
                                       loc=self.loc,
                                       scale=self.scale)

        #         elif self.type == 'constant':
        #             self.value = float(settings[self.name + '_' + 'value'])

        return
예제 #19
0
    def toggle_slider_vis(self):
        if len(graphList) > 0 and None not in graphList:
            for axis in graphList:
                axis.set_visible(not axis.get_visible())
            if not graphList[0].get_visible():
                allAxes = figure.get_axes()
                for ax in allAxes:
                    if ax == maximizedAxis:
                        ax.clear()
                if toMaximizeType == 'weibull plot':
                    c = toMaximize[1]
                    x = toMaximize[2]
                    # maximizedAxis.set_xscale("log", nonposx='clip')

                    weibull = ss.weibull_min(c)
                    (quantiles, values), (slope, intercept,
                                          r) = ss.probplot(x, dist=weibull)
                    maximizedAxis.plot(values, quantiles, 'ob')
                    maximizedAxis.plot(quantiles * slope + intercept,
                                       quantiles, 'r')
                    ticks_perc = [1, 5, 10, 20, 50, 80, 90, 95, 99, 99.9]
                    ticks_quan = [
                        ss.weibull_min.ppf(i / 100., c) for i in ticks_perc
                    ]
                    maximizedAxis.yaxis.set_ticklabels(
                        ticks_perc)  #Set the text values of the tick labels.
                    maximizedAxis.yaxis.set_ticks(ticks_quan)
                self.popup_menu.entryconfigure(0, label="Restore")
            else:
                self.popup_menu.entryconfigure(0, label="Maximize")
            maximizedAxis.set_visible(not maximizedAxis.get_visible())

        self.draw()
예제 #20
0
def weibull(data):
    shape, loc, scale = s.weibull_min.fit(data, floc=0)
    wei = s.weibull_min(shape, loc, scale)
    #    x=np.linspace(np.min(obs),np.max(obs))
    #    plt.hist(obs,normed=True,fc="none",ec="grey",label="frequency")
    #    plt.plot(x,wei.cdf(x),label="cdf")
    #    plt.plot(x,wei.pdf(x),label="pdf")
    return wei
예제 #21
0
def part1():
    sample = np.loadtxt('выборка_скорости_ветра_из_задания_2.txt')
    shape, loc, scale = sps.weibull_min.fit(sample, floc=0)
    print(shape, loc, scale)

    kstatisics, pvalue = sps.kstest(sample,
                                    sps.weibull_min(shape, scale=scale).cdf)
    print(kstatisics, pvalue)
예제 #22
0
def best_likelihood(grid, sample):
    # плотности распределения Вейбулла в точках grid
    logpdf = sps.weibull_min(c=grid[0], scale=grid[1]).logpdf
    # функции правдоподобия в точках grid
    logpdfs = logpdf(sample[:, np.newaxis, np.newaxis])
    likelihood = logpdfs.sum(axis=0)
    # индекс сетки, в котором функция правдоподобия максимальна
    argmax = cool_argmax(likelihood)
    # (k, λ)
    return grid[0][argmax], grid[1][argmax]
 def __init__(self, name,mean,stdv,epsilon=0,input_type=None,startpoint=None):
   self.type = 16
   self.distribution = {16:'Weibull'}
   self.name = name
   self.mean = mean
   self.stdv = stdv
   self.epsilon = epsilon
   self.input_type = input_type
   mean,stdv,p1,p2,p3,p4 = self.setMarginalDistribution()
   Distribution.__init__(self,name,self.type,mean,stdv,startpoint,p1,p2,p3,p4,input_type)
   self.rv = stats.weibull_min(c=p2, scale=p1-p3, loc=p3)
 def __init__(self, scale=None, shape=None):
     self.shape = shape
     self.scale = scale
     if (self.scale is not None) and (self.shape is not None):
         if ( self.shape > 0.0 ) and (self.scale > 0.0):
             self.mean = self.scale * gamma(1.0 + 1.0/self.shape)
             self.variance = self.scale**2 * ( gamma(1.0 + 2.0/self.shape) - (gamma(1.0 + 1.0/self.shape))**2  )
             self.parent = weibull_min(c =self.shape, scale=self.scale) 
             self.skewness = (gamma(1.0 + 3.0/self.shape) * self.scale**3 - 3 * self.mean * self.variance - self.mean**3  )/( np.sqrt(self.variance)**3 )
             self.bounds = np.array([0, np.inf])
             self.x_range_for_pdf = np.linspace(10**(-15), 30.0, RECURRENCE_PDF_SAMPLES)
예제 #25
0
    def _get_random_field( self ):
        '''generates an array of random matrix strength'''

        np = int( self.length / self.l_rho )
        if np <= 3:
            np = 4
        print np
        x_not_corr_points = linspace( 0, np * self.l_rho, np)
        y_not_corr_points = weibull_min( self.m, scale = self.scale_sigma_m ).ppf( rand( np ) )
        spline = InterpolatedUnivariateSpline( x_not_corr_points, y_not_corr_points )
        return spline( self.x_arr )
예제 #26
0
def simulate_data_with_births(samp_size, wei_params, start, percent_adult, max_days):
  """
  Simulate pig infection data based on a Weibull distribution and a uniform
  DOB distribution with sum percent of pigs being born before the the 
  interval of interest (adults)

  Parameters
  ----------
  samp_size : int
    Total number of hosts to sample
  wei_params : tuple
    alpha, sigma parameters of Weibull distribution
  start : pd.DateTime
    The start date of the infection season
  percent_adult : float
    Percent of pigs that are adults i.e. could be infected before the start of sampling.
  max_days : int
    The number of days from the start of the infection season at which the season
    ends

  Returns
  -------
  : DataFrame 
    Infection times, infection indicator, sample_date, dob

  """

  wei = stats.weibull_min(wei_params[0], scale=wei_params[1])

  adults = np.int(samp_size * percent_adult)
  dobs = np.append(np.repeat(0, adults), 
                  stats.uniform(loc=0, scale=max_days).rvs(size=samp_size - adults))

  upper_prob = wei.cdf(max_days)
  lower_probs = wei.cdf(dobs)
  inf_probs = upper_prob - lower_probs
  inf = stats.binom.rvs(1, inf_probs, size=len(inf_probs))

  # For each infected individual draw a toi
  unifrand = stats.uniform.rvs(loc=lower_probs, scale=upper_prob - lower_probs, 
                               size=len(inf_probs))
  toi_samp = wei.ppf(unifrand)

  sampling_time = stats.uniform(loc=dobs, scale=max_days - dobs).rvs(size=samp_size)
  eventobserved = ((sampling_time > toi_samp) & (inf == 1)).astype(np.int)
  time = np.where(eventobserved == 1, toi_samp, sampling_time)

  surv_df = pd.DataFrame(dict(time_in_season=time, infection=eventobserved == 1, 
                 sample_date = start + pd.to_timedelta(sampling_time, unit="D"),
                 dob=start + pd.to_timedelta(dobs, unit="D")))

  return(surv_df)
예제 #27
0
 def single_determ_filament():
     # SINGLE DETERMINISTIC FILAMENT
     w_arr = np.linspace(0.0, 0.5, 500)
     micro = GFRCMicro(FilamentCB=CBShortFiber)
     theta_dict = dict(tau=0.2, r=3.5e-3, E_f=70e3, le=9.0, phi=1.0, snub=0.5, xi=1e10, spall=0.5)
     for i in range(10):
         tau_i = uniform(loc=0.001, scale=0.4).rvs(1)
         xi_i = weibull_min(5.0, scale=0.025).rvs(1)
         theta_dict["xi"] = float(xi_i)
         theta_dict["tau"] = float(tau_i)
         mean_resp = micro.mean_response(w_arr, theta_dict)
         plt.plot(w_arr, mean_resp, lw=1)
     plt.show()
예제 #28
0
def test_weibull_rayleigh():

    lambda_ = 11
    rayleigh = cp.Rayleigh(scale=lambda_)
    r0, r1 = rayleigh.range()
    x = np.linspace(r0, r1, 300, endpoint=True)

    weibull = cp.Weibull(shape=2, scale=lambda_*math.sqrt(2))
    weibull_sp = stats.weibull_min(2, scale=lambda_*math.sqrt(2))

    np.testing.assert_allclose(weibull_sp.pdf(x), weibull.pdf(x), atol=1e-08)
    np.testing.assert_allclose(rayleigh.pdf(x), weibull.pdf(x), atol=1e-08)
    np.testing.assert_allclose(rayleigh.fwd(x), weibull.fwd(x), atol=1e-08)
예제 #29
0
def test_weibull_rayleigh():

    lambda_ = 11
    rayleigh = cp.Rayleigh(scale=lambda_)
    r0, r1 = rayleigh.range()
    x = np.linspace(r0, r1, 300, endpoint=True)

    weibull = cp.Weibull(shape=2, scale=lambda_ * math.sqrt(2))
    weibull_sp = stats.weibull_min(2, scale=lambda_ * math.sqrt(2))

    np.testing.assert_allclose(weibull_sp.pdf(x), weibull.pdf(x), atol=1e-08)
    np.testing.assert_allclose(rayleigh.pdf(x), weibull.pdf(x), atol=1e-08)
    np.testing.assert_allclose(rayleigh.fwd(x), weibull.fwd(x), atol=1e-08)
 def choose(self):
     self.name = "Weibull"
     if self.user_class == 'HF':
         peak_hours_for_volume_hf = [10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
         if self.hour in peak_hours_for_volume_hf:
             weibull_c_shape, weibull_scale, weibull_location = 0.819409132355671, 774639.610211396, 40
             return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
         else:
             weibull_c_shape, weibull_scale, weibull_location = 0.634477150024807, 384935.669023795, 40
             return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
     elif self.user_class == 'HO':
         peak_hours_for_volume_ho = [1, 2, 6, 7, 8, 9, 10, 14, 15, 16, 17, 18, 19, 21]
         if self.hour in peak_hours_for_volume_ho:
             weibull_c_shape, weibull_scale, weibull_location = 0.498273622342091, 476551.703412746, 30
         else:
             weibull_c_shape, weibull_scale, weibull_location = 0.507073160695169, 452332.836400453, 30
         return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
     elif self.user_class == 'MF':
         peak_hours_for_volume_mf = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
         if self.hour in peak_hours_for_volume_mf:
             weibull_c_shape, weibull_scale, weibull_location = 0.801202265360056, 13959.452422549, 37
             return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
         else:
             weibull_c_shape, weibull_scale, weibull_location = 0.797283673532605, 10657.9935943482, 33
             return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
     elif self.user_class == 'MO':
         peak_hours_for_volume_mo = [1, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
         if self.hour in peak_hours_for_volume_mo:
             weibull_c_shape, weibull_scale, weibull_location = 0.596142171663733, 31936.8353050143, 29
         else:
             weibull_c_shape, weibull_scale, weibull_location = 0.588535361156048, 26617.7612810844, 30
         return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
     elif self.user_class == 'LF':
         peak_hours_for_volume_lf = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
         if self.hour in peak_hours_for_volume_lf:
             weibull_c_shape, weibull_scale, weibull_location = 0.926450022452343, 1181.70293939011, 33
         else:
             weibull_c_shape, weibull_scale, weibull_location = 1.03429757728009, 873.579218199549, 34
         return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
     elif self.user_class == 'LO':
         peak_hours_for_volume_lo = [1, 3, 4, 19, 20, 21, 22, 23]
         if self.hour in peak_hours_for_volume_lo:
             weibull_c_shape, weibull_scale, weibull_location = 0.856409898006734, 3228.75558535546, 29
         else:
             weibull_c_shape, weibull_scale, weibull_location = 0.797856625454382, 2800.11615587819, 29
         return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
     else:
         raise Exception('The user class %s does not exist' % self.user_class)
 def choose(self):
   self.name = "Weibull"
   if self.user_class == 'HF':
     peak_hours_for_volume_hf = [10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
     if self.hour in peak_hours_for_volume_hf:
       weibull_c_shape, weibull_scale, weibull_location = 0.819409132355671, 774639.610211396, 40
       return weibull_min(weibull_c_shape, loc = weibull_location, scale = weibull_scale)
     else:
       weibull_c_shape, weibull_scale, weibull_location = 0.634477150024807, 384935.669023795, 40
       return weibull_min(weibull_c_shape, loc = weibull_location, scale = weibull_scale)
   elif self.user_class == 'HO':
     peak_hours_for_volume_ho = [1, 2, 6, 7, 8, 9, 10, 14, 15, 16, 17, 18, 19, 21]
     if self.hour in peak_hours_for_volume_ho:
       weibull_c_shape, weibull_scale, weibull_location = 0.498273622342091, 476551.703412746, 30
     else:
       weibull_c_shape, weibull_scale, weibull_location = 0.507073160695169, 452332.836400453, 30
     return weibull_min(weibull_c_shape, loc = weibull_location, scale = weibull_scale)
   elif self.user_class == 'MF':
     peak_hours_for_volume_mf = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
     if self.hour in peak_hours_for_volume_mf:
       weibull_c_shape, weibull_scale, weibull_location = 0.801202265360056, 13959.452422549, 37
       return weibull_min(weibull_c_shape, loc = weibull_location, scale = weibull_scale)
     else:
       weibull_c_shape, weibull_scale, weibull_location = 0.797283673532605, 10657.9935943482, 33
       return weibull_min(weibull_c_shape, loc = weibull_location, scale = weibull_scale)
   elif self.user_class == 'MO':
     peak_hours_for_volume_mo = [1, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
     if self.hour in peak_hours_for_volume_mo:
       weibull_c_shape, weibull_scale, weibull_location = 0.596142171663733, 31936.8353050143, 29
     else:
       weibull_c_shape, weibull_scale, weibull_location = 0.588535361156048, 26617.7612810844, 30
     return weibull_min(weibull_c_shape, loc = weibull_location, scale = weibull_scale)
   elif self.user_class == 'LF':
     peak_hours_for_volume_lf = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
     if self.hour in peak_hours_for_volume_lf:
       weibull_c_shape, weibull_scale, weibull_location = 0.926450022452343, 1181.70293939011, 33
     else:
       weibull_c_shape, weibull_scale, weibull_location = 1.03429757728009, 873.579218199549, 34
     return weibull_min(weibull_c_shape, loc = weibull_location, scale = weibull_scale)
   elif self.user_class == 'LO':
     peak_hours_for_volume_lo = [1, 3, 4, 19, 20, 21, 22, 23]
     if self.hour in peak_hours_for_volume_lo:
       weibull_c_shape, weibull_scale, weibull_location = 0.856409898006734, 3228.75558535546, 29
     else:
       weibull_c_shape, weibull_scale, weibull_location = 0.797856625454382, 2800.11615587819, 29
     return weibull_min(weibull_c_shape, loc = weibull_location, scale = weibull_scale)
   else:
     raise Exception('The user class %s does not exist' % self.user_class)
예제 #32
0
    def init_winds(self):

        for key, val in self.months.items():

            lam = val[0]
            k = val[1]

            # Creating the wind distribution for a month
            wind_distribution = weibull_min(k, loc=0, scale=lam)

            # Generate wind
            wind = wind_distribution.rvs(size=self.n)

            self.winds[key] = {"wind": wind, "dist": wind_distribution}
예제 #33
0
def KSTestCDFPlot(Stat_Stn, Stn, Setting):
    MonthlyStat = Stat_Stn["MonthlyStat"]
    Prep = Stat_Stn["PrepDF"]["P"]
    fig, axs = plt.subplots(nrows=4, ncols=3, sharex=True, sharey=True)
    m = 0
    for i in range(3):
        for j in range(4):
            Prep_m = Prep[Prep.index.month == (m + 1)].dropna()
            Prep_m = Prep_m[Prep_m != 0]
            coef1 = MonthlyStat.loc[m + 1, "exp"]
            coef2 = MonthlyStat.loc[m + 1, "gamma"]
            coef3 = MonthlyStat.loc[m + 1, "weibull"]
            coef4 = MonthlyStat.loc[m + 1, "lognorm"]
            # Plot
            ecdf = ECDF(Prep_m)
            x = np.arange(0, max(Prep_m), 0.1)
            axs[j, i].plot(x,
                           expon(coef1[0], coef1[1]).cdf(x),
                           label='exp',
                           linestyle=':')
            axs[j, i].plot(x,
                           gamma(coef2[0], coef2[1], coef2[2]).cdf(x),
                           label='gamma',
                           linestyle=':')
            axs[j, i].plot(x,
                           weibull_min(coef3[0], coef3[1], coef3[2]).cdf(x),
                           label='weibull',
                           linestyle=':')
            xlog = np.arange(min(np.log(Prep_m)), max(np.log(Prep_m)), 0.1)
            axs[j, i].plot(np.exp(xlog),
                           norm(coef4[0], coef4[1]).cdf(xlog),
                           label='lognorm',
                           linestyle=':')
            axs[j, i].plot(ecdf.x, ecdf.y, label='ecdf', color="red")
            axs[j,
                i].axvline(x=130, color="black", linestyle="--",
                           linewidth=1)  # Definition of storm defined by CWB
            axs[j, i].set_title(str(m + 1))
            axs[j, i].legend()
            m += 1
    fig.suptitle("KStest CDF " + Stn, fontsize=16)
    # Add common axis label
    fig.text(0.5, 0.04, 'Precipitation (mm)', ha='center', fontsize=14)
    fig.text(0.05, 0.5, 'CDF', va='center', rotation='vertical', fontsize=14)
    fig.set_size_inches(18.5, 10.5)
    plt.tight_layout(rect=[0.06, 0.05, 0.94,
                           0.94])  #rect : tuple (left, bottom, right, top)
    SaveFig(fig, "KStest CDF " + Stn, Setting)
    plt.show()
    return None
예제 #34
0
 def T_effect():
     strength_CB = []
     strength_MC = []
     m_arr = np.linspace(.5, 5., 30)
     for m in m_arr:
         # strengths.append(sigmac_max(l)[0])
         # print 'strentgth = ', strengths[-1]
         w_CB = np.linspace(0.0, .5, 100)
         w_MC = np.linspace(0.0, .03, 100)
         sigma_c_CB = -sigmac(w_CB, 1000., RV('weibull_min', shape=m, scale=0.1, loc=0.0), 5.0)
         sigma_c_MC = -sigmac(w_MC, 1.0, RV('weibull_min', shape=m, scale=0.1, loc=0.0), 5.0)
         strength_CB.append(np.max(sigma_c_CB))
         strength_MC.append(np.max(sigma_c_MC))
 #         plt.plot(w_CB, sigma_c_CB, label='CB')
 #         plt.plot(w_CB, sigma_c_MC, label='MC')
 #         plt.show()
     COV = [np.sqrt(weibull_min(m, scale=0.1).var()) / weibull_min(m, scale=0.1).mean() for m in m_arr]
     CB_arr = np.ones_like(np.array([strength_CB]))
     MC_arr = np.array([strength_MC]) / np.array([strength_CB])
     plt.plot(COV, CB_arr.flatten())
     plt.plot(COV, MC_arr.flatten())
     plt.ylim(0)
     plt.show()
예제 #35
0
def maximum_likelihood( data ):
    params = fmin( maxlike, [2., 5.], args = ( data ) )
    moments = weibull_min( params[0], scale = params[1], loc = 0. ).stats( 'mv' )
    print ' #### max likelihood #### '
    print 'mean = ', moments[0]
    print 'var = ', moments[1]
    print 'Weibull shape = ', params[0]
    print 'Weibull scale = ', params[1]
    # plot the Weibull fit according to maximum likelihood 
    e = linspace( 0., 0.3 * ( max( data ) - min( data ) ) + max( data ), 100 )
    #plt.plot( e, weibull_min.pdf( e, params[0], scale = params[1], loc = 0. ),
         #color = 'red', linewidth = 2, label = 'max likelihood' )
    plt.xlabel( 'Risspannung $\sigma_{c,u}$' , fontsize = 20 )
    plt.ylabel( 'PDF', fontsize = 20 )
예제 #36
0
def simulation(e_max):
    T = 2. * tau / r / Ef
    a = e_max / T
    nz = 500
    z_arr = np.linspace(a/2./nz, a - a/2./nz, nz)
    eps = e_max - T * z_arr
    dz = a/nz
    fu_arr = weibull_min(m, scale=s * (dz/L0)**(-1./m)).ppf(np.minimum(np.random.rand(nz), np.random.rand(nz)))
    max_diff = np.max(eps - fu_arr)
    if max_diff > 0.0:
        L = z_arr[np.argmax(eps - fu_arr)]
        eu = e_max - max_diff
        return L, eu
    else:
        return None, None
예제 #37
0
def get_distr_residuum( params, mean, stdev, skew ):
    print 'maan',mean,'variance',stdev
    print params
    shape = params[0]
    loc   = params[1]
    scale = params[2]
    mom_eq = stats.weibull_min( shape, loc = loc, scale = scale, moments = 'mvs' )
    moms = mom_eq.stats()
    print '---------------------------------'
    print moms
    mean_resid     = moms[0] - mean
    stdev_resid = sqrt( moms[1] ) - stdev
    skew_resid     = moms[2] - skew
    print 'mean', moms[0], 'stdev', sqrt( moms[1] )
    return ( mean_resid, stdev_resid, skew_resid )
예제 #38
0
def simulation(e_max):
    T = 2. * tau / r / Ef
    a = e_max / T
    nz = 500
    z_arr = np.linspace(a / 2. / nz, a - a / 2. / nz, nz)
    eps = e_max - T * z_arr
    dz = a / nz
    fu_arr = weibull_min(m, scale=s * (dz / L0)**(-1. / m)).ppf(
        np.minimum(np.random.rand(nz), np.random.rand(nz)))
    max_diff = np.max(eps - fu_arr)
    if max_diff > 0.0:
        L = z_arr[np.argmax(eps - fu_arr)]
        eu = e_max - max_diff
        return L, eu
    else:
        return None, None
예제 #39
0
def random_domain(w):
    Ef = 70e3
    Fxi = weibull_min(5., scale = 0.02)
    r = np.linspace(0.001, 0.005, 100)
    tau = np.linspace(0., 1., 100)
    e_arr = orthogonalize([np.arange(len(r)), np.arange(len(tau))])

    tau = tau.reshape(1, len(tau))
    r = r.reshape(len(r), 1)
    eps0 = np.sqrt(w * 2 * tau / r / Ef)
    F = Fxi.cdf(eps0)
    a = r * Ef / 2. / tau
    m.surf(e_arr[0], e_arr[1], 50 * F / np.max(F))
    m.surf(e_arr[0], e_arr[1], 50 * eps0 / np.max(eps0))
    m.surf(e_arr[0], e_arr[1], np.nan_to_num(a) / 100.)
    m.show()
예제 #40
0
def plot_distribution():
    size = 100000
    x = stats.norm(loc=42.0, scale=5).rvs(size=size)
    # (stats.norm(loc=-5, scale=1), False),
    #(stats.lognorm(scale=np.exp(-5), s=1), True)  # worse conv of higher moments
    # (stats.lognorm(scale=np.exp(-5), s=0.5), True)         # worse conv of higher moments
    # (stats.chi2(df=10), True)
    x = stats.weibull_min(c=3).rvs(size=size)  # Exponential
    # (stats.weibull_min(c=1.5), True)  # Infinite derivative at zero
    # (stats.weibull_min(c=3), True)    # Close to normal
    print("t mean ", np.mean(x))
    print("t var ", np.var(x))
    print("delka t ", len(x))
    plt.hist(x, bins=10000, normed=1)
    plt.show()
    exit()
예제 #41
0
 def __init__(self, scale=None, shape=None):
     self.shape = shape
     self.scale = scale
     if (self.scale is not None) and (self.shape is not None):
         if (self.shape > 0.0) and (self.scale > 0.0):
             self.mean = self.scale * gamma(1.0 + 1.0 / self.shape)
             self.variance = self.scale**2 * (
                 gamma(1.0 + 2.0 / self.shape) -
                 (gamma(1.0 + 1.0 / self.shape))**2)
             self.parent = weibull_min(c=self.shape, scale=self.scale)
             self.skewness = (gamma(1.0 + 3.0 / self.shape) * self.scale**3
                              - 3 * self.mean * self.variance -
                              self.mean**3) / (np.sqrt(self.variance)**3)
             self.bounds = np.array([0, np.inf])
             self.x_range_for_pdf = np.linspace(10**(-15), 30.0,
                                                RECURRENCE_PDF_SAMPLES)
예제 #42
0
def proper_truncated_weibull(upper_truncation_threshold,
                             lower_truncation_threshold,
                             k=3.353,
                             scale_factor=0.612):
    dist = weibull_min(c=k, scale=scale_factor)
    upper_value, lower_value = dist.cdf(
        (upper_truncation_threshold, lower_truncation_threshold))
    dist_range = upper_value - lower_value
    val = (dist.cdf(
        np.random.uniform(lower_truncation_threshold,
                          upper_truncation_threshold)) -
           lower_value) / dist_range
    # if val < lower_truncation_threshold or val > upper_truncation_threshold:
    #     print("Broken")
    # print(val, dist_range, upper_value, lower_value, upper_truncation_threshold, lower_truncation_threshold)
    return val
예제 #43
0
 def _get_random_field(self):
     '''simulates the Gaussian random field'''
     # evaluate the eigenvalues and eigenvectors of the autocorrelation matrix
     Lambda_C_sorted, Phi_C_sorted = self.eigenvalues
     # generate the RF with standardized Gaussian distribution
     ydata = np.dot(np.dot(Phi_C_sorted, (Lambda_C_sorted) ** 0.5), self.generated_random_vector)
     # transform the standardized Gaussian distribution
     if self.distr_type == 'Gauss':
         # scaling the std. distribution
         scaled_ydata = ydata * self.stdev + self.mean
     elif self.distr_type == 'Weibull':
         # setting Weibull params
         Pf = norm().cdf(ydata)
         scaled_ydata = weibull_min(self.shape, scale=self.scale, loc=self.loc).ppf(Pf)
     shape = tuple([len(grid_i) for grid_i in self.nDgrid])
     rf = np.reshape(scaled_ydata, shape)
     return rf
예제 #44
0
def part2():
    grid = np.linspace(0, 10, 500)
    # гистограмма
    plt.hist(sample,
             20,
             range=(grid.min(), grid.max()),
             normed=True,
             label='histogram')
    # истинная плотность
    plt.plot(grid,
             sps.weibull_min(c=k, scale=λ).pdf(grid),
             color='red',
             linewidth=2,
             alpha=0.3,
             label='true pdf')
    plt.legend()
    plt.show()
예제 #45
0
    def compute_bins(vmin, vmax, maxbin, c, k):
        """
        Finds bin boundaries with maximum `vmax`, minimum `vmin` and max bin
        size `maxbin`. Also returns the weibull cumulative distribution
        probability of each bin with shape factor `c` and scale factor `k`.

        Parameters
        ----------
        vmin : int | float
            Range minimum.
        vmax : int | float
            Range maximum.
        maxbin : int | float
            Maximum bin width.
        c : int | float
            Weibull shape factor.
        k : int | float
            Weibull scale factor.

        Returns
        -------
        int
            Number of bins.
        float
            Bin width.
        list
            List of upper boundaries of each bin.
        np.array
            Weibull probability of each bin.
        """

        num_bins = int(np.ceil((vmax - vmin) / maxbin))
        probabilities = np.zeros(num_bins)
        width = (vmax - vmin) / num_bins
        upper_bounds = []

        for i in range(num_bins):

            bot = vmin + i * width
            top = bot + width
            upper_bounds.append(top)

            dist = weibull_min(c, scale=k)
            probabilities[i] = dist.cdf(top) - dist.cdf(bot)

        return num_bins, width, upper_bounds, probabilities
예제 #46
0
 def maximum_likelihood(self, plot = True):
     data = self.data
     params = fmin(self.maxlike, np.array([10., np.mean(data)]))
     moments = weibull_min(params[0], scale = params[1], loc = 0.).stats('mv')
     print ' #### max likelihood #### '
     print 'mean = ', moments[0]
     print 'var = ', moments[1]
     print 'Weibull shape = ', params[0]
     print 'Weibull scale = ', params[1]
     #print 'scale sV0 = ', params[1] * (pi * 13.e-3**2 * self.length)**(1./params[0])
     if plot == True:
         # plot the Weibull fit according to maximum likelihood 
         e = np.linspace(0., 0.3 * (np.max(data) - np.min(data)) + np.max(data), 100)
         plt.plot(e, weibull_min.pdf(e, params[0], scale = params[1], loc = 0.),
              color = 'red', linewidth = 2, label = 'max likelihood')
         plt.xlabel('strain')
         plt.ylabel('PDF')
     return params[0], params[1]
예제 #47
0
    def bundle_comparison(w_arr, L, shape, scale, E):
        '''bundle (Weibull fibers) response for comparison with the CB model'''
        from scipy.stats import weibull_min
        eps = w_arr / L * (1. - weibull_min(shape, scale=scale).cdf(w_arr / L))
        plt.plot(w_arr / L, eps * E, lw=4, color='red', ls='dashed', label='FB model')

        bundle = Reinforcement(r=0.13, tau=0.00001, V_f=0.9999, E_f=E,
                          xi=RV('weibull_min', shape=shape, scale=scale),
                          n_int=50)
        ccb = CompositeCrackBridge(E_m=25e3,
                                   reinforcement_lst=[bundle],
                                   Ll=L / 2.,
                                   Lr=L / 2.)
        eps = []
        for w in w_arr:
            ccb.w = w
            eps.append(ccb.max_norm_stress / E)
        plt.plot(w_arr / L, np.array(eps) * E, color='blue', lw=2, label='CB model')
        plt.legend(loc='best')
def showWeibull():
    '''Utility function to show Weibull distributions'''
    
    t = frange(0, 2.5, 0.01)
    lambdaVal = 1
    ks = [0.5, 1, 1.5, 5]
    
    for k in ks:
        wd = stats.weibull_min(k)
        plt.plot(t, wd.pdf(t), label='k = {0:.1f}'.format(k))
        
    plt.xlim(0,2.5)
    plt.ylim(0,2.5)
    plt.xlabel('X')
    plt.ylabel('pdf(X)')
    plt.legend()
        
    outFile = 'Weibull_PDF.png'
    showData(outFile)
    def give_cb_attr(self):
        #gives every crack bridge attributes
        no_of_fibers = norm(self.distr_of_fibers[0], self.distr_of_fibers[1]).ppf(np.random.rand(1))
        phi_array = sin2x._ppf(np.random.rand(no_of_fibers))
        le_array = (np.random.rand(no_of_fibers) * self.fiber_length / 2.)
        if self.with_tau_distr:
            tau_array = abs(weibull_min(self.weibull_tau_shape, self.weibull_tau_scale).ppf(np.random.rand(no_of_fibers)))

        else:
            tau_array = self.tau


        if self.with_f_distr:
            f_array = abs(norm(self.mean_f, self.stdev_f).ppf(np.random.rand(no_of_fibers)))

        else: f_array = self.f
        self.fiber_data_tuple[0].append(int(no_of_fibers))
        self.fiber_data_tuple[1].append(phi_array)
        self.fiber_data_tuple[2].append(le_array)
        self.fiber_data_tuple[3].append(f_array)
        self.fiber_data_tuple[4].append(tau_array)
예제 #50
0
def weibull(scale=1,shape=1,loc=0):
    '''  pdf =shape* (x/scale+loc)**(shape-1)
        * exp(-(x/scale+loc)**shape)
    '''
    return stats.weibull_min(shape,scale=scale,loc=-loc)
예제 #51
0
    var_sim = []
    var_eval = []
    no_sim = linspace(100, 10000, 30)
    no_sim = [10000000]
    for points in no_sim:
        t = Test()
        t.sims = points
        X = t.X(x)
        N = t.N(x)
        sim = t.sims
        result = []
        filaments = t.N_ppf(rand(sim))
        for i, s in enumerate(filaments):
            resp = sum(t.X_ppf(rand(s - 1)))
            result.append(resp)
        mean_N = weibull_min(t.N_shape, scale=t.N_scale, loc=t.N_loc).stats("m")
        var_N = weibull_min(t.N_shape, scale=t.N_scale, loc=t.N_loc).stats("v")
        mean_X = weibull_min(t.X_shape, scale=t.X_scale, loc=t.X_loc).stats("m")
        var_X = weibull_min(t.X_shape, scale=t.X_scale, loc=t.X_loc).stats("v")
        var_D = mean_N * var_X + mean_X ** 2 * var_N
        var_sim.append(var(result))
        var_eval.append(var_D)

    print var_sim
    print var_eval
    plt.plot(no_sim, var_sim)
    plt.plot(no_sim, var_eval)
    # print 'computed variance = ', var_D
    # print 'variance for', sim, 'simulated data =', var( result )
    # plt.hist( result, normed = True, bins = 50 )
    plt.show()
 def _get_CDF( self ):
     sigma = linspace( 0, 30, 200 )
     return sigma, weibull_min( self.m, scale = self.scale_sigma_m ).cdf( sigma )
예제 #53
0
 def rvs(self, size):
     # This is working and matching the spreadsheet
     # But not sure why _min had to be used here...
     return ss.weibull_min(c=self.shape, loc=self.loc, scale=self.scale).rvs(size=size)
 def _get_CDF_arr( self ):
     '''discretizes the CDF for equal spaced stress values'''
     return weibull_min( self.m, scale = self.scale_sigma_m ).cdf( self.Pf_sigma_arr )
예제 #55
0
def bundle_ld():
    e = np.linspace(0.0, 1.5 * s, 1000)
    plt.plot(e, e * Ef * (1 - weibull_min(m, scale=s).cdf(e)), color="black", lw=3)
    plt.xlim(0, 1.6 * s)
예제 #56
0
def filaments_ld():
    eps_fu = weibull_min(m, scale=s).ppf(np.linspace(0.001, 0.999, 50))
    for eps in eps_fu:
        plt.plot([0, eps, eps], [0, eps * Ef, 0], color="grey")
    mu_eps = weibull_min(m, scale=s).stats("m")
    plt.plot([0, mu_eps, mu_eps], [0, mu_eps * Ef, 0], color="black", lw=3, ls="dashed")
 def _get_Pf_sigma_arr( self ):
     '''equivalently discretizes the matrix stresses'''
     low = weibull_min( self.m, scale = self.scale_sigma_m ).ppf( 1e-10 )
     high = weibull_min( self.m, scale = self.scale_sigma_m ).ppf( 1. - 1e-10 )
     return linspace( low, high, self.n_cdf )
 def surv_arr( self, sigma ):
     '''survival probabilities for stresses along the specimen'''
     return 1 - weibull_min( self.m, scale = self.scale_sigma_m ).cdf( sigma )