def calculate_linspace(distribution):
    if distribution[0] == 'EXP':
        lambda_ = distribution[1]
        scale_ = 1 / lambda_
        return np.linspace(expon.ppf(0.001, scale=scale_),
                           expon.ppf(0.999, scale=scale_), 1000)

    if distribution[0] == 'WEIBULL':
        scale = distribution[1]
        shape = distribution[2]
        return np.linspace(weibull_min.ppf(0.001, shape, loc=0, scale=scale),
                           weibull_min.ppf(0.999, shape, loc=0, scale=scale),
                           1000)

    if distribution[0] == 'NORMAL':
        mu = distribution[1]
        sigma = distribution[2]
        return np.linspace(norm.ppf(0.001, loc=mu, scale=sigma),
                           norm.ppf(0.999, loc=mu, scale=sigma), 1000)

    if distribution[0] == 'LOGNORM':
        mu = distribution[1]
        sigma = distribution[2]
        scale = math.exp(mu)
        return np.linspace(lognorm.ppf(0.001, sigma, loc=0, scale=scale),
                           lognorm.ppf(0.999, sigma, loc=0, scale=scale), 1000)
    else:
        return np.linspace(0, 100, 1000)
Example #2
0
    def _update_canvas(self):
        """
        Update the figure when the user changes an input value.
        :return:
        """
        # Get the parameters from the form
        loc = float(self.loc.text())
        scale = float(self.scale.text())
        shape_factor = float(self.shape_factor.text())

        # Get the selected distribution from the form
        distribution_type = self.distribution_type.currentText()

        if distribution_type == 'Gaussian':
            x = linspace(norm.ppf(0.001, loc, scale),
                         norm.ppf(0.999, loc, scale), 200)
            y = norm.pdf(x, loc, scale)
        elif distribution_type == 'Weibull':
            x = linspace(weibull_min.ppf(0.001, shape_factor),
                         weibull_min.ppf(0.999, shape_factor), 200)
            y = weibull_min.pdf(x, shape_factor, loc, scale)
        elif distribution_type == 'Rayleigh':
            x = linspace(rayleigh.ppf(0.001, loc, scale),
                         rayleigh.ppf(0.999, loc, scale), 200)
            y = rayleigh.pdf(x, loc, scale)
        elif distribution_type == 'Rice':
            x = linspace(rice.ppf(0.001, shape_factor),
                         rice.ppf(0.999, shape_factor), 200)
            y = rice.pdf(x, shape_factor, loc, scale)
        elif distribution_type == 'Chi Squared':
            x = linspace(chi2.ppf(0.001, shape_factor),
                         chi2.ppf(0.999, shape_factor), 200)
            y = chi2.pdf(x, shape_factor, loc, scale)

        # Clear the axes for the updated plot
        self.axes1.clear()

        # Display the results
        self.axes1.plot(x, y, '')

        # Set the plot title and labels
        self.axes1.set_title('Probability Density Function', size=14)
        self.axes1.set_xlabel('x', size=12)
        self.axes1.set_ylabel('Probability p(x)', size=12)

        # Set the tick label size
        self.axes1.tick_params(labelsize=12)

        # Turn on the grid
        self.axes1.grid(linestyle=':', linewidth=0.5)

        # Update the canvas
        self.my_canvas.draw()
Example #3
0
def distrib_quantile(q, largeur):
    """modèles de distribution pour partager en quantile (pour affichage du seuil [axvline])"""
    global ladistribution
    if ladistribution == "alpha":
        return alpha.ppf(q, 0.8, 0, largeur)
    elif ladistribution == "gauss":
        return stat.norm.ppf(q, 0, largeur)
    elif ladistribution == "triangle":
        return triang.ppf(q, 0, 0, largeur)
    elif ladistribution == "weibull":
        return weibull_min.ppf(q, 1.1, 0, largeur)
Example #4
0
    def inv(self, p):
        """
        @brief Return the inverse cummulative probability for p.

        @param p is the value between 0 and 1
        """

        if p <= 0.0:
            p = 0.0000000000001
        if p >= 1.0:
            p = 0.9999999999999
        return weibull_min.ppf(p, self.shape, loc=self.loc, scale=self.scale)
Example #5
0
    def _get_csf(self):
        # composite stress at Pf probability for CS to be of final range
        # scale parameter for composite stress
        scale_sigma_c = self.scale_sigma_m / self.E_m * self.E_c

        sigma = weibull_min.ppf(self.Pf, self.m, scale=scale_sigma_c)

        # point of reaching final crack spacing
        epsilon_csf = hstack(
            (0, self._get_epsilon_c(sigma), self._get_epsilon_c(sigma)))
        sigma_csf = hstack((sigma, sigma, 0))
        return epsilon_csf, sigma_csf
Example #6
0
    def inv(self, p):
        '''
        @brief Return the inverse cummulative probability for p.

        @param p is the value between 0 and 1
        '''

        if p <= 0.0:
            p = 0.0000000000001
        if p >= 1.0:
            p = 0.9999999999999
        return weibull_min.ppf(p, self.shape, loc=self.loc, scale=self.scale)
Example #7
0
    def _get_csf(self):
        # composite stress at Pf probability for CS to be of final range
        # scale parameter for composite stress
        scale_sigma_c = self.scale_sigma_m / self.E_m * self.E_c

        sigma = weibull_min.ppf(self.Pf, self.m, scale = scale_sigma_c)

        # point of reaching final crack spacing
        epsilon_csf = np.hstack((0,
                    self._get_epsilon_c(sigma),
                    self._get_epsilon_c(sigma )))
        sigma_csf = np.hstack((sigma, sigma, 0))
        return epsilon_csf, sigma_csf
Example #8
0
 def Amount(Rn, Dist, Coef):
     if Dist == "exp":
         GenP = expon.ppf(Rn, Coef[0], Coef[1])
     elif Dist == "gamma":
         GenP = gamma.ppf(Rn, Coef[0], Coef[1], Coef[2])
     elif Dist == "weibull":
         GenP = weibull_min.ppf(Rn, Coef[0], Coef[1], Coef[2])
     elif Dist == "lognorm":
         GenP = np.exp(norm.ppf(Rn, Coef[0],
                                Coef[1]))  # use norm generate lognorm
     #elif Dist == "pearson3":
     #    GenP = pearson3.ppf(Rn,coef[0],coef[1],coef[2])
     return GenP
Example #9
0
 def _get_sigma_cu(self):
     '''Ultimate composite strength.
     The strength is given by the fiber strength related to the composite
     cross section by the reinforcement ratio rho and projected
     by the cosine of the fiber inclination into the loading direction.
     '''
     # 0.05 quantile strength of the matrix as a criterion for matrix failure
     # when this value is higher than the composite strength governed by the
     # reinforcement stress
     quantile = weibull_min.ppf( 0.05, self.m, scale = self.scale_sigma_m )
     # composite failure due to matrix failure
     if self.sigma_fu * self.V_f * cos( self.orientation ) < quantile / self.V_m:
         return quantile / self.V_m
     else:
     # composite failure due to fiber failure
         return self.sigma_fu * self.V_f * cos( self.orientation )
Example #10
0
 def _get_sigma_cu(self):
     '''Ultimate composite strength.
     The strength is given by the fiber strength related to the composite
     cross section by the reinforcement ratio rho and projected
     by the cosine of the fiber inclination into the loading direction.
     '''
     # 0.05 quantile strength of the matrix as a criterion for matrix failure
     # when this value is higher than the composite strength governed by the
     # reinforcement stress
     quantile = weibull_min.ppf(0.05, self.m, scale=self.scale_sigma_m)
     # composite failure due to matrix failure
     if self.sigma_fu * self.V_f * cos(
             self.orientation) < quantile / self.V_m:
         return quantile / self.V_m
     else:
         # composite failure due to fiber failure
         return self.sigma_fu * self.V_f * cos(self.orientation)
    zorder=11, linewidth=5)
plt.scatter(x_max, y_max, c='firebrick', marker='*', label='data (max)', s=45)
plt.legend(fontsize=14)
plt.xlim(0, 10)
plt.xlabel("x")
plt.ylabel("y")
plt.title(r"Data and model comparison between min and max of min(${\chi}^{2}$)")
fig3.show()

# error_pdf_comparison.png plot
sns.distplot(np.random.normal(mu, sigma, 100000), label='gaussian')
sns.distplot(np.random.logistic(loc, scale, 100000), label='logistic')                             
plt.legend(loc='best')
plt.show() 

# Weibull pdf plot for different parameter values
from scipy.stats import weibull_min 
fig, ax = plt.subplots(1, 1)
c_arr = np.linspace(1,3,20)
mean, var, skew, kurt = weibull_min.stats(c, moments='mvsk')
x = np.linspace(weibull_min.ppf(0.01, c), weibull_min.ppf(0.99, c), 100) 
ax.set_prop_cycle(color=[
    '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',
    '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
    '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',
    '#17becf', '#9edae5'])
for idx in range(len(c_arr)):
    ax.plot(x, weibull_min.pdf(x, c_arr[idx]), lw=5, alpha=0.6, label='c={0}'.format(np.round(c_arr[idx], 2)))
plt.legend(loc='best', prop={'size': 10})
plt.title('Weibull pdf')
plt.show()
from scipy.stats import weibull_min
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)

# Calculate a few first moments:

c = 1.79
mean, var, skew, kurt = weibull_min.stats(c, moments='mvsk')

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

x = np.linspace(weibull_min.ppf(0.01, c), weibull_min.ppf(0.99, c), 100)
ax.plot(x,
        weibull_min.pdf(x, c),
        'r-',
        lw=5,
        alpha=0.6,
        label='weibull_min 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 = weibull_min(c)
ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')

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

vals = weibull_min.ppf([0.001, 0.5, 0.999], c)
Example #13
0
    for j in range(len(x_bins)):
        mask1 = h_ind_bin == j + ind_min_bin
        real_bins[j] = hs_i[mask1].mean()
        weib_par_cond[j,:] = weibull_min.fit(v_i[mask1], floc=0)
    try:
        k = curve_fit(power3, real_bins, weib_par_cond[:,0], bounds=bounds)[0]
        a = curve_fit(power3, real_bins, weib_par_cond[:,2], bounds=bounds)[0]
    except RuntimeError: 
        try:
            k = curve_fit(power3, real_bins[0:-1], weib_par_cond[0:-1,0], bounds=bounds)[0]
            a = curve_fit(power3, real_bins[0:-1], weib_par_cond[0:-1,2], bounds=bounds)[0]
        except RuntimeError: 
            k = curve_fit(power3, real_bins[0:-2], weib_par_cond[0:-2,0], bounds=bounds)[0]
            a = curve_fit(power3, real_bins[0:-2], weib_par_cond[0:-2,2], bounds=bounds)[0]

    x1_50 = weibull_min.ppf( norm.cdf(u1_50), *weib_par2)

    # The weibull conditional distribution
    k_x1_50 =  power3(x1_50, *k)
    a_x1_50 =  power3(x1_50, *a)

    x0_50 = weibull_min.ppf( norm.cdf(u0_50), k_x1_50, loc=0, scale=a_x1_50)

#    import seaborn as sns
#    h = sns.jointplot(x= v_i , y=hs_i, s=5)
#    h.x, h.y = x0_50, x1_50
#    h.plot_joint(plt.plot, color='C1')
    
#    ids_contour_i = []
    # Compute 50-yr IFORM contour.
#    iform_contour_i = IFormContour(my_fit.mul_var_dist, return_period, 1,
Example #14
0
 def var(self, alph):
     return weibull_min.ppf(alph, self.shape, 0, self.scale)
Example #15
0
def plot_pdf_with_raw_data(dim_index, parent_index, low_index, shape, loc,
                           scale, distribution_type, dist_points, interval,
                           var_name, symbol_parent_var, directory,
                           probabilistic_model):
    """
    Creates and saves an image, which shows a fit of a distribution.

    Parameters
    ----------
    dim_index : int,
          The index of the current dimension (distribution). The index is used
          to recognise the image later.
    parent_index : int,
        The index of the variable on which the conditional is based
        (when no condition: None).
    low_index : int,
         The index of the interval. (needed to recognize the images later)
    shape : float,
        The value of the shape parameter.
    loc : float,
        The value of the loc parameter. (location)
    scale : float,
        The value of the scale parameter.
    distribution_type: str,
        Name of the distribution, must be "Normal", "Weibull" or
        "Lognormal"
    dist_points: list of float,
       The dates for the histogram.
    interval : list of float,
        The list contains the interval of the plotted distribution.
    var_name : str,
        The name of a single variable of the probabilistic model.
    symbol_parent_var : str,
        Symbol of the variable on which the conditional variable is based.
    directory : str,
        The directory where the figure should be saved
    probabilistic_model : ProbabilisticModel,
        Probabilistic model which has the particular pdf.
    """
    fig = plt.figure()
    ax = fig.add_subplot(111)

    if distribution_type == 'Normal':
        x = np.linspace(norm.ppf(0.0001, loc, scale),
                        norm.ppf(0.9999, loc, scale), 100)
        y = norm.pdf(x, loc, scale)
        text = distribution_type + ',' + \
               ' μ=' + str(format(loc, '.3f')) + \
               ' σ=' + str(format(scale, '.3f'))
    elif distribution_type == 'Weibull':
        x = np.linspace(weibull_min.ppf(0.0001, shape, loc, scale),
                        weibull_min.ppf(0.9999, shape, loc, scale), 100)
        y = weibull_min.pdf(x, shape, loc, scale)
        text = distribution_type + ',' + \
               ' α=' + str(format(scale, '.3f')) + \
               ' β=' + str(format(shape, '.3f')) + \
               ' γ=' + str(format(loc, '.3f'))
    elif distribution_type == 'Lognormal':
        x = np.linspace(lognorm.ppf(0.0001, shape, scale=scale),
                        lognorm.ppf(0.9999, shape, scale=scale), 100)
        y = lognorm.pdf(x, shape, scale=scale)

        # plot_pdf_with_raw_data works with the scale parameter, but the user
        # should be presented the mu value. Consequently, the scale value must
        # be converted.
        text = distribution_type + ',' + \
               ' μ=' + str(format(np.log(scale), '.3f')) + \
               ' σ=' + str(format(shape, '.3f'))

    else:
        raise KeyError('No function match - {}'.format(distribution_type))

    text = text + ' ('
    if symbol_parent_var:
        text = text + str(format(interval[0], '.3f')) + '≤' + \
               symbol_parent_var + '<' + str(format(interval[1], '.3f')) + ', '
    text = text + 'n=' + str(len(dist_points)) + ')'

    ax.plot(x, y, 'r-', lw=5, alpha=0.6, label=distribution_type)
    n_intervals_histogram = int(round(len(dist_points) / 50.0))
    if n_intervals_histogram > 100:
        n_intervals_histogram = 100
    if n_intervals_histogram < 10:
        n_intervals_histogram = 10

    ax.hist(dist_points,
            n_intervals_histogram,
            normed=True,
            histtype='stepfilled',
            alpha=0.9,
            color='#54889c')
    ax.grid(True)

    plt.title(text)
    plt.xlabel(var_name)
    plt.ylabel('probability density [-]')
    dim_index_2_digits = str(dim_index).zfill(2)
    parent_index_2_digits = str(parent_index).zfill(2)
    low_index_2_digits = str(low_index).zfill(2)

    # The convention for image name is like this: 'fit_01_00_02.png' means
    # a plot of the second variable (01) which is conditional on the first
    # variable (00) and this is the third (02) fit
    # For the following block thanks to: https://stackoverflow.com/questions/
    # 20580179/saving-a-matplotlib-graph-as-an-image-field-in-database
    f = BytesIO()
    plt.savefig(f, bbox_inches='tight')
    plt.close(fig)
    content_file = ContentFile(f.getvalue())

    dists_models = DistributionModel.objects.filter(
        probabilistic_model=probabilistic_model)
    plotted_figure = PlottedFigure(probabilistic_model=probabilistic_model,
                                   distribution_model=dists_models[dim_index])
    file_name = 'fit_' + dim_index_2_digits + '_' + parent_index_2_digits + \
                '_' + low_index_2_digits + '.png'
    plotted_figure.image.save(file_name, content_file)
    plotted_figure.save()
Example #16
0
def ppf_fn5(q):
    return weibull_min.ppf(q, c=5)
Example #17
0
 def _get_xi(self):
     # Nf random numbers from the interval (0,1)
     rn = random.rand(self.Nf)   
     xi_rand = weibull_min.ppf(rn, self.xi_shape, scale = self.xi_scale)
     return xi_rand
Example #18
0
def plot_weibull(name,
                 metric,
                 distribution,
                 times,
                 theoretical_distribution=None):
    scale = distribution[1]
    shape = distribution[2]

    theoretical_scale = None
    theoretical_shape = None
    # Checks whether there is a theoretical distribution to compare it to
    if theoretical_distribution is not None:
        theoretical_scale = theoretical_distribution[1]
        theoretical_shape = theoretical_distribution[2]

    fig, subplots = setup_fig_subplots(metric)
    fig.suptitle(name)

    linspace = np.linspace(weibull_min.ppf(0.001, shape, loc=0, scale=scale),
                           weibull_min.ppf(0.999, shape, loc=0, scale=scale),
                           1000)

    # First plot PDF
    if theoretical_distribution is not None:
        subplots[0].plot(linspace,
                         weibull_min.pdf(linspace, shape, loc=0, scale=scale),
                         'r-',
                         lw=1,
                         alpha=0.6,
                         label='Reconstructed')
        subplots[0].plot(linspace,
                         weibull_min.pdf(linspace,
                                         theoretical_shape,
                                         loc=0,
                                         scale=theoretical_scale),
                         'b-',
                         lw=1,
                         alpha=0.6,
                         label='Theoretical')
        subplots[0].legend()
    else:
        subplots[0].plot(linspace,
                         weibull_min.pdf(linspace, shape, loc=0, scale=scale),
                         'r-',
                         lw=1,
                         alpha=0.6)

    if times != EMPTY_LIST:
        if metric == 'Reliability':
            subplots[0].hist(times,
                             bins=20,
                             normed=True,
                             histtype='stepfilled',
                             alpha=0.2,
                             label='Time to failures')
        if metric == 'Maintainability':
            subplots[0].hist(times,
                             bins=20,
                             normed=True,
                             histtype='stepfilled',
                             alpha=0.2,
                             label='Time to repairs')
        subplots[0].legend()
    subplots[0].set_title('Weibull PDF')

    # Second plot CDF and/or Maintainability
    if theoretical_distribution is not None:
        subplots[1].plot(linspace,
                         weibull_min.cdf(linspace, shape, loc=0, scale=scale),
                         'r-',
                         lw=1,
                         alpha=0.6,
                         label='Reconstructed')
        subplots[1].plot(linspace,
                         weibull_min.cdf(linspace,
                                         theoretical_shape,
                                         loc=0,
                                         scale=theoretical_scale),
                         'b-',
                         lw=1,
                         alpha=0.6,
                         label='Theoretical')
        subplots[1].legend()
    else:
        subplots[1].plot(linspace,
                         weibull_min.cdf(linspace, shape, loc=0, scale=scale),
                         'r-',
                         lw=1,
                         alpha=0.6)

    if metric == 'Reliability':
        subplots[1].set_title('Weibull CDF')
    if metric == 'Maintainability':
        subplots[1].set_title('Weibull CDF (Maintainability)')

    # Third plot Reliability
    if metric == 'Reliability':
        if theoretical_distribution is not None:
            subplots[2].plot(
                linspace,
                1 - weibull_min.cdf(linspace, shape, loc=0, scale=scale),
                'r-',
                lw=1,
                alpha=0.6,
                label='Reconstructed')
            subplots[2].plot(linspace,
                             1 - weibull_min.cdf(linspace,
                                                 theoretical_shape,
                                                 loc=0,
                                                 scale=theoretical_scale),
                             'b-',
                             lw=1,
                             alpha=0.6,
                             label='Theoretical')
            subplots[2].legend()
        else:
            subplots[2].plot(
                linspace,
                1 - weibull_min.cdf(linspace, shape, loc=0, scale=scale),
                'r-',
                lw=1,
                alpha=0.6)
        subplots[2].set_title(metric)

    #plt.show()
    plt.show(block=False)
Example #19
-1
 def X_ppf(self, n):
     return weibull_min.ppf(n, self.X_shape, scale=self.X_scale, loc=self.X_loc)