|
| 1 | +import streamlit as st |
| 2 | +import numpy as np |
| 3 | +import matplotlib.pyplot as plt |
| 4 | +import scipy.special |
| 5 | +import math |
| 6 | +from scipy.stats import multivariate_normal |
| 7 | +st.title("Probability Explorer") |
| 8 | + |
| 9 | +# Create two columns for layout |
| 10 | +left_col, right_col = st.columns([1, 2]) |
| 11 | + |
| 12 | +with left_col: |
| 13 | + # Add interactive elements for probability exploration |
| 14 | + # Select distribution type |
| 15 | + dist_type = st.selectbox( |
| 16 | + 'Select probability distribution', |
| 17 | + ['Multivariate Normal', 'Binomial', 'Normal', 'Poisson', 'Uniform'] |
| 18 | + ) |
| 19 | + st.write(f'Selected distribution: {dist_type}') |
| 20 | + |
| 21 | + # Parameters based on distribution type |
| 22 | + if dist_type == 'Multivariate Normal': |
| 23 | + st.write('Mean Vector:') |
| 24 | + mean1 = st.slider('μ₁', -5.0, 5.0, 0.0, 0.1) |
| 25 | + mean2 = st.slider('μ₂', -5.0, 5.0, 0.0, 0.1) |
| 26 | + |
| 27 | + st.write('Covariance Matrix:') |
| 28 | + var1 = st.slider('σ₁²', 0.1, 5.0, 1.0, 0.1) |
| 29 | + var2 = st.slider('σ₂²', 0.1, 5.0, 1.0, 0.1) |
| 30 | + corr = st.slider('Correlation ρ', -1.0, 1.0, 0.0, 0.1) |
| 31 | + |
| 32 | + # Calculate covariance from correlation |
| 33 | + cov12 = corr * np.sqrt(var1 * var2) |
| 34 | + |
| 35 | + # Display covariance matrix |
| 36 | + cov_matrix = np.array([[var1, cov12], [cov12, var2]]) |
| 37 | + st.write("Covariance Matrix:") |
| 38 | + st.write(cov_matrix) |
| 39 | + |
| 40 | + elif dist_type == 'Normal': |
| 41 | + mean = st.slider('Mean', -10.0, 10.0, 0.0, 0.1) |
| 42 | + std = st.slider('Standard deviation', 0.1, 5.0, 1.0, 0.1) |
| 43 | + st.write(f'Mean: {mean}, Standard deviation: {std}') |
| 44 | + elif dist_type == 'Uniform': |
| 45 | + a = st.slider('Lower bound (a)', -10.0, 10.0, 0.0, 0.1) |
| 46 | + b = st.slider('Upper bound (b)', -10.0, 10.0, 1.0, 0.1) |
| 47 | + if b <= a: |
| 48 | + st.error('Upper bound must be greater than lower bound') |
| 49 | + b = a + 0.1 |
| 50 | + else: |
| 51 | + # Slider for probability value |
| 52 | + probability = st.slider('Select a probability value', 0.0, 1.0, 0.5, 0.1) |
| 53 | + st.write(f'Selected probability: {probability}') |
| 54 | + |
| 55 | + # Number of trials input |
| 56 | + trials = st.number_input('Number of trials', min_value=1, value=100) |
| 57 | + st.write(f'Number of trials: {trials}') |
| 58 | + |
| 59 | + # Add auto-update toggle |
| 60 | + auto_update = st.checkbox('Auto-update plot', value=True) |
| 61 | + |
| 62 | + # Set confidence level |
| 63 | + confidence = 0.95 |
| 64 | + |
| 65 | +def calculate_and_plot(): |
| 66 | + # Add these lines at the start of the function to access the variables |
| 67 | + global mean, std, probability, trials, a, b, mean1, mean2, var1, var2, cov12 |
| 68 | + |
| 69 | + with right_col: |
| 70 | + st.write('Calculating probability distribution...') |
| 71 | + |
| 72 | + # Display formula based on distribution type |
| 73 | + if dist_type == 'Multivariate Normal': |
| 74 | + st.latex(r'f(x) = \frac{1}{2\pi|\Sigma|^{1/2}} \exp\left(-\frac{1}{2}(x-\mu)^T\Sigma^{-1}(x-\mu)\right)') |
| 75 | + elif dist_type == 'Normal': |
| 76 | + st.latex(r'f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}') |
| 77 | + elif dist_type == 'Binomial': |
| 78 | + st.latex(r'P(X=k) = \binom{n}{k}p^k(1-p)^{n-k}') |
| 79 | + elif dist_type == 'Poisson': |
| 80 | + st.latex(r'P(X=k) = \frac{\lambda^k e^{-\lambda}}{k!}') |
| 81 | + elif dist_type == 'Uniform': |
| 82 | + st.latex(r'f(x) = \frac{1}{b-a} \text{ for } a \leq x \leq b') |
| 83 | + |
| 84 | + # Create figure |
| 85 | + fig, ax = plt.subplots() |
| 86 | + |
| 87 | + # Generate data based on selected distribution |
| 88 | + if dist_type == 'Multivariate Normal': |
| 89 | + # Create grid of points |
| 90 | + x, y = np.mgrid[-5:5:.01, -5:5:.01] |
| 91 | + pos = np.dstack((x, y)) |
| 92 | + |
| 93 | + # Define distribution parameters |
| 94 | + mean = [mean1, mean2] |
| 95 | + cov = [[var1, cov12], [cov12, var2]] |
| 96 | + |
| 97 | + # Create multivariate normal distribution |
| 98 | + rv = multivariate_normal(mean, cov) |
| 99 | + |
| 100 | + # Calculate pdf |
| 101 | + z = rv.pdf(pos) |
| 102 | + |
| 103 | + # Create contour plot |
| 104 | + plt.contourf(x, y, z, levels=20, cmap='viridis') |
| 105 | + plt.colorbar(label='Probability Density') |
| 106 | + |
| 107 | + ax.set_xlabel('X₁') |
| 108 | + ax.set_ylabel('X₂') |
| 109 | + |
| 110 | + elif dist_type == 'Normal': |
| 111 | + x = np.linspace(mean - 4*std, mean + 4*std, 100) |
| 112 | + y = np.exp(-((x - mean)**2)/(2*std**2))/(std*np.sqrt(2*np.pi)) |
| 113 | + ax.plot(x, y) |
| 114 | + elif dist_type == 'Binomial': |
| 115 | + x = np.arange(0, trials + 1) |
| 116 | + y = [scipy.special.comb(trials, k) * (probability**k) * ((1-probability)**(trials-k)) for k in x] |
| 117 | + ax.plot(x, y) |
| 118 | + elif dist_type == 'Poisson': |
| 119 | + x = np.arange(0, trials + 1) |
| 120 | + y = [(probability**k * np.exp(-probability))/math.factorial(k) for k in x] |
| 121 | + ax.plot(x, y) |
| 122 | + elif dist_type == 'Uniform': |
| 123 | + x = np.linspace(a - 0.5, b + 0.5, 100) |
| 124 | + y = np.where((x >= a) & (x <= b), 1/(b-a), 0) |
| 125 | + ax.plot(x, y) |
| 126 | + |
| 127 | + ax.set_title(f'{dist_type} Distribution') |
| 128 | + ax.grid(True) |
| 129 | + |
| 130 | + # Display plot in Streamlit |
| 131 | + st.pyplot(fig) |
| 132 | + st.success(icon="🔥", body="Distribution calculated!") |
| 133 | + |
| 134 | +# Calculate either on button press or automatically based on toggle |
| 135 | +if auto_update: |
| 136 | + calculate_and_plot() |
| 137 | +else: |
| 138 | + with left_col: |
| 139 | + if st.button('Calculate Distribution'): |
| 140 | + calculate_and_plot() |
0 commit comments