-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.py
More file actions
81 lines (61 loc) · 2.51 KB
/
basic.py
File metadata and controls
81 lines (61 loc) · 2.51 KB
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
import pystan
import numpy as np
def run_basic_sampler(d, s, transition_prior, gamma=100, beta=0.1):
# Build the stan model
code = """
data {
int N; // number of time steps
int n; // number of composited to be merged
real beta; // beta for the BT likelihood
real gamma; // gamma for the BT likelihood
vector[N] d[n]; // n-composites vectors of N-time-steps -- the data
vector[N] s[n]; // corresponding standard deviation for each data point
vector[N] m; // mean jump value for the transition prior
vector[N] q; // standard deviations for the transition prior
}
parameters {
vector[N] y; // true-time series
}
model{
// initial y-value has a broad uniform prior (default in stan if unspecified)
y[2:N] ~ normal(y[1:N-1] + m[2:N], q[2:N]);
// Likelihood
// for every time step
for(t in 1:N){
// for every composite
for(c in 1:n){
// add Box-Tiao likelihood to the "target", ie the log-likleihood
target += log_sum_exp( log(beta) + normal_lpdf(y[t] | d[c][t], gamma*s[c][t]), log(1-beta) + normal_lpdf(y[t] | d[c][t], s[c][t]) );
}
}
}
"""
# Compile the model
model = pystan.StanModel(model_code=code)
# Number of composites
n = len(d)
# Length of composites (number of time steps)
N = len(d[0])
# Construct transition prior will go here in the end...
# Construct SVD errors will go here in the end...
# Define the data
composite_data = {
'd':np.array(d),
's':np.array(s),
'n':n,
'N':N,
'beta':beta,
'gamma':gamma,
'm':transition_prior[0],
'q':transition_prior[1]
}
# Starting point for the chains
initialization = []
for k in range(0,n):
initialization.append({'y':d[k]})
initialization.append({'y':np.mean(np.array(d), axis=0)})
# Run the sampler
fit = model.sampling(data=composite_data, iter=20000, chains=n+1, init=initialization, warmup=1000)
# Extract the chain
chain = fit.extract()['y']
return chain