Skip to content

Commit

Permalink
Added notes for session 9
Browse files Browse the repository at this point in the history
  • Loading branch information
LilianBittar committed May 30, 2023
1 parent 9a17de4 commit 8cc2ff0
Show file tree
Hide file tree
Showing 7 changed files with 183 additions and 0 deletions.
Binary file added session09/Markov Chains.pdf
Binary file not shown.
Binary file added session09/Matrix Algebra.pdf
Binary file not shown.
Binary file added session09/Recap Regression.pdf
Binary file not shown.
Binary file added session09/SMP 9 Template.pdf
Binary file not shown.
70 changes: 70 additions & 0 deletions session09/randomcoins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
import scipy.stats as stats
import time

def simulate_coin_tosses(n_flips, n_trials, seed=None, sleep_time = 1):
if seed is not None:
np.random.seed(seed)

# Simulate coin tosses for each trial
coin_tosses = np.random.choice([-1, 1], size=(n_trials, n_flips))

# Calculate the sum of coin tosses for each trial
coin_sums = np.sum(coin_tosses, axis=1)

return coin_sums

def plot_frequency(max_n_flips, n_trials, seed=None, sleep_time=10**-10):
for n_flips in range(1, max_n_flips + 1):
# Simulate coin tosses and calculate sums
coin_sums = simulate_coin_tosses(n_flips, n_trials, seed)

# Calculate the frequencies of each sum
frequencies = Counter(coin_sums)

# Calculate the probabilities
probabilities = {k: v / n_trials for k, v in frequencies.items()}

# Create the bar plot
plt.bar(probabilities.keys(), probabilities.values(), alpha=0.75)
plt.title(f"Frequency Plot of Coin Tosses Sum with Normal Distribution (n_flips = {n_flips})")
plt.xlabel("Sum")
plt.ylabel("Probability")
plt.grid(True)

# Calculate the mean and standard deviation of coin_sums
mean = np.mean(coin_sums)
std_dev = np.std(coin_sums)

# Generate x values for the normal distribution
x = np.linspace(min(coin_sums), max(coin_sums), 100)

# Calculate the normal distribution probability density function (PDF) values
y = stats.norm.pdf(x, mean, std_dev)

# Plot the smooth normal distribution
plt.plot(x, y, 'r', linewidth=2)

# Set x-axis ticks and limits
#plt.xticks(np.arange(-10, 11, step=1))
#plt.xlim(-10, 10)

# Show the plot and pause for a specified time
plt.draw()
plt.pause(sleep_time)

# Clear the plot for the next iteration, but not after the last n
if n_flips != max_n_flips:
plt.clf()

plt.show()

# Parameters
max_n_flips = int(input("Trials: "))
n_trials = 10000
seed = 42

# Plot the frequency plot of the coin tosses sum with normal distribution overlay in real-time
plot_frequency(max_n_flips = max_n_flips, n_trials = n_trials)
54 changes: 54 additions & 0 deletions session09/randomwalk.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import clear_output

def random_walk_1d_real_time(n_steps, seed=None, pause_time=0.01):
if seed is not None:
np.random.seed(seed)

# Initialize the position
position = 0

# Create an empty plot
plt.figure()
plt.title("1D Random Walk")
plt.xlabel("Steps")
plt.ylabel("Position")

# Initialize the position history for plotting lines
position_history = [0]

# Generate and plot each step
for i in range(n_steps):
# Generate a random step: -1 (left) or 1 (right)
step = np.random.choice([-1, 1])

# Update the position
position += step

# Update the position history
position_history.append(position)

# Update the plot
plt.plot(position_history, c='b')
plt.xlim(0, n_steps)
plt.yticks(np.arange(-10, 11, step=1))
plt.ylim(-10, 10) # Set the y-axis limits to -10 and 10

if i < n_steps - 1: # Don't clear the output on the last step
plt.pause(pause_time)
clear_output(wait=True)
else:
# Print the absolute value of the y position at the end of n steps
print(f"Absolute position at the end of {n_steps} steps: {abs(position)}")
plt.pause(pause_time)
clear_output(wait=True)

plt.show()

# Parameters
n_steps = 100
pause_time = 0.01

# Simulate and visualize the random walk in real-time without a specific seed
random_walk_1d_real_time(n_steps, pause_time=pause_time)
59 changes: 59 additions & 0 deletions session09/randomwalk2d.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import numpy as np
import matplotlib.pyplot as plt
import time

def random_walk_2d_step(x, y):
step = np.random.choice(['up', 'down', 'left', 'right'])

if step == 'up':
y += 1
elif step == 'down':
y -= 1
elif step == 'left':
x -= 1
elif step == 'right':
x += 1

return x, y

def plot_random_walk_2d_realtime(n_steps, seed=None, sleep_time=0.3):
if seed is not None:
np.random.seed(seed)

x_positions = [0]
y_positions = [0]

plt.ion() # Enable interactive mode
plt.title("2D Random Walk")
plt.xlabel("X")
plt.ylabel("Y")
plt.grid(True)

# Set fixed axis limits
plt.xlim(-10, 10)
plt.ylim(-10, 10)

# Add "Start" text at the starting point
plt.text(x_positions[0], y_positions[0], "Start", fontsize=12, color='red')

for i in range(n_steps):
x, y = random_walk_2d_step(x_positions[-1], y_positions[-1])
x_positions.append(x)
y_positions.append(y)

plt.plot(x_positions[-2:], y_positions[-2:], marker='o', markersize=5, linestyle='-')
plt.draw()
plt.pause(sleep_time)

# Add "Finish" text at the ending point
plt.text(x_positions[-1], y_positions[-1], "Finish", fontsize=12, color='green')

plt.ioff() # Disable interactive mode
plt.show()

# Parameters
n_steps = 50
seed = 42

# Simulate and plot the 2D random walk in real-time
plot_random_walk_2d_realtime(n_steps)

0 comments on commit 8cc2ff0

Please sign in to comment.