Skip to content

Instantly share code, notes, and snippets.

@albertbuchard
Last active March 19, 2024 18:25
Show Gist options
  • Save albertbuchard/e2f4f05e5d506ec67cb0a77e31f5e8dc to your computer and use it in GitHub Desktop.
Save albertbuchard/e2f4f05e5d506ec67cb0a77e31f5e8dc to your computer and use it in GitHub Desktop.
Parallelizing Simulations to Calculate HH vs HT Win Rates
from concurrent.futures import ProcessPoolExecutor
import numpy as np
from scipy.signal import convolve2d
from tqdm import tqdm
nsims = int(1e6)
nevents = int(1e5)
def convolve_nsims(chunk):
nsims, nevents = chunk
matrix = np.random.choice([-1, 1], size=(nsims, nevents))
pattern1 = np.array([-0.5, -0.5]) # Alice wins
pattern2 = np.array([-0.5, 0.5]) # Bob wins
convolved1 = convolve2d(matrix, pattern1.reshape(1, -1), mode='valid')
convolved2 = convolve2d(matrix, pattern2.reshape(1, -1), mode='valid')
convolved1_thresholded = np.where(convolved1 < 1, 0, convolved1)
convolved2_thresholded = np.where(convolved2 < 1, 0, convolved2)
win_alice = np.sum(convolved1_thresholded, axis=1)
win_bob = np.sum(convolved2_thresholded, axis=1)
win_rates = win_alice / (win_bob + win_alice)
return win_rates
if __name__ == "__main__":
chunk_size = 1000
nsim = 0
win_rate_alice = 0
if chunk_size > nsims:
chunk_size = nsims
chunks = [(min(chunk_size, nsims - i), nevents) for i in range(0, nsims, chunk_size)]
with ProcessPoolExecutor() as executor:
for win_rates in tqdm(executor.map(convolve_nsims, chunks), total=len(chunks),
desc=f"Parallel simulation by chunk of {chunk_size}"):
win_rate_alice = (win_rate_alice * nsim) + np.sum(win_rates)
nsim += win_rates.shape[0]
win_rate_alice /= nsim
print(f"Win Rate For Alice After {nsims} simulations with {nevents} events each: {win_rate_alice}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment