예제 #1
0
def add_bootstrap_plot_full(aeps,
                            aep_qs,
                            skew,
                            mu,
                            sigma,
                            nbs=1,
                            nsamples=50,
                            color="brown",
                            s=25):
    """
    Analyitcal Bootstrap with Empirical Plotting 
    """
    f, a = plot_aep_full(aeps, aep_qs, skew, mu, sigma)
    for i in range(0, nbs):
        rvs = pearson3.rvs(skew, loc=mu, scale=sigma, size=nsamples)

        lp3_data = LP3(rvs)
        log_peaks = lp3_data.log
        skew_new = lp3_data.weighted_skew(rskew, rskew_mse)
        mu_new = lp3_data.log.mean()
        sigma_new = lp3_data.log.std()

        x = np.linspace(
            pearson3.ppf(0.0001, skew_new, loc=mu_new, scale=sigma_new),
            pearson3.ppf(0.9999, skew, loc=mu, scale=sigma), 100)

        fax2.plot(pearson3.pdf(x, skew_new, loc=mu_new, scale=sigma_new),
                  10**x,
                  "black",
                  lw=2,
                  alpha=1,
                  label="pearson3 pdf")

    a.set_title(f"{nbs} Bootstraps", fontsize=20)
    return f, a
    def moment_plot(self):
        """
        # 绘制矩法估计参数理论概率曲线
        """
        x = np.linspace(self.prob_lim_left, self.prob_lim_right, 1000)
        theo_y = (pearson3.ppf(1 - x / 100, self.coeff_of_skew) *
                  self.coeff_of_var + 1) * self.expectation

        self.ax.plot(x, theo_y, "--", lw=1, label="矩法估计参数概率曲线")
    def fitted_plot(self):
        """
        # 绘制适线后的概率曲线
        
        """

        x = np.linspace(self.prob_lim_left, self.prob_lim_right, 1000)
        theoY = (pearson3.ppf(1 - x / 100, self.fit_CS) * self.fit_CV +
                 1) * self.fit_EX

        self.ax.plot(x, theoY, lw=2, label="适线后概率曲线")
    def prob_to_value(self, prob):
        """
        # 由设计频率转换设计值
        
        ## 输入参数
        
        + `prob`:设计频率,单位百分数
        
        ## 输出参数
        
        + `value`:设计值
        """

        value = (pearson3.ppf(1 - prob / 100, self.fit_CS) * self.fit_CV +
                 1) * self.fit_EX

        print("%.4f%% 的设计频率对应的设计值为 %.2f" % (prob, value))

        return value
def p3ProbPlot(Ex, Cv, Cs, show=False):
    """
    该函数用于绘制P3曲线
    Ex          曲线的数学期望
    Cv          曲线的变差系数
    Cs          曲线的偏态系数
    show=False  是否显示图像,默认不显示
    """

    # 获取理论曲线的控制点
    x = np.linspace(0.1, 99.9, 1000)
    theoryY = (pearson3.ppf(1 - x / 100, Cs) * Cv + 1) * Ex

    # 绘制理论曲线
    plt.plot(x, theoryY, 'r-', lw=2, label='理论频率曲线')

    plt.legend()

    if show == True:
        plt.show()
예제 #6
0
def add_bootstrap_plot_from_sample_pop_full(aeps,
                                            aep_qs,
                                            skew,
                                            mu,
                                            sigma,
                                            rskew,
                                            rskew_mse,
                                            nbs=1,
                                            nsamples=10,
                                            color="brown",
                                            nx=200,
                                            s=25):
    """
    Bootstrap with Empirical Plotting 
    """
    f, a = plot_aep_full(aeps, aep_qs, skew, mu, sigma)
    xs = np.linspace(0.9999, 0.0001, nx)

    for i in range(0, nbs):
        rvs = np.random.choice(aep_qs, size=nsamples)
        lp3_data = LP3(rvs)
        log_peaks = lp3_data.log
        skew_new = lp3_data.weighted_skew(rskew, rskew_mse)
        mu_new = lp3_data.log.mean()
        sigma_new = lp3_data.log.std()

        ys = []
        for x in xs:
            ys.append(10**pearson3.ppf(1 - x,
                                       skew_new,
                                       loc=mu_new,
                                       scale=sigma_new))

        # Some Unusual Behavior results in negative skew?
        # Reversing here for plotting, need to debug this.
        if skew_new > 0:
            a.scatter(x=xs, y=ys, color=color, s=s)
    a.set_title(f"{nsamples}: Samples -- {nbs} Bootstraps", fontsize=20)
    return f, a
예제 #7
0
from scipy.stats import pearson3
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)

# Calculate a few first moments:

skew = 0.1
mean, var, skew, kurt = pearson3.stats(skew, moments='mvsk')

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

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

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

vals = pearson3.ppf([0.001, 0.5, 0.999], skew)
np.allclose([0.001, 0.5, 0.999], pearson3.cdf(vals, skew))
# True

# Generate random numbers:
예제 #8
0
def plot_aep_full(aeps, aep_qs, skew, mu, sigma, color="Brown", ci=95):
    # PDF
    fig, ax = plt.subplots(figsize=(30, 8))

    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    gs = gridspec.GridSpec(ncols=6, nrows=1, figure=fig)

    fax1 = fig.add_subplot(gs[0:5])
    fax2 = fig.add_subplot(gs[5], sharey=fax1)

    fax2.axes.yaxis.set_visible(False)
    fax2.axes.xaxis.set_visible(False)

    x = np.linspace(pearson3.ppf(0.0001, skew, loc=mu, scale=sigma),
                    pearson3.ppf(0.9999, skew, loc=mu, scale=sigma), 100)

    fax2.plot(pearson3.pdf(x, skew, loc=mu, scale=sigma),
              10**x,
              "black",
              lw=2,
              alpha=1,
              label="pearson3 pdf")

    density_range = pearson3.pdf(x, skew, loc=mu, scale=sigma)

    # -----------------------------------------------------------------------------------------------------------------------------------------------------

    # fax2.fill_between(, 0, 100, color='black', alpha = 0.2)
    # fax2.fill_between(density_range, q90lower, q90upper, color='gray', alpha = 0.2)
    # fax2.fill_between(density_range, q90lower, pdfmin, color='lightgray', alpha = 0.2)
    fax2.set_xlim([0, np.max(density_range)])
    fax1.set_ylim([20000, 1200000])

    fax2.set_yscale("log")

    pdfmin = 10**x[0]
    pdfmax = 10**x[-1]

    # adjust the line for to match the extent of peakfq plots
    fax1.plot(aeps[1:-10], aep_qs[1:-10], "black", linewidth=2, alpha=0.8)

    # Plot Formatting
    # fax1.invert_xaxis()
    fax1.set_xscale("logit")

    # fax1.xaxis.set_major_formatter(ticker.FuncFormatter(myLogitFormat))
    fax1.set_yscale("log")
    fax1.set_xlim([0.990, 0.002])
    fax1.set_ylim([20000, 1200000])
    # fax1.set_xlabel('Annual exceedance probability, [%]');fax1.set_ylabel('Discharge, [cfs]')
    fax1.set_title("Flow Frequency Curve")
    fax1.grid(True, which="both")
    fax1.xaxis.set_minor_formatter(ticker.FuncFormatter(logit_plot_format))
    fax1.yaxis.set_major_formatter(ticker.FuncFormatter(log_plot_format))
    fax1.set_xlabel("Annual Exceendence Probability")
    fax1.set_ylabel("Flow (cfs)")

    # fax1.axhline(pdfmax, 0, 1e9, color='purple');
    upper_ci, lower_ci = ci * 0.01, (100 - ci) * 0.01

    qupper = int(10**pearson3.ppf(upper_ci, skew, loc=mu, scale=sigma))
    qlower = int(10**pearson3.ppf(lower_ci, skew, loc=mu, scale=sigma))

    fax1.fill_between(np.arange(0.990, 0.002, -0.001),
                      pdfmax,
                      qupper,
                      color="gray",
                      alpha=0.2)
    fax1.fill_between(np.arange(0.990, 0.002, -0.001),
                      qlower,
                      qupper,
                      color="black",
                      alpha=0.2)
    fax1.fill_between(np.arange(0.990, 0.002, -0.001),
                      qlower,
                      pdfmin,
                      color="gray",
                      alpha=0.2)

    fax2.grid()
    fig.tight_layout(pad=1.00, h_pad=0, w_pad=-1, rect=None)
    return fig, fax1
    def plot_fitting(self, sv_ratio=0, ex_fitting=True, output=True):
        """
        # 优化适线
        
        ## 输入参数

        + `sv_ratio`:倍比系数,即偏态系数 `Cs` 与 变差系数 `Cv` 之比。
        
            默认为 0,即关闭倍比系数功能。
        
            - 当 `sv_ratio` ≠ 0 时,Cs 不参与适线运算中,且 `Cs` = `sv_ratio` × `Cv`;

            - 当 `sv_ratio` = 0 时,Cs 正常参与适线运算。

        + `ex_fitting`:适线时是否调整 EX,默认为 True

        + `output`:是否在控制台输出参数,默认为 True
        """

        if sv_ratio == 0:
            if ex_fitting:
                p3 = lambda prob, ex, cv, cs: (pearson3.ppf(
                    1 - prob / 100, cs) * cv + 1) * ex

                [self.fit_EX, self.fit_CV, self.fit_CS], pcov = curve_fit(
                    p3, self.empi_prob, self.arr,
                    [self.expectation, self.coeff_of_var, self.coeff_of_skew])

            else:
                p3 = lambda prob, cv, cs: (pearson3.ppf(1 - prob / 100, cs) *
                                           cv + 1) * self.expectation

                [self.fit_CV, self.fit_CS
                 ], pcov = curve_fit(p3, self.empi_prob, self.arr,
                                     [self.coeff_of_var, self.coeff_of_skew])

                self.fit_EX = self.expectation

        else:
            if ex_fitting:
                p3 = lambda prob, ex, cv: (pearson3.ppf(
                    1 - prob / 100, cv * sv_ratio) * cv + 1) * ex

                [self.fit_EX, self.fit_CV
                 ], pcov = curve_fit(p3, self.empi_prob, self.arr,
                                     [self.expectation, self.coeff_of_var])

            else:
                p3 = lambda prob, cv: (pearson3.ppf(
                    1 - prob / 100, cv * sv_ratio) * cv + 1) * self.expectation

                [self.fit_CV], pcov = curve_fit(p3, self.empi_prob, self.arr,
                                                [self.coeff_of_var])

                self.fit_EX = self.expectation

            self.fit_CS = self.fit_CV * sv_ratio

        if output:
            print("适线后")
            print("期望 EX 为 %.2f" % self.fit_EX)
            print("变差系数 Cv 为 %.4f" % self.fit_CV)
            print("偏态系数 Cs 为 %.4f" % self.fit_CS)