import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

# Target distribution f(x): Mixture of two Gaussians
def f(x):
    return 0.5 * norm.pdf(x, loc=-2, scale=1) + 0.5 * norm.pdf(x, loc=3, scale=1)

# Proposal distributions g1(x) and g2(x)
def g1(x):
    return norm.pdf(x, loc=0.5, scale=2.5)

def g2(x):
    return norm.pdf(x, loc=0, scale=1)

# Number of samples
N = 10000

# Draw samples from g1 and g2
samples_g1 = np.random.normal(loc=0.5, scale=2.5, size=N)
samples_g2 = np.random.normal(loc=0, scale=1, size=N)

# Calculate importance weights
weights_g1 = f(samples_g1) / g1(samples_g1)
weights_g2 = f(samples_g2) / g2(samples_g2)

# Resampling according to weights
resampled_g1 = np.random.choice(samples_g1, size=N, p=weights_g1/weights_g1.sum())
resampled_g2 = np.random.choice(samples_g2, size=N, p=weights_g2/weights_g2.sum())

# Plotting histograms
plt.figure(figsize=(12, 6))

# Histogram for g1
plt.subplot(1, 2, 1)
plt.hist(resampled_g1, bins=30, density=True, alpha=0.6, color='b', label='Resampled g1')
x = np.linspace(-6, 8, 1000)
plt.plot(x, f(x), 'r--', label='f(x) Target Distribution')
plt.title('Resampled Points from g1(x)')
plt.legend()

# Histogram for g2
plt.subplot(1, 2, 2)
plt.hist(resampled_g2, bins=30, density=True, alpha=0.6, color='g', label='Resampled g2')
plt.plot(x, f(x), 'r--', label='f(x) Target Distribution')
plt.title('Resampled Points from g2(x)')
plt.legend()

plt.show()
