In [ ]:
import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
from crossing_tree import crossings, crossing_tree
from crossing_tree.processes import FractionalBrownianMotion as FBM
from crossing_tree.processes import WeierstrassFunction as WEI
from crossing_tree.processes import HermiteProcess as HRP
Set the path length and the Hurst exponent
In [ ]:
N, H = 2**21+1, 0.55
gen_ = FBM(N, hurst=H, random_state=123, n_threads=2)
gen_.start()
## Generate a sample path
T, X = gen_.draw()
Get the crossing times, levels and offspring structure
In [ ]:
## Set the base scale to the median
scale = np.median(np.abs(np.diff(X)))
origin = X[0]
## Build a crossing tree
xi, ti, offspring, Vnk, Znk, Wnk = crossing_tree(X, T, scale, origin=origin)
# Rebuild the tree
index = list([offspring[0]])
for index_ in offspring[1:]:
index.append(index[-1][index_])
Xnk = [xi.base[index_] for index_ in index]
Tnk = [ti.base[index_] for index_ in index]
Choose the levels to plot.
In [ ]:
l = len(Tnk) - 2
levels = np.arange(l-4, l+1, dtype=np.int)
Plot the crossings
In [ ]:
## Plot the sample path
fig = plt.figure(figsize=(6, 5))
ax = fig.add_subplot(111)
ax.set_xticks(np.linspace(0, 1, num=11), minor=False)
ax.set_xticks(Tnk[levels[0]], minor=True)
ax.set_xticklabels(["%0.2f"%(t,) for t in np.linspace(0, 1, num=11)],
minor=False)
delta = 2 * scale * (1 << levels[0])
xm, xM = (Xnk[levels[0]] - origin).min() / delta, (Xnk[levels[0]] - origin).max() / delta
ax.set_yticks(origin + np.arange(xm-1, xM+2) * delta)
ax.plot(T, X, linestyle='-', color='gray', label='X(t)', alpha=0.5)
color=plt.cm.rainbow_r(np.linspace(0, 1, len(levels)))
for j, col_ in zip(levels, color):
ax.plot(Tnk[j], Xnk[j], '-s', color=col_, markersize=4, alpha=0.75)
ax.grid(color='k', linestyle='-', alpha=0.15, zorder=-99)
ax.set_xlim(-0.01, 1.01)
plt.savefig("../plots/sample_path.pdf", format='pdf')
plt.close();
Draw the corresponding crossing tree
In [ ]:
fig = plt.figure(figsize=(6, 5))
ax = fig.add_subplot(111)
ax.set_xticks(np.linspace(0, 1, num=11), minor=False)
ax.set_xticks(Tnk[levels[0]], minor=True)
ax.set_xticklabels(["%0.2f"%(t,) for t in np.linspace(0, 1, num=11)],
minor=False )
colors = plt.cm.rainbow_r(np.linspace(0, 1, len(levels)))
for j, col_ in zip(levels, colors):
lht0, lht1 = Tnk[j], Tnk[j+1]
offs_ = offspring[j+1]
parent = np.repeat(np.arange(len(offs_) - 1), np.diff(offs_))
parent = np.r_[parent, np.repeat(len(offs_) - 1, len(lht0) - offs_[-1])]
p_ti = np.r_[np.repeat(np.nan, offs_[0]), lht1[parent]]
## Draw the line segments between two levels
delta = (1 << j)
ax.plot([p_ti, lht0], [len(lht0) * [2 * delta], len(lht0) * [delta]],
'-s', color=col_, markersize=2, lw=.5)
ax.grid(color='k', linestyle='-', alpha=0.05, zorder=-99)
ax.set_yscale("log", basey=2)
ax.set_xlim(-0.01, 1.01)
ax.set_ylim(0.9 * (1 << levels[0]), 1.1 * (1 << levels[-1] + 1))
ax.set_ylabel(r"$\delta \times 2^k$")
plt.savefig("../plots/sample_tree.pdf", format='pdf')
plt.close();
In [ ]: