In [1]:
#simulation to perform many runs of the healthy vs. unhealthy dynamics
#this version will start with an initial condition in the diseased state space with an
#initial covariance that is nonzero. 
import numpy as np
import matplotlib.pyplot as plt
import math
import sys
from threechoice_dynamics import *

#tf.set_random_seed(101)
pi = math.pi
#np.random.seed(101)

#define the gradients and parameters of the simulation
xdim = 2 #state dimension
udim = 2 #control dimension
T = 10000 #number of steps

#define the noise for the system
dt = 1.0e-4
gamma = 1.0e-4
sigsstate = (1./dt)*(1e-9)#fix these

sigsobs = 1.0e-6

Q = sigsstate*np.eye(xdim)
R = sigsobs*np.eye(xdim)

#the non-tensorflow anonymous functions, for generalizations
true_nontf = lambda x,c: grad_threechoice(x[0],x[1],dt,c)
target_nontf = lambda x: grad_threechoice_healthy(x[0],x[1],dt)

In [8]:
ns = 500 #number of samples
#------- the main simulation loop. I might make this a function if i use it a lot

#make these numpy version
statenoise = np.random.normal(0,sigsstate**0.5,[xdim,T,ns])
obsnoise = np.random.normal(0,sigsobs**0.5,[xdim,T,ns])
G = dt**(0.5)*np.eye(xdim) #system noise matrix, for covariance prediction

xvec = np.zeros((xdim,T,ns))
yvec = np.zeros((xdim,T,ns))
loss = np.zeros((T,ns))
lag = 0
ci = [0.,0.]

for m in range(ns):
    x_init = np.random.uniform(0.,0.5,(2,))

    x_k = x_init
    xvec[:,0,m] = x_init

    #print(m)

    #go ahead and propagate lag-steps ahead before starting state estimation and such
    for k in range(1,T):
        #update actual dynamics
        grad_cont = true_nontf(xvec[:,k-1,m],ci)
        xvec[:,k,m] = xvec[:,k-1,m] + grad_cont + statenoise[:,k,m]
        yvec[:,k,m] = xvec[:,k,m] + obsnoise[:,k,m]
        
        loss[k,m] = np.linalg.norm(
            true_nontf(xvec[:,k,m],ci)-
            target_nontf(xvec[:,k,m]))


0
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499

In [9]:
#------------ save
import pickle
fname = 'threechoice_initruns_nocont_T10000.p'
index = ['xvec','yvec','loss']
alldata = [index,xvec,yvec,loss]
pickle.dump( alldata, open( fname, "wb" ) )

In [15]:
#set up and run EKF in tensorflow
import tensorflow as tf
from tf_funs import *

X_est = tf.placeholder(shape=xdim,dtype=tf.float32,name='X_est') #the state estimate
PI_est = tf.placeholder(shape = (xdim,xdim),dtype=tf.float32, name = 'PI_est') #estimated covariance
Y_tp1 = tf.placeholder(shape= xdim,dtype=tf.float32, name = 'Y_tp1') #the most recent observation
#now run EKF for last 100 steps and get the state estimates for the final 
Q_tf = tf.constant(Q,dtype=tf.float32, name = 'Q') #state noise covariance
R_tf = tf.constant(R,dtype=tf.float32, name = 'R') #observation noise covariance  
Control = tf.placeholder(shape = udim, dtype=tf.float32, name='Control')

#graphs for updating state and observation
true_model_est = grad_threechoice_tf(X_est[0],X_est[1],dt,Control)
true_model_est_null = grad_threechoice_tf(X_est[0],X_est[1],dt,[0.,0.]) #state est. gradient null control
target_model_est = grad_threechoice_healthy_tf(X_est[0],X_est[1],dt) #state est. target dynamics
#the non-tensorflow anonymous functions, for generalizations
true_nontf = lambda x,c: grad_threechoice(x[0],x[1],dt,c)
target_nontf = lambda x: grad_threechoice_healthy(x[0],x[1],dt)   

X_plus,PI_plus = EKF(X_est,Y_tp1,PI_est,true_model_est,true_model_est_null,Q_tf,R_tf,xdim,dt)

In [19]:
session_conf = tf.ConfigProto(
      intra_op_parallelism_threads=4,
      inter_op_parallelism_threads=4)
sess = tf.Session(config=session_conf)

init = tf.global_variables_initializer()
sess.run(init)

t_start = T-100

x_estvec = np.zeros((xdim,T-t_start,ns))
PI_estvec = np.zeros((xdim,xdim,T-t_start,ns))
xvec_init = xvec[:,t_start:T,:] #values of x that we are running EKF on

x_inits = xvec[:,t_start,:]
PI_init = [[1.0e-4,0.],[0.,1.0e-4]] #initial covariance
x_estvec[:,0,:] = x_inits
for k in range(ns):
    PI_estvec[:,:,0,k] = PI_init
print('starting estimation')

for m in range(ns):
    for k in range(1,T-t_start):
        test = sess.run([X_plus,PI_plus],
                            {X_est:x_estvec[:,k-1,m], PI_est:PI_estvec[:,:,k-1,m],
                             Control:ci, Y_tp1:yvec[:,t_start + k,m]})
        x_estvec[:,k,m] = test[0]
        PI_estvec[:,:,k,m] = test[1]
    #print(m)


starting estimation

In [23]:
import pickle
xvec_init = xvec[:,t_start:T,:] #values of x that we are running EKF on
fname = 'threechoice_initruns_nocont_ekf.p'
index = ['x_estvec','PI_estvec','xvec_init']
alldata = [index,x_estvec,PI_estvec,xvec_init]
pickle.dump( alldata, open( fname, "wb" ) )

In [26]:
#run the whole last 1000 steps to get state esitmate and loss
loss_tf = loss_full(X_est,PI_est,true_model_est,target_model_est)
session_conf = tf.ConfigProto(
      intra_op_parallelism_threads=4,
      inter_op_parallelism_threads=4)
sess = tf.Session(config=session_conf)

init = tf.global_variables_initializer()
sess.run(init)

t_start = T-1000

x_estvec = np.zeros((xdim,T-t_start,ns))
PI_estvec = np.zeros((xdim,xdim,T-t_start,ns))
xvec_init = xvec[:,t_start:T,:] #values of x that we are running EKF on
loss = np.zeros((4,T-t_start,ns))

x_inits = xvec[:,t_start,:]
PI_init = [[1.0e-4,0.],[0.,1.0e-4]] #initial covariance
x_estvec[:,0,:] = x_inits
for k in range(ns):
    PI_estvec[:,:,0,k] = PI_init
print('starting estimation')


for m in range(ns):
    print(m)
    for k in range(1,T-t_start):
        test = sess.run([X_plus,PI_plus],
                            {X_est:x_estvec[:,k-1,m], PI_est:PI_estvec[:,:,k-1,m],
                             Control:ci, Y_tp1:yvec[:,t_start + k,m]})
        x_estvec[:,k,m] = test[0]
        PI_estvec[:,:,k,m] = test[1]
        
        ltest = sess.run(loss_tf,{X_est:x_estvec[:,k-1,m],
                                               PI_est:PI_estvec[:,:,k-1,m],
                                               Control:ci
                                              })
        loss[:,k-lag,m] = ltest
    #print(m)


starting estimation
0
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499

In [27]:
#save 
xvec_init = xvec[:,t_start:T,:] #values of x that we are running EKF on
fname = 'threechoice_initruns_nocont_ekf_T1000.p'
index = ['x_estvec','PI_estvec','xvec_init','loss']
alldata = [index,x_estvec,PI_estvec,xvec_init,loss]
pickle.dump( alldata, open( fname, "wb" ) )