-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnscore.py
358 lines (294 loc) · 12.7 KB
/
Enscore.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import torch
import numpy as np
import matplotlib.pyplot as plt
from functools import partial
import time
import sys
import os
class EnSF:
def __init__(self, n_dim, ensemble_size,eps_alpha, device,obs_sigma,euler_steps,scalefact,init_std_x_state, ISarctan=False ):
####################################################################
# EnSF setup
# define the diffusion process eps_alpha
# ensemble size ensemble_size = 250
self.n_dim = n_dim
self.ensemble_size = ensemble_size
self.eps_alpha = eps_alpha
self.device = device
self.obs_sigma = obs_sigma
self.ISarctan = ISarctan
self.euler_steps = euler_steps
self.scalefact = scalefact
self.init_std_x_state = init_std_x_state
# computation setting
#torch.set_default_dtype(torch.float16) # half precision
#device = 'cuda' 'cpu'
# compact version
def cond_alpha(self,t):
# conditional information
# alpha_t(0) = 1
# alpha_t(1) = esp_alpha \approx 0
return 1 - (1-self.eps_alpha)*t
def cond_sigma_sq(self,t):
# conditional sigma^2
# sigma2_t(0) = 0
# sigma2_t(1) = 1
# sigma(t) = t
return t
# drift function of forward SDE
def f(self,t):
# f=d_(log_alpha)/dt
alpha_t = self.cond_alpha(t)
f_t = -(1-self.eps_alpha) / alpha_t
return f_t
def g_sq(self,t):
# g = d(sigma_t^2)/dt -2f sigma_t^2
d_sigma_sq_dt = 1
g2 = d_sigma_sq_dt - 2*self.f(t)*self.cond_sigma_sq(t)
return g2
def g(self,t):
return np.sqrt(self.g_sq(t))
# generate sample with reverse SDE
def reverse_SDE(self, obs,x0, time_steps,obs_sigma, save_path=False):
# x_T: sample from standard Gaussian
# x_0: target distribution to sample from
ensemble_size = self.ensemble_size
n_dim = self.n_dim
device = self.device
#drift_fun=f, diffuse_fun=g, alpha_fun=cond_alpha, sigma2_fun=cond_sigma_sq, score_likelihood=None,
# reverse SDE sampling process
# N1 = x_T.shape[0]
# N2 = x0.shape[0]
# d = x_T.shape[1]
# Generate the time mesh
dt = 1.0/time_steps
# Initialization
xt = torch.randn(ensemble_size,n_dim, device=device)
t = 1.0
# define storage
if save_path:
path_all = [xt]
t_vec = [t]
mart_point = int(0.20 * time_steps) ###0.20
temp_state = torch.zeros(mart_point,n_dim)
# forward Euler sampling
for i in range(time_steps):
temp_mean_old = temp_state.mean(dim = 0)
# prior score evaluation
alpha_t = self.cond_alpha(t)#alpha_fun(t)
sigma2_t = self.cond_sigma_sq(t)#sigma2_fun(t)
# Evaluate the diffusion term
diffuse = self.g(t) #diffuse_fun(t)
# Update
xt += - dt * (self.f(t)*xt + diffuse**2 * ( (xt- alpha_t*x0)/sigma2_t) - diffuse**2 * self.score_likelihood(xt, t,obs,obs_sigma) ) \
+ np.sqrt(dt)*diffuse*torch.randn_like(xt)
# Store the state in the path
if save_path:
path_all.append(xt)
t_vec.append(t)
#save moving state
temp_state[i % mart_point,:] = xt.mean(dim = 0)
if (abs(temp_state.mean(dim = 0) - temp_mean_old) < 0.005).all() and i >mart_point:
break
else:
pass
if i > 500:
break
# update time
t = t - dt
if save_path:
return path_all, t_vec
else:
return xt
# damping function(tau(0) = 1; tau(1) = 0;)
def g_tau(self, t):
return 1-t
# define likelihood score
def score_likelihood(self, xt, t,obs,obs_sigma):
# obs: (d)
# xt: (ensemble, d)
if self.ISarctan:
score_x = -(torch.atan(self.scalefact*xt) - obs)/(obs_sigma)**2 * (self.scalefact*1./(1. + self.scalefact**2 * xt**2))
else:
score_x = -( self.scalefact*xt - obs)/obs_sigma**2 * self.scalefact #self.scalefact*
#score_x = -( xt - obs)/obs_sigma**2 #hxens only
tau = self.g_tau(t)
return tau*score_x
def state_update_hxens(self,x_input,state_target_input, obs_input):
# filtering settings
ensemble_size = self.ensemble_size
# observation sigma
# forward Euler step
euler_steps = self.euler_steps
#####################################################################################################################
# filtering ensemble
x_state = torch.tensor(x_input,device='cuda')
state_target = torch.tensor(state_target_input,device='cuda')
# get observation
obs = torch.tensor(obs_input,device='cuda')
temp_obs_sigma = self.obs_sigma * 0.1
'''
# get state memory size
mem_state = x_state.element_size() * x_state.nelement()/1e+6
mem_ensemble = mem_state * ensemble_size
print(f'single state memory: {mem_state:.2f} MB')
print(f'state ensemble memory: {mem_ensemble:.2f} MB')
'''
torch.cuda.empty_cache()
t1 = time.time()
# generate posterior sample
x_state = self.reverse_SDE(obs=obs,x0=x_state,time_steps=euler_steps,obs_sigma = temp_obs_sigma) #self.obs_sigma
# get state estimates
x_est = torch.mean(x_state,dim=0)
# get rmse
rmse_temp = torch.sqrt(torch.mean((x_est - state_target)**2)).item()
# get time
if x_state.device.type == 'cuda':
torch.cuda.current_stream().synchronize()
t2 = time.time()
print(f'\t RMSE = {rmse_temp:.4f}')
#print(f'\t time = {t2-t1:.4f} ')
# Diverge Warning
if rmse_temp > 1000:
print('diverge!')
return x_state#, x_est, rmse_temp
def state_update(self,x_input,state_target_input, obs_input):
# filtering settings
ensemble_size = self.ensemble_size
# observation sigma
# forward Euler step
euler_steps = self.euler_steps
#####################################################################################################################
# filtering ensemble
x_state = torch.tensor(x_input,device='cuda')
state_target = torch.tensor(state_target_input,device='cuda')
# get observation
obs = torch.tensor(obs_input,device='cuda')
temp_obs_sigma = self.obs_sigma
'''
# get state memory size
mem_state = x_state.element_size() * x_state.nelement()/1e+6
mem_ensemble = mem_state * ensemble_size
print(f'single state memory: {mem_state:.2f} MB')
print(f'state ensemble memory: {mem_ensemble:.2f} MB')
'''
torch.cuda.empty_cache()
t1 = time.time()
# generate posterior sample
x_state = self.reverse_SDE(obs=obs,x0=x_state,time_steps=euler_steps,obs_sigma = temp_obs_sigma)
# get state estimates
x_est = torch.mean(x_state,dim=0)
# get rmse
rmse_temp = torch.sqrt(torch.mean((x_est - state_target)**2)).item()
# get time
if x_state.device.type == 'cuda':
torch.cuda.current_stream().synchronize()
t2 = time.time()
print(f'\t RMSE = {rmse_temp:.4f}')
#print(f'\t time = {t2-t1:.4f} ')
# Diverge Warning
#if rmse_temp > 1000:
# print('diverge!')
return x_state#, x_est, rmse_temp
def state_update_normalized(self,x_input,state_target_input, obs_input):
torch.set_default_dtype(torch.float16)
# filtering settings
ensemble_size = self.ensemble_size
# observation sigma
# forward Euler step
euler_steps = self.euler_steps
#####################################################################################################################
# filtering ensemble
x_state = torch.tensor(x_input,device='cuda')
state_target = torch.tensor(state_target_input,device='cuda')
init_std_x_state = torch.tensor(self.init_std_x_state,device='cuda')
# get observation
obs = torch.tensor(obs_input,device='cuda')
#normalize
std_x_state = x_state.std(dim=0)
mean_x_state = x_state.mean(dim=0)
x_state = (x_state- mean_x_state) / std_x_state
obs = ((obs / self.scalefact - mean_x_state) / std_x_state) * self.scalefact
temp_obs_sigma = self.obs_sigma / self.scalefact / std_x_state * self.scalefact
'''
# get state memory size
mem_state = x_state.element_size() * x_state.nelement()/1e+6
mem_ensemble = mem_state * ensemble_size
print(f'single state memory: {mem_state:.2f} MB')
print(f'state ensemble memory: {mem_ensemble:.2f} MB')
'''
torch.cuda.empty_cache()
t1 = time.time()
# generate posterior sample
x_state = self.reverse_SDE(obs=obs,x0=x_state,time_steps=euler_steps,obs_sigma = temp_obs_sigma)
#print(x_state.mean(dim=0))
x_state = x_state * std_x_state + mean_x_state
# get state estimates
x_est = torch.mean(x_state,dim=0)
# get rmse
rmse_temp = torch.sqrt(torch.mean((x_est - state_target)**2)).item()
x_state_temp = (x_state - x_state.mean(dim=0)) * (std_x_state/x_state.std(dim=0) ) + x_state.mean(dim=0)
if (x_state_temp.std() > (1.5 * init_std_x_state)).any():
x_state = (x_state - x_state.mean(dim=0)) * (init_std_x_state/x_state.std(dim=0) ) + x_state.mean(dim=0)
else:
x_state = x_state_temp
''''''
# get time
if x_state.device.type == 'cuda':
torch.cuda.current_stream().synchronize()
t2 = time.time()
#print(f'\t RMSE = {rmse_temp:.4f}')
#print(f'\t time = {t2-t1:.4f} ')
# Diverge Warning
#if rmse_temp > 1000:
# print('diverge!')
return x_state#, rmse_temp
def state_update_arctan(self,x_input,state_target_input, obs_input):
#torch.set_default_dtype(torch.float32)
# forward Euler step
euler_steps = self.euler_steps
#####################################################################################################################
# filtering ensemble
x_state = torch.tensor(x_input,device='cuda')
state_target = torch.tensor(state_target_input,device='cuda')
init_std_x_state = torch.tensor(self.init_std_x_state,device='cuda')
# get observation
obs = torch.tensor(obs_input,device='cuda')
#normalize
std_x_state = x_state.std(dim=0)
mean_x_state = x_state.mean(dim=0)
x_state = (x_state- mean_x_state) / std_x_state
obs = torch.atan((torch.tan(obs) / self.scalefact - mean_x_state)* self.scalefact/ std_x_state )
temp_obs_sigma = self.obs_sigma * self.scalefact *5
'''
# get state memory size
mem_state = x_state.element_size() * x_state.nelement()/1e+6
mem_ensemble = mem_state * ensemble_size
print(f'single state memory: {mem_state:.2f} MB')
print(f'state ensemble memory: {mem_ensemble:.2f} MB')
'''
torch.cuda.empty_cache()
t1 = time.time()
# generate posterior sample
x_state = self.reverse_SDE(obs=obs,x0=x_state,time_steps=euler_steps,obs_sigma = temp_obs_sigma)
x_state = x_state * std_x_state + mean_x_state
x_out = x_state
# get state estimates
x_est = torch.mean(x_state,dim=0)
x_state_temp = (x_state - x_state.mean(dim=0)) * (std_x_state/x_state.std(dim=0) ) + x_state.mean(dim=0)
if (x_state_temp.std() > (1.5 * init_std_x_state)).any():
x_state = (x_state - x_state.mean(dim=0)) * (init_std_x_state/x_state.std(dim=0) ) + x_state.mean(dim=0)
else:
x_state = x_state_temp
# get rmse
rmse_temp = torch.sqrt(torch.mean((x_est - state_target)**2)).item()
# get time
if x_state.device.type == 'cuda':
torch.cuda.current_stream().synchronize()
t2 = time.time()
#print(f'\t RMSE = {rmse_temp:.4f}')
#print(f'\t time = {t2-t1:.4f} ')
# Diverge Warning
#if rmse_temp > 1000:
# print('diverge!')
return x_state#, rmse_temp , x_state