Skip to content

Instantly share code, notes, and snippets.

@joreilly86
Created August 11, 2024 05:44
Show Gist options
  • Select an option

  • Save joreilly86/4c768c15eebc6bc00d1594edbf654536 to your computer and use it in GitHub Desktop.

Select an option

Save joreilly86/4c768c15eebc6bc00d1594edbf654536 to your computer and use it in GitHub Desktop.
#043 - Bayesian Methods
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import norm
# Set the background color to black
plt.style.use('dark_background')
# Step 1: Define the prior distribution for the remaining fatigue life (in years)
prior_mean = 20 # Prior mean fatigue life in years
prior_std = 5 # Prior standard deviation in years
prior_var = prior_std**2 # Prior variance
# Step 2: Collect new data (e.g., updated stress ranges from recent inspections)
# Assume the new data suggests that the fatigue life may be shorter than previously estimated
new_data_mean = 15 # Mean fatigue life suggested by new data
new_data_std = 3 # Uncertainty in the new data (standard deviation)
# Step 3: Compute the posterior distribution using Bayesian updating
posterior_variance = 1 / (1 / prior_var + 1 / new_data_std**2)
posterior_mean = posterior_variance * (prior_mean / prior_var + new_data_mean / new_data_std**2)
posterior_std = np.sqrt(posterior_variance)
# Step 4: Visualize the prior and posterior distributions
x = np.linspace(5, 30, 500) # Range of fatigue life values to plot
# Define Flocode brand colors
prior_color = '#80F7BD' # Pastel green
posterior_color = '#60D5F9' # Pastel blue
# Create a 16:9 aspect ratio figure
plt.figure(figsize=(8, 4.5))
# Plot prior distribution
prior_pdf = norm.pdf(x, prior_mean, prior_std)
sns.lineplot(x=x, y=prior_pdf, label='Prior', color=prior_color)
# Plot posterior distribution
posterior_pdf = norm.pdf(x, posterior_mean, posterior_std)
sns.lineplot(x=x, y=posterior_pdf, label='Posterior', color=posterior_color)
# Final touches
plt.axvline(posterior_mean, color=posterior_color, linestyle='--', label=f'Posterior Mean: {posterior_mean:.2f} years')
plt.title('Bayesian Update of Bridge Fatigue Life Estimation')
plt.xlabel('Remaining Fatigue Life (years)')
plt.ylabel('Probability Density')
plt.legend()
plt.grid(True, color='#444444') # Slightly lighter grid lines for contrast
plt.show()
# Output the calculated values
print(f"Prior Mean Fatigue Life: {prior_mean} years")
print(f"Prior Standard Deviation: {prior_std} years")
print(f"Posterior Mean Fatigue Life: {posterior_mean:.2f} years")
print(f"Posterior Standard Deviation: {posterior_std:.2f} years")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment