Skip to content

Instantly share code, notes, and snippets.

@kstoneriv3
Created February 1, 2024 14:37
Show Gist options
  • Save kstoneriv3/c1627285d5c52511dd82dfe26ccc4779 to your computer and use it in GitHub Desktop.
Save kstoneriv3/c1627285d5c52511dd82dfe26ccc4779 to your computer and use it in GitHub Desktop.
Visualization of Brownian bridge construction of a Brownian motion
"""Visualization of Brownian bridge construction of a Brownian motion."""
import numpy as np
from matplotlib import pyplot as plt
T = 1
TAB10_CMAP = plt.get_cmap("tab10")
DEFAULT_COLOR = TAB10_CMAP(0)
def generate_brownian_path(num_steps, level=0):
np.random.seed(level)
if level == 0:
time = np.arange(num_steps + 1) / num_steps
eps = np.concatenate([np.zeros(1), np.random.randn(num_steps)])
path = np.cumsum(eps) / np.sqrt(num_steps)
elif level > 0:
time = np.arange(num_steps * 2 ** level + 1) / (num_steps * 2 ** level)
_, path0 = generate_brownian_path(num_steps, level - 1)
eps = np.random.randn(num_steps * 2 ** (level - 1))
path = np.empty((num_steps * 2 ** level + 1,))
path[::2] = path0
path[1::2] = (path0[:-1] + path0[1:]) / 2 + eps / np.sqrt(2 * num_steps * 2 ** level)
else:
raise ValueError("level must be non-negative integer.")
return time, path
def plot_bridge_construction(max_level=5):
for level in range(max_level):
time, path = generate_brownian_path(1, level)
if level == 0:
plot_axis()
plt.plot(time, path, c=DEFAULT_COLOR, alpha=1 / max_level)
elif level > 0:
plt.plot(time, path, linestyle='-', c=DEFAULT_COLOR, alpha=(level + 1) / max_level)
else:
raise ValueError("level must be non-negative integer.", c=0)
plt.xlabel('Time t')
plt.ylabel('Path')
plt.xlim([-0.2, 1.1])
plt.ylim([-0.5, 3.0])
def plot_axis():
ax = plt.gca()
ax.axis("off")
plt.axhline(0,color='black') # x = 0
plt.axvline(0,color='black') # y = 0
if __name__ == "__main__":
plt.figure(figsize=(6, 18))
for i in range(10):
plt.subplot(5, 2, i + 1)
plot_bridge_construction(i + 1)
plt.show()
@kstoneriv3
Copy link
Author

This script generates a figure like this:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment