-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathsimulate_sin.py
108 lines (83 loc) · 2.91 KB
/
simulate_sin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import numpy as np
import matplotlib.pyplot as plt
from fbm import FBM
def generate_sin(x, T, A):
"""Generate a mixed sinusoidal sequence"""
y = np.zeros(len(x))
for i in range(len(T)):
y += A[i] * np.sin(2 * np.pi / T[i] * x)
return y
def gen_covariates(x, index):
"""Generate covariates"""
covariates = np.zeros((x.shape[0], 4))
covariates[:, 0] = (x // 24) % 7
covariates[:, 1] = x % 24
covariates[:, 2] = (x // (24 * 30)) % 12
covariates[:, 0] = covariates[:, 0] / 6
covariates[:, 1] = covariates[:, 1] / 23
covariates[:, 2] = covariates[:, 2] / 11
covariates[:, -1] = np.zeros(x.shape[0]) + index
return covariates
def fractional_brownian_noise(length, hurst, step):
"""Genereate fractional brownian noise"""
f = FBM(length, hurst, step)
noise = f.fbm()
return noise
def synthesis_data():
"""synthesis a mixed sinusoidal dataset"""
T = [24, 168, 720]
seq_num = 60
seq_len = T[-1] * 20
data = []
covariates = []
for i in range(seq_num):
start = int(np.random.uniform(0, T[-1]))
x = start + np.arange(seq_len)
A = np.random.uniform(5, 10, 3)
y = generate_sin(x, T, A)
data.append(y)
covariates.append(gen_covariates(x, i))
# plt.plot(x[:T[-1]], y[:T[-1]])
# plt.show()
data = np.array(data)
mean, cov = polynomial_decay_cov(seq_len)
noise = multivariate_normal(mean, cov, seq_num)
data = data + noise
covariates = np.array(covariates)
data = np.concatenate([data[:, :, None], covariates], axis=2)
np.save('data/synthetic.npy', data)
def covariance(data):
"""compute the covariance of the data"""
data_mean = data.mean(0)
data = data - data_mean
length = data.shape[1]
data_covariance = np.zeros((length, length))
for i in range(length):
for j in range(length):
data_covariance[i, j] = (data[:, i] * data[:, j]).mean()
return data_covariance
def test_fbm():
"""Plot the covariance of the generated fractional brownian noise"""
f = FBM(300, 0.3, 1)
fbm_data = []
for i in range(100):
sample = f.fbm()
fbm_data.append(sample[1:])
fbm_data = np.array(fbm_data)
cov = covariance(fbm_data)
plt.imshow(cov)
plt.savefig('fbm_cov.jpg')
def polynomial_decay_cov(length):
"""Define the function of covariance decay with distance"""
mean = np.zeros(length)
x_axis = np.arange(length)
distance = x_axis[:, None] - x_axis[None, :]
distance = np.abs(distance)
cov = 1 / (distance + 1)
return mean, cov
def multivariate_normal(mean, cov, seq_num):
"""Generate multivariate normal distribution"""
noise = np.random.multivariate_normal(mean, cov, (seq_num,), 'raise')
return noise
if __name__ == '__main__':
synthesis_data()