def plot_post(param_sample_vec, cred_mass=0.95, comp_val=False,
              ROPE=False, ylab='', xlab='parameter', fontsize=14, labelsize=14,
              title='', framealpha=1, facecolor='skyblue', edgecolor='white',
              show_mode=True, bins=50):

    #compute HDI
    HDI = hpd(param_sample_vec, 1-cred_mass)

    post_summary = {'mean':0,'median':0,'mode':0, 'hdi_mass':0,'hdi_low':0,
                   'hdi_high':0, 'comp_val':0, 'pc_gt_comp_val':0, 'ROPE_low':0,
                   'ROPE_high':0, 'pc_in_ROPE':0}
    post_summary['mean'] = np.mean(param_sample_vec)
    post_summary['median'] = np.median(param_sample_vec)
    post_summary['mode'] = stats.mode(param_sample_vec)[0]
    post_summary['hdi_mass'] = cred_mass
    post_summary['hdi_low'] = HDI[0]
    post_summary['hdi_high'] = HDI[1]

    # Plot histogram.
    n, bins, patches = plt.hist(param_sample_vec, normed=True, bins=bins,
                                edgecolor=edgecolor, facecolor=facecolor)
    plt.xlabel(xlab, fontsize=fontsize)
    plt.ylabel(ylab, fontsize=fontsize)
    plt.title(title, fontsize=fontsize)

    cv_ht = 0.75*np.max(n)
    cen_tend_ht = 0.9 * cv_ht
    ROPE_text_ht = 0.55 * cv_ht
#    # Display mean or mode:
    if show_mode:
        plt.plot(0, label='mode = %.2f' % post_summary['mode'], alpha=0)
    else:
        plt.plot(0, label='mean = %.2f' % post_summary['mean'], alpha=0)
    # Display the comparison value.

    if comp_val is not False:
        pc_gt_comp_val = 100 * np.sum(param_sample_vec > comp_val)/len(param_sample_vec)
        pc_lt_comp_val = 100 - pc_gt_comp_val
        plt.plot([comp_val, comp_val], [0, cv_ht], color='darkgreen',
                 linestyle='--', linewidth=2,
                 label='%.1f%% <%.1f < %.1f%%'
                 % (pc_lt_comp_val, comp_val, pc_gt_comp_val))
        post_summary['comp_val'] = comp_val
        post_summary['pc_gt_comp_val'] = pc_gt_comp_val
#    # Display the ROPE.
    if ROPE is not False:
        rope_col = 'darkred'
        pc_in_ROPE = round(np.sum((param_sample_vec > ROPE[0]) & (param_sample_vec < ROPE[1]))/len(param_sample_vec)*100)
        plt.plot([ROPE[0], ROPE[0]], [0, 0.96*ROPE_text_ht], color=rope_col,
                linestyle=':', linewidth=4,
                label='%.1f%% in ROPE' % pc_in_ROPE)
        plt.plot([ROPE[1], ROPE[1]], [0, 0.96*ROPE_text_ht], color=rope_col,
                linestyle=':', linewidth=4)
        post_summary['ROPE_low'] = ROPE[0] 
        post_summary['ROPE_high'] = ROPE[1] 
        post_summary['pc_in_ROPE'] = pc_in_ROPE
#    # Display the HDI.
    plt.plot(HDI, [0, 0], linewidth=6, color='k', label='HDI %.1f%% %.3f-%.3f' % (cred_mass*100, HDI[0], HDI[1]))
    plt.legend(loc='upper left', fontsize=labelsize, framealpha=framealpha)
    return post_summary
def bern_grid(theta, p_theta, data, credib=.95):
    """
    Bayesian updating for Bernoulli likelihood and prior specified on a grid.
    Input arguments:
     theta is a vector of theta values, all between 0 and 1.
     p_theta is a vector of corresponding probability _masses_.
     data is a vector of 1's and 0's, where 1 corresponds to a and 0 to b.
     credib is the probability mass of the credible interval, default is 0.95.
    Output:
     p_theta_given_data is a vector of posterior probability masses over theta.
     Also creates a three-panel graph of prior, likelihood, and posterior
     probability masses with credible interval.
    Example of use:
     Create vector of theta values.
     bin_width = 1/1000 
     theta_grid = np.arange(0, 1+bin_width, bin_width)
     Specify probability mass at each theta value.
     > rel_prob = np.minimum(theta_grid, 1-theta_grid) relative prob at each theta
     > prior = rel_prob / sum(rel_prob) probability mass at each theta
     Specify the data vector.
     data_vec = np.repeat([1, 0], [11, 3])  # 3 heads, 1 tail
     Call the function.
     > posterior = bern_grid( theta=theta_grid , p_theta=prior , data=data_vec )
    """

    import matplotlib.pyplot as plt
    import numpy as np
    from hpd import hpd

# Create summary values of data
    z = sum(data[data == 1])  # number of 1's in data
    N = len(data)  # number of flips in data
# Compute the likelihood of the data for each value of theta.
    p_data_given_theta = theta**z * (1 - theta)**(N - z)
# Compute the evidence and the posterior.
    p_data = sum(p_data_given_theta * p_theta)
    p_theta_given_data = p_data_given_theta * p_theta / p_data
    # Determine the limits of the highest density interval
    x = np.random.choice(theta, size=5000, replace=True, p=p_theta_given_data)
    intervals = hpd(x, alpha=1-credib)

# Plot the results.
    plt.figure(figsize=(12, 12))
    plt.subplots_adjust(hspace=0.7)

#    # Plot the prior.
    locx = 0.05
    mean_theta = sum(theta * p_theta)  # mean of prior, for plotting
    plt.subplot(3, 1, 1)
    plt.plot(theta, p_theta)
    plt.xlim(0, 1)
    plt.ylim(0, np.max(p_theta)*1.2)
    plt.xlabel(r'$\theta$')
    plt.ylabel(r'$P(\theta)$')
    plt.title('Prior')
    plt.text(locx, np.max(p_theta)/2, r'mean($\theta$;%5.2f)' % mean_theta)
    # Plot the likelihood:
    plt.subplot(3, 1, 2)
    plt.plot(theta, p_data_given_theta)
    plt.xlim(0, 1)
    plt.ylim(0, np.max(p_data_given_theta)*1.2)
    plt.xlabel(r'$\theta$')
    plt.ylabel(r'$P(D|\theta)$')
    plt.title('Likelihood')
    plt.text(locx, np.max(p_data_given_theta)/2, 'data: z=%s, N=%s' % (z, N))
    # Plot the posterior:
    mean_theta_given_data = sum(theta * p_theta_given_data)
    plt.subplot(3, 1, 3)
    plt.plot(theta, p_theta_given_data)
    plt.xlim(0, 1)
    plt.ylim(0, np.max(p_theta_given_data)*1.2)
    plt.xlabel(r'$\theta$')
    plt.ylabel(r'$P(\theta|D)$')
    plt.title('Posterior')
    loc = np.linspace(0, np.max(p_theta_given_data), 5)
    plt.text(locx, loc[1], r'mean($\theta$;%5.2f)' % mean_theta_given_data)
    plt.text(locx, loc[2], 'P(D) = %g' % p_data)
    # Plot the HDI
    plt.text(locx, loc[3],
             'Intervals =%s' % ', '.join('%.3f' % x for x in intervals))
    for i in range(0, len(intervals), 2):
        plt.fill_between(theta, 0, p_theta_given_data,
                         where=np.logical_and(theta > intervals[i],
                                              theta < intervals[i+1]),
                         color='blue', alpha=0.3)
    plt.savefig('Figure_6.1.png')
    plt.show()
    return p_theta_given_data
def plot_post(param_sample_vec,
              cred_mass=0.95,
              comp_val=False,
              ROPE=False,
              ylab='',
              xlab='parameter',
              fontsize=14,
              labelsize=14,
              title='',
              framealpha=1,
              facecolor='skyblue',
              edgecolor='white',
              show_mode=True,
              bins=50):

    #compute HDI
    HDI = hpd(param_sample_vec, 1 - cred_mass)

    post_summary = {
        'mean': 0,
        'median': 0,
        'mode': 0,
        'hdi_mass': 0,
        'hdi_low': 0,
        'hdi_high': 0,
        'comp_val': 0,
        'pc_gt_comp_val': 0,
        'ROPE_low': 0,
        'ROPE_high': 0,
        'pc_in_ROPE': 0
    }
    post_summary['mean'] = np.mean(param_sample_vec)
    post_summary['median'] = np.median(param_sample_vec)
    post_summary['mode'] = stats.mode(param_sample_vec)[0]
    post_summary['hdi_mass'] = cred_mass
    post_summary['hdi_low'] = HDI[0]
    post_summary['hdi_high'] = HDI[1]

    # Plot histogram.
    n, bins, patches = plt.hist(param_sample_vec,
                                normed=True,
                                bins=bins,
                                edgecolor=edgecolor,
                                facecolor=facecolor)
    plt.xlabel(xlab, fontsize=fontsize)
    plt.ylabel(ylab, fontsize=fontsize)
    plt.title(title, fontsize=fontsize)

    cv_ht = 0.75 * np.max(n)
    cen_tend_ht = 0.9 * cv_ht
    ROPE_text_ht = 0.55 * cv_ht
    #    # Display mean or mode:
    if show_mode:
        plt.plot(0, label='mode = %.2f' % post_summary['mode'], alpha=0)
    else:
        plt.plot(0, label='mean = %.2f' % post_summary['mean'], alpha=0)
    # Display the comparison value.

    if comp_val is not False:
        pc_gt_comp_val = 100 * np.sum(
            param_sample_vec > comp_val) / len(param_sample_vec)
        pc_lt_comp_val = 100 - pc_gt_comp_val
        plt.plot([comp_val, comp_val], [0, cv_ht],
                 color='darkgreen',
                 linestyle='--',
                 linewidth=2,
                 label='%.1f%% <%.1f < %.1f%%' %
                 (pc_lt_comp_val, comp_val, pc_gt_comp_val))
        post_summary['comp_val'] = comp_val
        post_summary['pc_gt_comp_val'] = pc_gt_comp_val
#    # Display the ROPE.
    if ROPE is not False:
        rope_col = 'darkred'
        pc_in_ROPE = round(
            np.sum((param_sample_vec > ROPE[0]) & (param_sample_vec < ROPE[1]))
            / len(param_sample_vec) * 100)
        plt.plot([ROPE[0], ROPE[0]], [0, 0.96 * ROPE_text_ht],
                 color=rope_col,
                 linestyle=':',
                 linewidth=4,
                 label='%.1f%% in ROPE' % pc_in_ROPE)
        plt.plot([ROPE[1], ROPE[1]], [0, 0.96 * ROPE_text_ht],
                 color=rope_col,
                 linestyle=':',
                 linewidth=4)
        post_summary['ROPE_low'] = ROPE[0]
        post_summary['ROPE_high'] = ROPE[1]
        post_summary['pc_in_ROPE'] = pc_in_ROPE
#    # Display the HDI.
    plt.plot(HDI, [0, 0],
             linewidth=6,
             color='k',
             label='HDI %.1f%% %.3f-%.3f' % (cred_mass * 100, HDI[0], HDI[1]))
    plt.legend(loc='upper left', fontsize=labelsize, framealpha=framealpha)
    frame = plt.gca()
    frame.axes.get_yaxis().set_ticks([])
    return post_summary
Esempio n. 4
0
def bern_grid(theta, p_theta, data, credib=.95):
    """
    Bayesian updating for Bernoulli likelihood and prior specified on a grid.
    Input arguments:
     theta is a vector of theta values, all between 0 and 1.
     p_theta is a vector of corresponding probability _masses_.
     data is a vector of 1's and 0's, where 1 corresponds to a and 0 to b.
     credib is the probability mass of the credible interval, default is 0.95.
    Output:
     p_theta_given_data is a vector of posterior probability masses over theta.
     Also creates a three-panel graph of prior, likelihood, and posterior
     probability masses with credible interval.
    Example of use:
     Create vector of theta values.
     bin_width = 1/1000 
     theta_grid = np.arange(0, 1+bin_width, bin_width)
     Specify probability mass at each theta value.
     > rel_prob = np.minimum(theta_grid, 1-theta_grid) relative prob at each theta
     > prior = rel_prob / sum(rel_prob) probability mass at each theta
     Specify the data vector.
     data_vec = np.repeat([1, 0], [11, 3])  # 3 heads, 1 tail
     Call the function.
     > posterior = bern_grid( theta=theta_grid , p_theta=prior , data=data_vec )
    """

    # Create summary values of data
    z = sum(data[data == 1])  # number of 1's in data
    N = len(data)  # number of flips in data
    # Compute the likelihood of the data for each value of theta.
    p_data_given_theta = theta**z * (1 - theta)**(N - z)
    # Compute the evidence and the posterior.
    p_data = sum(p_data_given_theta * p_theta)
    p_theta_given_data = p_data_given_theta * p_theta / p_data
    # Determine the limits of the highest density interval
    x = np.random.choice(theta, size=5000, replace=True, p=p_theta_given_data)
    intervals = hpd(x, alpha=1 - credib)

    # Plot the results.
    plt.figure(figsize=(12, 12))
    plt.subplots_adjust(hspace=0.7)

    #    # Plot the prior.
    locx = 0.05
    mean_theta = sum(theta * p_theta)  # mean of prior, for plotting
    plt.subplot(3, 1, 1)
    plt.plot(theta, p_theta)
    plt.xlim(0, 1)
    plt.ylim(0, np.max(p_theta) * 1.2)
    plt.xlabel(r'$\theta$')
    plt.ylabel(r'$P(\theta)$')
    plt.title('Prior')
    plt.text(locx, np.max(p_theta) / 2, r'mean($\theta$;%5.2f)' % mean_theta)
    # Plot the likelihood:
    plt.subplot(3, 1, 2)
    plt.plot(theta, p_data_given_theta)
    plt.xlim(0, 1)
    plt.ylim(0, np.max(p_data_given_theta) * 1.2)
    plt.xlabel(r'$\theta$')
    plt.ylabel(r'$P(D|\theta)$')
    plt.title('Likelihood')
    plt.text(locx, np.max(p_data_given_theta) / 2, 'data: z=%s, N=%s' % (z, N))
    # Plot the posterior:
    mean_theta_given_data = sum(theta * p_theta_given_data)
    plt.subplot(3, 1, 3)
    plt.plot(theta, p_theta_given_data)
    plt.xlim(0, 1)
    plt.ylim(0, np.max(p_theta_given_data) * 1.2)
    plt.xlabel(r'$\theta$')
    plt.ylabel(r'$P(\theta|D)$')
    plt.title('Posterior')
    loc = np.linspace(0, np.max(p_theta_given_data), 5)
    plt.text(locx, loc[1], r'mean($\theta$;%5.2f)' % mean_theta_given_data)
    plt.text(locx, loc[2], 'P(D) = %g' % p_data)
    # Plot the HDI
    plt.text(locx, loc[3],
             'Intervals =%s' % ', '.join('%.3f' % x for x in intervals))
    for i in range(0, len(intervals), 2):
        plt.fill_between(theta,
                         0,
                         p_theta_given_data,
                         where=np.logical_and(theta > intervals[i],
                                              theta < intervals[i + 1]),
                         color='blue',
                         alpha=0.3)
    plt.savefig('Figure_6.1.png')
    plt.show()
    return p_theta_given_data
def plot_post(
    param_sample_vec,
    cred_mass=0.95,
    comp_val=False,
    ROPE=False,
    ylab="",
    xlab="parameter",
    fontsize=14,
    title="",
    facecolor="skyblue",
    edgecolor="white",
    show_mode=True,
    bins=50,
):

    # compute HDI
    HDI = hpd(param_sample_vec, 1 - cred_mass)

    post_summary = {
        "mean": 0,
        "median": 0,
        "mode": 0,
        "hdi_mass": 0,
        "hdi_low": 0,
        "hdi_high": 0,
        "comp_val": 0,
        "pc_gt_comp_val": 0,
        "ROPE_low": 0,
        "ROPE_high": 0,
        "pc_in_ROPE": 0,
    }
    post_summary["mean"] = np.mean(param_sample_vec)
    post_summary["median"] = np.median(param_sample_vec)
    post_summary["mode"] = stats.mode(param_sample_vec)[0]
    post_summary["hdi_mass"] = cred_mass
    post_summary["hdi_low"] = HDI[0]
    post_summary["hdi_high"] = HDI[1]

    # Plot histogram.
    n, bins, patches = plt.hist(param_sample_vec, normed=True, bins=bins, edgecolor=edgecolor, facecolor=facecolor)
    plt.xlabel(xlab, fontsize=fontsize)
    plt.ylabel(ylab, fontsize=fontsize)
    plt.title(title, fontsize=fontsize)

    idx = (np.abs(bins - comp_val)).argmin()  # index of the nearest value to comp_val
    cvHt = n[idx - 1]
    cenTendHt = 0.9 * cvHt
    ROPEtextHt = 0.55 * cvHt
    #    # Display mean or mode:
    if show_mode:
        plt.plot(0, label="mode = %.2f" % post_summary["mode"], alpha=0)
    else:
        plt.plot(0, label="mean = %.2f" % post_summary["mean"], alpha=0)
    # Display the comparison value.

    if comp_val is not False:
        pc_gt_comp_val = 100 * np.sum(param_sample_vec > comp_val) / len(param_sample_vec)
        pc_lt_comp_val = 100 - pc_gt_comp_val
        plt.plot(
            [comp_val, comp_val],
            [0, cvHt],
            color="darkgreen",
            linestyle="--",
            linewidth=2,
            label="%.1f%% <%.1f < %.1f%%" % (pc_lt_comp_val, comp_val, pc_gt_comp_val),
        )
        post_summary["comp_val"] = comp_val
        post_summary["pc_gt_comp_val"] = pc_gt_comp_val
    #    # Display the ROPE.
    if ROPE is not False:
        rope_col = "darkred"
        pc_in_ROPE = round(
            np.sum((param_sample_vec > ROPE[0]) & (param_sample_vec < ROPE[1])) / len(param_sample_vec) * 100
        )
        plt.plot(
            [ROPE[0], ROPE[0]],
            [0, 0.96 * ROPEtextHt],
            color=rope_col,
            linestyle=":",
            linewidth=4,
            label="%.1f%% in ROPE" % pc_in_ROPE,
        )
        plt.plot([ROPE[1], ROPE[1]], [0, 0.96 * ROPEtextHt], color=rope_col, linestyle=":", linewidth=4)
        post_summary["ROPE_low"] = ROPE[0]
        post_summary["ROPE_high"] = ROPE[1]
        post_summary["pc_in_ROPE"] = pc_in_ROPE
    #    # Display the HDI.
    plt.plot(HDI, [0, 0], linewidth=6, color="k", label="HDI %.1f%% %.3f-%.3f" % (cred_mass * 100, HDI[0], HDI[1]))
    plt.legend(loc="upper left")
    return post_summary
Esempio n. 6
0
#	locyp, locint = [], []
#	for ttt in tt:
#		locyp.append(xtest)
#		locint.append(pdftest)
#	yp.append(locyp)
#	integrall.append(locint)


###############################################################################
# Compute credibility intervals for each experiment:

beta = []
for x_L, pdf_L, obs_L in zip(allYP, allINTEGRAL, allh):
	beta_loc = []
	for x, pdf, obs in zip(x_L, pdf_L, obs_L):
		beta_loc.append( hpd(x, pdf, obs) )
	beta.append(beta_loc)

print '# betas!'
for i in xrange(len(beta[0])-1):
	#print allYP[i], beta[i]
	print times[i], 1-beta[1][i] 

###############################################################################
# Plot posterior for obs along with obs for a few cases
# and save it to a file
Obs_ind = [5, 20, 35]
for beta_loc, filename, x_L, pdf_L, obs_L in zip(beta, DataFilesNames, allYP, allINTEGRAL, allh):
	justnameoffile, extension = os.path.splitext(filename)

	maxind = np.where(beta_loc == max(beta_loc))[0][0]
def bern_beta(prior_shape, data_vec, cred_mass=0.95):
    """Bayesian updating for Bernoulli likelihood and beta prior.
     Input arguments:
       prior_shape
         vector of parameter values for the prior beta distribution.
       data_vec
         vector of 1's and 0's.
       cred_mass
         the probability mass of the HDI.
     Output:
       post_shape
         vector of parameter values for the posterior beta distribution.
     Graphics:
       Creates a three-panel graph of prior, likelihood, and posterior
       with highest posterior density interval.
     Example of use:
     post_shape = bern_beta(prior_shape=[1,1] , data_vec=[1,0,0,1,1])"""

    # Check for errors in input arguments:
    if len(prior_shape) != 2:
        sys.exit('prior_shape must have two components.')
    if any([i < 0 for i in prior_shape]):
        sys.exit('prior_shape components must be positive.')
    if any([i != 0 and i != 1 for i in data_vec]):
        sys.exit('data_vec must be a vector of 1s and 0s.')
    if cred_mass <= 0 or cred_mass >= 1.0:
        sys.exit('cred_mass must be between 0 and 1.')

    # Rename the prior shape parameters, for convenience:
    a = prior_shape[0]
    b = prior_shape[1]
    # Create summary values of the data:
    z = sum(data_vec[data_vec == 1])  # number of 1's in data_vec
    N = len(data_vec)   # number of flips in data_vec
    # Compute the posterior shape parameters:
    post_shape = [a+z, b+N-z]
    # Compute the evidence, p(D):
    p_data = beta_func(z+a, N-z+b)/beta_func(a, b)
    # Construct grid of theta values, used for graphing.
    bin_width = 0.005  # Arbitrary small value for comb on theta.
    theta = np.arange(bin_width/2, 1-(bin_width/2)+bin_width, bin_width)
    # Compute the prior at each value of theta.
    p_theta = beta.pdf(theta, a, b)
    # Compute the likelihood of the data at each value of theta.
    p_data_given_theta = theta**z * (1-theta)**(N-z)
    # Compute the posterior at each value of theta.
    post_a = a + z
    post_b = b+N-z
    p_theta_given_data = beta.pdf(theta, a+z, b+N-z)
    # Determine the limits of the highest density interval
    x = np.random.beta(a=post_shape[0], b=post_shape[1], size=5000)
    intervals = hpd(x, alpha=1-cred_mass)  # hdp is a function from PyMC package
                                          # takes a sample vector as input, not
                                          # a function, like the HDIofICDF.R

    # Plot the results.
    plt.figure(figsize=(12, 12))
    plt.subplots_adjust(hspace=0.7)

    # Plot the prior.
    locx = 0.05
    plt.subplot(3, 1, 1)
    plt.plot(theta, p_theta)
    plt.xlim(0, 1)
    plt.ylim(0, np.max(p_theta)*1.2)
    plt.xlabel('$\\theta$')
    plt.ylabel('$P(\\theta)$')
    plt.title('Prior')
    plt.text(locx, np.max(p_theta)/2, 'beta($\\theta$;%s,%s)' % (a, b))
    # Plot the likelihood:
    plt.subplot(3, 1, 2)
    plt.plot(theta, p_data_given_theta)
    plt.xlim(0, 1)
    plt.ylim(0, np.max(p_data_given_theta)*1.2)
    plt.xlabel('$\\theta$')
    plt.ylabel('$P(D|\\theta)$')
    plt.title('Likelihood')
    plt.text(locx, np.max(p_data_given_theta)/2, 'Data: z=%s, N=%s' % (z, N))
    # Plot the posterior:
    plt.subplot(3, 1, 3)
    plt.plot(theta, p_theta_given_data)
    plt.xlim(0, 1)
    plt.ylim(0, np.max(p_theta_given_data)*1.2)
    plt.xlabel('$\\theta$')
    plt.ylabel('$P(\\theta|D)$')
    plt.title('Posterior')
    locy = np.linspace(0, np.max(p_theta_given_data), 5)
    plt.text(locx, locy[1], 'beta($\\theta$;%s,%s)' % (post_a, post_b))
    plt.text(locx, locy[2], 'P(D) = %g' % p_data)
    # Plot the HDI
    plt.text(locx, locy[3],
             'Intervals =%s' % ', '.join('%.3f' % x for x in intervals))
    for i in range(0, len(intervals), 2):
        plt.fill_between(theta, 0, p_theta_given_data,
                         where=np.logical_and(theta > intervals[i],
                                              theta < intervals[i+1]),
                        color='blue', alpha=0.3)
    return intervals
Esempio n. 8
0
def plot_post(param_sample_vec, cred_mass=0.95, comp_val=None,
              ROPE=None, ylab='', xlab='parameter', fontsize=14, labelsize=14,
              title='', framealpha=1, show_mode=True, bins=50, kde_plot=True, 
              roundto=3):
    """
    Write me!
    """        
    # colors taken from the default seaborn color pallete
    blue, green, red = [(0.2980392156862745, 0.4470588235294118, 
    0.6901960784313725), (0.3333333333333333, 0.6588235294117647, 
    0.40784313725490196), (0.7686274509803922, 0.3058823529411765, 
    0.3215686274509804)]
    ## Compute HDI
    HDI = hpd(param_sample_vec, 1-cred_mass)

    post_summary = {'mean':0,'median':0,'mode':0, 'hdi_mass':0,'hdi_low':0,
                   'hdi_high':0, 'comp_val':0, 'pc_gt_comp_val':0, 'ROPE_low':0,
                   'ROPE_high':0, 'pc_in_ROPE':0}

    post_summary['mean'] = round(np.mean(param_sample_vec), roundto)
    post_summary['median'] = round(np.median(param_sample_vec), roundto)
    post_summary['mode'] = round(stats.mode(param_sample_vec)[0], roundto)
    post_summary['hdi_mass'] = cred_mass
    post_summary['hdi_low'] = round(HDI[0], roundto)
    post_summary['hdi_high'] = round(HDI[1], roundto)

    ## Plot KDE.
    if kde_plot:
            density = stats.kde.gaussian_kde(param_sample_vec)
            l = np.min(param_sample_vec)
            u = np.max(param_sample_vec)
            x = np.linspace(0, 1, 100) * (u - l) + l
            plt.plot(x, density(x), color=blue)
    ## Plot histogram.
    else:
        plt.hist(param_sample_vec, normed=True, bins=bins, facecolor=blue, 
        edgecolor='w')


    ## Display mean or mode:
    if show_mode:
        plt.plot(0, label='mode = %.2f' % post_summary['mode'], alpha=0)
    else:
        plt.plot(0, label='mean = %.2f' % post_summary['mean'], alpha=0)
    ## Display the comparison value.
    if comp_val is not None:
        pc_gt_comp_val = 100 * np.sum(param_sample_vec > comp_val)/len(param_sample_vec)
        pc_lt_comp_val = 100 - pc_gt_comp_val
        plt.axvline(comp_val, ymax=.75, color=green,
                 linestyle='--', linewidth=4,
                 label='%.1f%% < %.1f < %.1f%%'
                 % (pc_lt_comp_val, comp_val, pc_gt_comp_val))
        post_summary['comp_val'] = comp_val
        post_summary['pc_gt_comp_val'] = pc_gt_comp_val
    ## Display the ROPE.
    if ROPE is not None:
        rope_col = 'darkred'
        pc_in_ROPE = round(np.sum((param_sample_vec > ROPE[0]) & (param_sample_vec < ROPE[1]))/len(param_sample_vec)*100)
        plt.axvline(ROPE[0], ymax=.75, color=red, linewidth=4,
                label='%.1f%% in ROPE' % pc_in_ROPE)
        plt.axvline(ROPE[1], ymax=.75, color=red, linewidth=4)
        post_summary['ROPE_low'] = ROPE[0] 
        post_summary['ROPE_high'] = ROPE[1] 
        post_summary['pc_in_ROPE'] = pc_in_ROPE

    ## Display the HDI.
    plt.plot(HDI, [0, 0], linewidth=8, color='k', label='HDI %.1f%% %.3f-%.3f' % (cred_mass*100, HDI[0], HDI[1]))

    plt.xlabel(xlab, fontsize=fontsize)
    plt.ylabel(ylab, fontsize=fontsize)
    plt.title(title, fontsize=fontsize)
    plt.legend(loc='upper left', fontsize=labelsize, framealpha=framealpha)
    frame = plt.gca()
    frame.axes.get_yaxis().set_ticks([])
    return post_summary