示例#1
0
def get_wavelet_var(wavelet, H=0.3, samp_size=1024, plot_sil=1):
    f = FBM(n=samp_size, hurst=H, length=0.5, method='daviesharte')
    fbm_sample = f.fbm()
    t_values = f.times()
    cA, cD = pywt.dwt(fbm_sample, wavelet)

    M = len(cD)
    R = np.zeros(M + 1)

    for k in range(M + 1):
        cD_shift = shift(cD, k, cval=0)
        R[k] = np.sum(cD * np.conjugate(cD_shift))

    print(M + 1)
    print(np.argmin(R))
    plt.plot(R)
    plt.show()
    AutoCorr_mat = toeplitz(R[0:M], R[0:M]) + 2.5
    #pdb.set_trace()

    mean_corr = (np.sum(AutoCorr_mat) - M * AutoCorr_mat[0][0]) / (M**2 - M)
    #print(mean_corr)
    max_corr = np.max(R[1:])
    #pdb.set_trace()
    U, S, V = svd(AutoCorr_mat)
    if (plot_sil != 1):
        plt.plot(np.log10(np.arange(M) + 1), np.log10(S))

    return S[0], 1 + (M - 1) * mean_corr
def simulate_fbm_df(d_const, n_dim, n_steps, dt, loc_std=0, hurst=0.5):
    """Simulate and output a single trajectory of fractional brownian motion in a specified number of dimensions.

    :param d_const: diffusion constant in um2/s
    :param n_dim: number of spatial dimensions for simulation (1, 2, or 3)
    :param n_steps: trajectory length (number of steps)
    :param dt: timestep size (s)
    :param loc_std: standard deviation for Gaussian localization error (um)
    :param hurst: Hurst index in range (0,1), hurst=0.5 gives brownian motion
    :return: trajectory dataframe (position in n_dim dimensions, at each timepoint)
    """

    np.random.seed()

    # create fractional brownian motion trajectory generator
    # Package ref: https://github.com/crflynn/fbm
    f = FBM(n=n_steps, hurst=hurst, length=n_steps * dt, method='daviesharte')

    # get time list and trajectory where each timestep has and n-dimensional vector step size
    t_values = f.times()
    fbm_sim = []
    for dim in range(n_dim):
        fbm_sim.append(f.fbm() * np.sqrt(2 * d_const))

    df = pd.DataFrame()
    for i in range(n_steps):

        x_curr = [fbm_sim[dim][i] for dim in range(n_dim)]
        # for initial time point, start at origin and optionally add noise
        if i == 0:
            x_obs_curr = [
                x_curr[dim] + loc_std * np.random.randn()
                for dim in range(n_dim)
            ]
        # for latter timepoints, set "current" position to position determined by displacement out of the last timepoint
        else:
            x_obs_curr = x_obs_next

        # Get next n-dimensional position
        x_next = [fbm_sim[dim][i + 1] for dim in range(n_dim)]
        # Get noise to add to next position, to get the observed position
        noise_next = [loc_std * np.random.randn() for _dim in range(n_dim)]
        x_obs_next = [x_next[dim] + noise_next[dim] for dim in range(n_dim)]
        # break current and next position into vector and magnitdue displacements
        dx_obs = [x_obs_next[dim] - x_obs_curr[dim] for dim in range(n_dim)]
        dx = [x_next[dim] - x_curr[dim] for dim in range(n_dim)]
        dr_obs = np.linalg.norm(dx_obs)
        dr = np.linalg.norm(dx)
        t = t_values[i]

        # Add timestep data to dataframe
        data = {
            't_step': t,
            'x': x_curr,
            'x_obs': x_obs_curr,
            'dx': dx,
            'dx_obs': dx_obs,
            'dr': dr,
            'dr_obs': dr_obs
        }
        df = df.append(data, ignore_index=True)

    return df
from fbm import FBM
import matplotlib.pyplot as plt

f = FBM(n=100, hurst=0.9, length=1, method='daviesharte')

# Generate a fBm realization
fbm_sample = f.fbm()

# Generate a fGn realization
fgn_sample = f.fgn()

# Get the times associated with the fBm
t_values = f.times()
plt.plot(t_values, fbm_sample)
plt.show()
示例#4
0
phi = norm.cdf(u * T**(-H) + c2 * T**(1 - H))
phi = norm.cdf((u + c2 * T) / (sigma * T**H))
print("u=%.4f  H=%.4f" % (u, H))
print("theoretical upper bound = %.3f" %
      (1 - phi + exp(-2 * u * c2 * T**(1 - 2 * H) / sigma**2) * phi))

## =================================================================
##  分形布朗运动模拟
## =================================================================

from fbm import FBM
from tqdm import trange

f = FBM(n=1000, hurst=H, length=T, method='daviesharte')
for i in trange(实验次数, ncols=80):
    fbm_ts = f.times()
    fbm_asset = f.fbm()
    fbm_asset = [
        u + c2 * fbm_ts[i] - amp**H * fbm_asset[i]
        for i in range(len(fbm_asset))
    ]

    for i in range(len(fbm_asset)):
        if fbm_asset[i] < 0:
            fbm_ts = fbm_ts[:i + 1]
            fbm_asset = fbm_asset[:i + 1]
            break

    if fbm_asset[-1:][0] < 0:
        #print("Ruin time=",fbm_ts[len(fbm_asset)-1],"asset=",fbm_asset[-1:][0])
        破产次数 += 1
示例#5
0
# flake8: noqa
from fbm import FBM
import matplotlib.pyplot as plt
import time
import math
import numpy as np


def h(s):
    # return 0.499*math.sin(t) + 0.5
    # return 0.6 * t + 0.3
    return 0.5 * np.exp(-8.0 * s**2)


fbm_generator = FBM(2**8, 0.85)
t = fbm_generator.times()
fbm_realization = fbm_generator.fbm()
fgn_realization = fbm_generator.fgn()
h_t = np.array(h(fbm_realization))
plt.plot(t, fbm_realization)
plt.plot(t, h_t)
# plt.plot(t[0:-1], fgn_realization)
plt.show()
    # Generate Unaltered Test Data
    data_x_test = np.sort(
        np.random.uniform(low=-(1 + Extrapolation_size),
                          high=(1 + Extrapolation_size),
                          size=N_test))

    data_y_test = unknown_f(data_x_test)

    # Generate Unaltered Training Data
    data_x = np.sort(np.random.uniform(low=-1, high=1, size=N_train))
    data_y = unknown_f(data_x)
else:
    # Generate Fractional Data
    FBM_Generator = FBM(n=N_data, hurst=0.75, length=1, method='daviesharte')
    data_y_outputs_full = FBM_Generator.fbm()
    data_x_outputs_full = FBM_Generator.times()
    # Partition Data
    data_x, data_x_test, data_y, data_y_test = train_test_split(
        data_x_outputs_full,
        data_y_outputs_full,
        test_size=Test_set_proportion,
        random_state=2020,
        shuffle=True)

    # Reorder Train Set
    indices_train = np.argsort(data_x)
    data_x = data_x[indices_train]
    data_y = data_y[indices_train]

    # Reorder Test Set
    indices_test = np.argsort(data_x_test)
示例#7
0
def test_FBM_times(n_good, hurst_good, length_good, fbm_method_good):
    f = FBM(n_good, hurst_good, length_good, fbm_method_good)
    ts = f.times()
    assert isinstance(ts, np.ndarray)
    assert len(ts) == n_good + 1