-
Notifications
You must be signed in to change notification settings - Fork 1
/
NeurIPS2020.py
2052 lines (1865 loc) · 101 KB
/
NeurIPS2020.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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""------------------------------- README ------------------------------- """
"""
Subject: Codes used to generate results presented in paper "Estimating Fluctuations in Neural Representations of
Uncertain Environments" which is submitted to NeurIPS 2020.
Author: Anonymous
How to use:
- Dependencies: dependencies through lines 17-26. All of the libraries are very well-known and open source.
- In order to generate the figures in the paper, first everything up to line 1983 must be executed. After that,
for each of the following figures execute the corresponding lines:
Paper, Figure 2A Lines 1985-1987
Paper, Figure 2B Lines 1989-1991
Paper, Figure 2C Lines 1993-1997
Paper, Figure 3 Lines 1999-2002
Paper, Figure 4A Lines 2004-2010
Paper, Figure 4B Lines 2012-2016
Paper, Figure 4C Lines 2018-2029
Paper, Figure 4D Lines 2031-2035
Supplementary Material, Figure 1 Lines 2042-2053
Note 1: Data used for this analysis is not shared, as it is not permitted by people who collected that.
Note 2: A version of this code that works for a simulated data is going to be developed, and it will be shared along
with the simulated data publicly later.
"""
import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from collections import Counter
import statsmodels.api as sm
from scipy.ndimage import gaussian_filter
from scipy.stats import norm
import scipy
from sklearn.cluster import KMeans
if 'Apple_PubSub_Socket_Render' in os.environ:
# on OSX
matplotlib.use('TkAgg')
elif 'JOB_ID' in os.environ:
# running in an SCC batch job, no interactive graphics
matplotlib.use('Agg')
else:
matplotlib.use('TkAgg')
print('Using TkAgg.')
def find_nearest(arr1, arr2):
# For each element x of arr2, find the index of the closest element of arr1 to that.
ans = []
for x in arr2:
y = np.argmin(np.abs(arr1 - x))
ans.append(y)
ans = np.array(ans)
return ans
def compute_hist_cov (Y, hist_wind):
# Compute the covaraite matrix that consists of the history of the response vector (each column one lag)
# This function is used for fitting models with history-dependent component
# Y: the response vector
# hist_wind: size of the history window
Y_hist = np.zeros(shape=[Y.shape[0] - hist_wind, hist_wind])
for h in range(hist_wind):
Y_hist[:, h] = Y[h: h + Y.shape[0] - hist_wind]
return Y_hist
def morph_trials(morph_lvl):
# Return trials for the given morph level
# morph_lvl: morph level
ind = np.where(VRData[:, 1] == morph_lvl)[0]
lst = VRData[ind, 20].astype(int)
cnt = Counter(lst)
out = list(set([x for x in lst if cnt[x] > 4])) # only keep complete trials, i.e. with at least 4 data points
out.sort()
out = np.array(out)
return out
def compute_activity_rate(exp_id, morphs, morph_lvl, breaks):
# For each cell, for each trial with given morph level, return the activity rate as a function of the position
# morph_lvl: the fixed morph level
# morphs: all trials with the fixed morph level
# breaks: number of bins used to discretize the 1-dimensional position
# exp_id: experiment id
step = (max_pos - min_pos) / breaks
activity_rates = np.zeros(shape=[ncells, breaks, ntrials])
activity_count = np.zeros(shape=[ncells, breaks, ntrials])
last_moment_activity_rates = np.zeros(shape=[ncells])
last_moment_activity_count = np.zeros(shape=[ncells])
for tr in morphs:
print(tr)
for i in range(breaks):
ind = np.where((VRData[:, 3] >= min_pos + i*step) & (VRData[:, 3] < min_pos + (i+1)*step) & (
VRData[:, 20] == tr))[0]
# if there is no data point for a cell and a given bin, use the activity rate for the previous bin
if len(ind) == 0:
if i == 0:
activity_rates[:, i, tr] = np.zeros(shape=[ncells])
activity_count[:, i, tr] = np.zeros(shape=[ncells])
else:
activity_rates[:, i, tr] = last_moment_activity_rates
activity_count[:, i, tr] = last_moment_activity_count
else:
activity_rates[:, i, tr] = np.mean(F[:, ind], axis=1)
activity_count[:, i, tr] = len(ind)
last_moment_activity_rates = activity_rates[:, i, tr]
last_moment_activity_count = activity_count[:, i, tr]
np.save(os.getcwd() + '/Data/activity_rates_exp_' + str(exp_id) + '_morph_' + str(morph_lvl) + '.npy',
activity_rates)
np.save(os.getcwd() + '/Data/activity_count_exp_' + str(exp_id) + '_morph_' + str(morph_lvl) + '.npy',
activity_count)
def compute_spline_mat(X):
# Compute the cubic spline matrix for a 1-dimensional position vector X with regularly distributed knots.
# X: 1-dimensional input
min_val = np.min(X)
max_val = np.max(X)
knots = np.array([min_val - 10] + list(np.arange(min_val, max_val+50, 50)) + [max_val + 10])
par = 0.5 # tension parameter
out = np.zeros(shape=[X.shape[0], knots.shape[0]])
for i in range(X.shape[0]):
x = X[i]
nearest_knot_ind = np.argmax(knots[knots <= x])
nearest_knot = knots[nearest_knot_ind]
next1 = knots[nearest_knot_ind+1]
next2 = knots[nearest_knot_ind+2]
u = (x - nearest_knot)/(next1 - nearest_knot)
l = (next2 - next1)/(next1 - nearest_knot)
A = np.array([np.power(u, 3), np.power(u, 2), u, 1])
B = np.array([[-par, 2-par/l, par-2, par/l], [2*par, par/l-3, 3-2*par, -par/l], [-par, 0, par, 0],
[0, 1, 0, 0]])
r = A.dot(B)
r = np.reshape(r, newshape=(1, r.shape[0]))
out[i, nearest_knot_ind-1: nearest_knot_ind+3] = r
return out
def compute_spline_Normal_loglike(exp_id, morph_lvl, morphs):
# For each cell, for each trial with a fixed morph level, fit a spline-Normal model and return the computed
# log-likelihoods.
# model: Y ~ Normal(mean = beta_0 + Sum beta_i g_i(x)) where g_i(x)'s are spline basis evaluated at position x
# morph_lvl: fixed morph level
# morphs: trials with given morph level
# exp_id: experiment id
breaks = 400
ind = np.where(np.isin(VRData[:, 20], morphs))[0]
X = VRData[ind, 3]
Y = F[:, ind]
step = (max_pos - min_pos) / breaks
X_disc = []
Y_disc = []
for i in range(breaks):
ind0 = np.where((X >= min_pos + i * step) & (X < min_pos + (i + 1) * step))[0]
if i == 0:
X_disc.append(min_pos)
elif i == breaks - 1:
X_disc.append(max_pos)
else:
X_disc.append(min_pos + (i + 1 / 2) * step)
if ind0.shape[0] == 0:
Y_disc.append(Y_disc[-1])
if ind0.shape[0] > 0:
Y_disc.append(np.mean(Y[:, ind0], axis=1))
X_disc = np.array(X_disc)
Y_disc = np.array(Y_disc)
spline_mat = compute_spline_mat(X_disc)
loglike = []
for cell_id in range(ncells):
print(cell_id)
gauss_ident = sm.GLM(Y_disc[:, cell_id], spline_mat, family=sm.families.Gaussian(sm.families.links.identity()))
gauss_ident_results = gauss_ident.fit()
b = np.array(gauss_ident_results.params)
est = spline_mat.dot(b)
loglike.append(gauss_ident_results.llf)
loglike = np.array(loglike)
np.save(os.getcwd() + '/Data/spline_Normal_loglike_exp_' + str(exp_id) + '_morph_' + str(morph_lvl) + '.npy',
loglike)
def compute_spline_Normal_dist(exp_id):
# For each cell, fit two spline_Normal models for two original environments and return the L2 distance between
# estimated activities obtained from these models.
# exp_id: experiment id
# For morph = 0
breaks = 400
ind = np.where(np.isin(VRData[:, 20], morph_0_trials))[0]
X = VRData[ind, 3]
Y = F[:, ind]
step = (max_pos - min_pos) / breaks
X_disc = []
Y0_disc = []
for i in range(breaks):
ind0 = np.where((X >= min_pos + i * step) & (X < min_pos + (i + 1) * step))[0]
if i == 0:
X_disc.append(min_pos)
elif i == breaks - 1:
X_disc.append(max_pos)
else:
X_disc.append(min_pos + (i + 1 / 2) * step)
if ind0.shape[0] == 0:
Y0_disc.append(Y0_disc[-1])
if ind0.shape[0] > 0:
Y0_disc.append(np.mean(Y[:, ind0], axis=1))
X_disc = np.array(X_disc)
Y0_disc = np.array(Y0_disc)
spline_mat0 = compute_spline_mat(X_disc)
# For morph = 1
breaks = 400
ind = np.where(np.isin(VRData[:, 20], morph_1_trials))[0]
X = VRData[ind, 3]
Y = F[:, ind]
step = (max_pos - min_pos) / breaks
X_disc = []
Y1_disc = []
for i in range(breaks):
ind0 = np.where((X >= min_pos + i * step) & (X < min_pos + (i + 1) * step))[0]
if i == 0:
X_disc.append(min_pos)
elif i == breaks - 1:
X_disc.append(max_pos)
else:
X_disc.append(min_pos + (i + 1 / 2) * step)
if ind0.shape[0] == 0:
Y1_disc.append(Y1_disc[-1])
if ind0.shape[0] > 0:
Y1_disc.append(np.mean(Y[:, ind0], axis=1))
X_disc = np.array(X_disc)
Y1_disc = np.array(Y1_disc)
spline_mat1 = compute_spline_mat(X_disc)
# Fitting the models nd computing the L2 distance
dis = []
for cell_id in range(ncells):
print(cell_id)
gauss_ident = sm.GLM(Y0_disc[:, cell_id], spline_mat0, family=sm.families.Gaussian(sm.families.links.identity()))
gauss_ident_results = gauss_ident.fit()
b = np.array(gauss_ident_results.params)
est0 = spline_mat0.dot(b)
gauss_ident = sm.GLM(Y1_disc[:, cell_id], spline_mat1, family=sm.families.Gaussian(sm.families.links.identity()))
gauss_ident_results = gauss_ident.fit()
b = np.array(gauss_ident_results.params)
est1 = spline_mat1.dot(b)
dis.append(np.mean((est0 - est1)**2))
dis = np.array(dis)
np.save(os.getcwd() + '/Data/spline_Normal_dist_exp_' + str(exp_id) + '.npy', dis)
def compute_active_trials(exp_id, morphs, morph_lvl):
# For each cell_id, for each trial with given morph level, use K-means to divide trials into 2 groups using the
# average activity or place field location. The resulting groups are called "active" and "inactive". However,
# the inactive group doesn't necessary mean that the cell has no significant activity.
# exp_id: experiment id
# morph_lvl: fixed morph level
# morphs: trials with the fixed morph level
active_trials = np.zeros(shape=[ncells, len(morphs)])
activity_trials = np.zeros(shape=[ncells, len(morphs)])
thrsh = 12000
for cell_id in range(ncells):
print('cell_id = {}'.format(cell_id))
top_num = 5
top_act = []
for tr_id in morphs:
ind = np.where(VRData[:, 20] == tr_id)[0]
s = np.flip(np.sort(F[cell_id, ind]))
top_act.append(np.mean(s[:top_num]))
top_act = np.array(top_act)
activity_trials[cell_id, :] = top_act
top_act_org = np.copy(top_act)
if np.min(top_act) < thrsh:
top_act[top_act > thrsh] = thrsh
top_act = np.reshape(top_act, newshape=[top_act.shape[0], 1])
dots = np.append(np.zeros(shape=top_act.shape), top_act, axis=1)
kmeans = KMeans(n_clusters=2, random_state=0).fit(dots)
x = np.argmax(dots[:, 1])
if kmeans.labels_[x] == 0:
kmeans.labels_ = 1 - kmeans.labels_
active_trials[cell_id, :] = kmeans.labels_
np.save(os.getcwd() + '/Data/active_trials_morph_' + str(morph_lvl) + '_exp_' + str(exp_id) + '.npy',
active_trials)
np.save(os.getcwd() + '/Data/top_activity_trials_morph_' + str(morph_lvl) + '_exp_' + str(exp_id) + '.npy',
activity_trials)
def decode_morphs(exp_id, p, mode, visualize, visualize2, history):
# For each cell fit 8 spline-Gamma models for morph0/morph1 active/inactive with_history/without_history. In
# addition, fit 2 Gamma models for all active/inactive trials to use later for hypothesis tests on existence of
# multiple spatial maps. The without_history models are used only for debugging. For each trial compute its
# log-likelihood and likelihood based on if its active/inactive indicator for both morph0 and morph1 models.
# Eventually, use the filter and smoother algorithms to compute decoded probability. This function Returns all 8
# fitted models along with decoding results.
# exp_id: experiment id
# p: probability of jumping form one state to the other one in first-order Markov chain
# mode: shows if we are using shorted version of data (mode = short) or all data (mode = all)
# visualize: determines if the function must show the decoding results for each cell and each trial or not.
# visualize2: determines if the function must show the decoding results as a heatmap (for all trials and each
# individual cell)
# history: determines if we want to visualize models with history component or not.
# each row = [X_tr, Y_tr, p_morphs_filt, p_morph_smooth, p_morph_likelihood]
p_morph = np.empty(shape=[ncells, ntrials, 6], dtype=object)
# used later for performing hypothesis tests for existence of multiple spatial maps
goodness_of_fit = np.empty(shape=[ncells, ntrials, 2], dtype=object)
gamma_fit_0_act = np.empty(shape=[ncells, 8], dtype=object) # morph0, active trials, with history
gamma_fit_0_inact = np.empty(shape=[ncells, 8], dtype=object) # morph0, inactive trials, with history
gamma_fit_1_act = np.empty(shape=[ncells, 8], dtype=object) # morph1, active trials, with history
gamma_fit_1_inact = np.empty(shape=[ncells, 8], dtype=object) # morph1, inactive trials, with history
gamma_fit_0_act_nohist = np.empty(shape=[ncells, 8], dtype=object) # morph0, active trials, without history
gamma_fit_0_inact_nohist = np.empty(shape=[ncells, 8], dtype=object) # morph0, inactive trials, without history
gamma_fit_1_act_nohist = np.empty(shape=[ncells, 8], dtype=object) # morph1, active trials, without history
gamma_fit_1_inact_nohist = np.empty(shape=[ncells, 8], dtype=object) # morph1, inactive trials, without history
gamma_fit_0_all = np.empty(shape=[ncells, 8], dtype=object) # morph0, all trials, with history
gamma_fit_1_all = np.empty(shape=[ncells, 8], dtype=object) # morph1, all trials, with history
trial_ids = range(ntrials)
cnt = 1
for cell_id in cells_under_study:
print('processing the {}-th cell'.format(cnt))
cnt += 1
ind = np.where(active_trials_0[cell_id, :] == 1)[0]
morph0_act = morph_0_trials[ind]
ind = np.where(active_trials_0[cell_id, :] == 0)[0]
morph0_inact = morph_0_trials[ind]
ind = np.where(active_trials_1[cell_id, :] == 1)[0]
morph1_act = morph_1_trials[ind]
ind = np.where(active_trials_1[cell_id, :] == 0)[0]
morph1_inact = morph_1_trials[ind]
# For morph 0 active trials
X = np.array(1)
Y = np.array(1)
Y_hist = np.array(1)
first_one = True
for tr_id in morph0_act:
ind = np.where(VRData[:, 20] == tr_id)[0]
X_tr = VRData[ind, :]
X_tr = X_tr[:, 3]
Y_tr = F[cell_id, ind]
Y_hist_tr = compute_hist_cov(Y_tr, hist_wind)
X_tr = X_tr[hist_wind:]
Y_tr = Y_tr[hist_wind:]
if first_one:
X = X_tr.copy()
Y = Y_tr.copy()
Y_hist = Y_hist_tr
first_one = False
else:
X = np.concatenate((X, X_tr), axis=0)
Y = np.concatenate((Y, Y_tr), axis=0)
Y_hist = np.concatenate((Y_hist, Y_hist_tr), axis=0)
X0_act = X.copy()
Y0_act = Y.copy()
Y0hist_act= Y_hist.copy()
# Fititng model with no history for visualization only
spline_mat0_act = compute_spline_mat(X0_act)
gamma_0_act = sm.GLM(Y0_act, spline_mat0_act, family=sm.families.Gamma(sm.families.links.identity))
gamma_res_0_act = gamma_0_act.fit()
mu_0_act_nohist = gamma_res_0_act.mu
v_0_act_nohist = 1 / gamma_res_0_act.scale
params_0_act_nohist = gamma_res_0_act.params
# Fitting model with history
cov0_act = np.concatenate((spline_mat0_act, Y0hist_act), axis=1)
gamma_0_act = sm.GLM(Y0_act, cov0_act, family=sm.families.Gamma(sm.families.links.identity))
gamma_res_0_act = gamma_0_act.fit()
mu_0_act = gamma_res_0_act.mu
v_0_act = 1 / gamma_res_0_act.scale
params_0_act = gamma_res_0_act.params
# For morph 0 inactive trials
X = np.array(1)
Y = np.array(1)
Y_hist = np.array(1)
first_one = True
for tr_id in morph0_inact:
ind = np.where(VRData[:, 20] == tr_id)[0]
X_tr = VRData[ind, :]
X_tr = X_tr[:, 3]
Y_tr = F[cell_id, ind]
Y_hist_tr = compute_hist_cov(Y_tr, hist_wind)
X_tr = X_tr[hist_wind:]
Y_tr = Y_tr[hist_wind:]
if first_one:
X = X_tr.copy()
Y = Y_tr.copy()
Y_hist = Y_hist_tr
first_one = False
else:
X = np.concatenate((X, X_tr), axis=0)
Y = np.concatenate((Y, Y_tr), axis=0)
Y_hist = np.concatenate((Y_hist, Y_hist_tr), axis=0)
X0_inact = X.copy()
Y0_inact = Y.copy()
Y0hist_inact = Y_hist.copy()
# Fititng model with no history for visualization only
spline_mat0_inact = compute_spline_mat(X0_inact)
gamma_0_inact = sm.GLM(Y0_inact, spline_mat0_inact, family=sm.families.Gamma(sm.families.links.identity))
gamma_res_0_inact = gamma_0_inact.fit()
mu_0_inact_nohist = gamma_res_0_inact.mu
v_0_inact_nohist = 1 / gamma_res_0_inact.scale
params_0_inact_nohist = gamma_res_0_inact.params
# Fitting model with history
cov0_inact = np.concatenate((spline_mat0_inact, Y0hist_inact), axis=1)
gamma_0_inact = sm.GLM(Y0_inact, cov0_inact, family=sm.families.Gamma(sm.families.links.identity))
gamma_res_0_inact = gamma_0_inact.fit()
mu_0_inact = gamma_res_0_inact.mu
v_0_inact = 1 / gamma_res_0_inact.scale
params_0_inact = gamma_res_0_inact.params
# For morph 1 active trials
X = np.array(1)
Y = np.array(1)
Y_hist = np.array(1)
first_one = True
for tr_id in morph1_act:
ind = np.where(VRData[:, 20] == tr_id)[0]
X_tr = VRData[ind, :]
X_tr = X_tr[:, 3]
Y_tr = F[cell_id, ind]
Y_hist_tr = compute_hist_cov(Y_tr, hist_wind)
X_tr = X_tr[hist_wind:]
Y_tr = Y_tr[hist_wind:]
if first_one:
X = X_tr.copy()
Y = Y_tr.copy()
Y_hist = Y_hist_tr
first_one = False
else:
X = np.concatenate((X, X_tr), axis=0)
Y = np.concatenate((Y, Y_tr), axis=0)
Y_hist = np.concatenate((Y_hist, Y_hist_tr), axis=0)
X1_act = X.copy()
Y1_act = Y.copy()
Y1hist_act = Y_hist.copy()
# Fitting model with no history for visualization only
spline_mat1_act = compute_spline_mat(X1_act)
gamma_1_act = sm.GLM(Y1_act, spline_mat1_act, family=sm.families.Gamma(sm.families.links.identity))
gamma_res_1_act = gamma_1_act.fit()
mu_1_act_nohist = gamma_res_1_act.mu
v_1_act_nohist = 1 / gamma_res_1_act.scale
params_1_act_nohist = gamma_res_1_act.params
# Fitting model with history
cov1_act = np.concatenate((spline_mat1_act, Y1hist_act), axis=1)
gamma_1_act = sm.GLM(Y1_act, cov1_act, family=sm.families.Gamma(sm.families.links.identity))
gamma_res_1_act = gamma_1_act.fit()
mu_1_act = gamma_res_1_act.mu
v_1_act = 1 / gamma_res_1_act.scale
params_1_act = gamma_res_1_act.params
# For morph 1 inactive trials
X = np.array(1)
Y = np.array(1)
Y_hist = np.array(1)
first_one = True
for tr_id in morph1_inact:
ind = np.where(VRData[:, 20] == tr_id)[0]
X_tr = VRData[ind, :]
X_tr = X_tr[:, 3]
Y_tr = F[cell_id, ind]
Y_hist_tr = compute_hist_cov(Y_tr, hist_wind)
X_tr = X_tr[hist_wind:]
Y_tr = Y_tr[hist_wind:]
if first_one:
X = X_tr.copy()
Y = Y_tr.copy()
Y_hist = Y_hist_tr
first_one = False
else:
X = np.concatenate((X, X_tr), axis=0)
Y = np.concatenate((Y, Y_tr), axis=0)
Y_hist = np.concatenate((Y_hist, Y_hist_tr), axis=0)
X1_inact = X.copy()
Y1_inact = Y.copy()
Y1hist_inact = Y_hist.copy()
# Fititng model with no history for visualization only
spline_mat1_inact = compute_spline_mat(X1_inact)
gamma_1_inact = sm.GLM(Y1_inact, spline_mat1_inact, family=sm.families.Gamma(sm.families.links.identity))
gamma_res_1_inact = gamma_1_inact.fit()
mu_1_inact_nohist = gamma_res_1_inact.mu
v_1_inact_nohist = 1 / gamma_res_1_inact.scale
params_1_inact_nohist = gamma_res_1_inact.params
# Fitting model with history
cov1_inact = np.concatenate((spline_mat1_inact, Y1hist_inact), axis=1)
gamma_1_inact = sm.GLM(Y1_inact, cov1_inact, family=sm.families.Gamma(sm.families.links.identity))
gamma_res_1_inact = gamma_1_inact.fit()
mu_1_inact = gamma_res_1_inact.mu
v_1_inact = 1 / gamma_res_1_inact.scale
params_1_inact = gamma_res_1_inact.params
# Fitting 1-Gamma model to all trials with morph 0 (later used for hypothesis tests of multiple maps)
X = np.array(1)
Y = np.array(1)
Y_hist = np.array(1)
first_one = True
for tr_id in morph_0_trials:
ind = np.where(VRData[:, 20] == tr_id)[0]
X_tr = VRData[ind, :]
X_tr = X_tr[:, 3]
Y_tr = F[cell_id, ind]
Y_hist_tr = compute_hist_cov(Y_tr, hist_wind)
X_tr = X_tr[hist_wind:]
Y_tr = Y_tr[hist_wind:]
if first_one:
X = X_tr.copy()
Y = Y_tr.copy()
Y_hist = Y_hist_tr
first_one = False
else:
X = np.concatenate((X, X_tr), axis=0)
Y = np.concatenate((Y, Y_tr), axis=0)
Y_hist = np.concatenate((Y_hist, Y_hist_tr), axis=0)
X0_all = X.copy()
Y0_all = Y.copy()
Y0hist_all = Y_hist.copy()
spline_mat0_all = compute_spline_mat(X0_all)
cov0_all = np.concatenate((spline_mat0_all, Y0hist_all), axis=1)
gamma_0_all = sm.GLM(Y0_all, cov0_all, family=sm.families.Gamma(sm.families.links.identity))
gamma_res_0_all = gamma_0_all.fit()
mu_0_all = gamma_res_0_all.mu
v_0_all = 1 / gamma_res_0_all.scale
params_0_all = gamma_res_0_all.params
# Fitting 1-Gamma model to all trials with morph 0 (later used for hypothesis tests of multiple maps)
X = np.array(1)
Y = np.array(1)
Y_hist = np.array(1)
first_one = True
for tr_id in morph_1_trials:
ind = np.where(VRData[:, 20] == tr_id)[0]
X_tr = VRData[ind, :]
X_tr = X_tr[:, 3]
Y_tr = F[cell_id, ind]
Y_hist_tr = compute_hist_cov(Y_tr, hist_wind)
X_tr = X_tr[hist_wind:]
Y_tr = Y_tr[hist_wind:]
if first_one:
X = X_tr.copy()
Y = Y_tr.copy()
Y_hist = Y_hist_tr
first_one = False
else:
X = np.concatenate((X, X_tr), axis=0)
Y = np.concatenate((Y, Y_tr), axis=0)
Y_hist = np.concatenate((Y_hist, Y_hist_tr), axis=0)
X1_all = X.copy()
Y1_all = Y.copy()
Y1hist_all = Y_hist.copy()
spline_mat1_all = compute_spline_mat(X1_all)
cov1_all = np.concatenate((spline_mat1_all, Y1hist_all), axis=1)
gamma_1_all = sm.GLM(Y1_all, cov1_all, family=sm.families.Gamma(sm.families.links.identity))
gamma_res_1_all = gamma_1_all.fit()
mu_1_all = gamma_res_1_all.mu
v_1_all = 1 / gamma_res_1_all.scale
params_1_all = gamma_res_1_all.params
# For nohist model columns 2 and 4 are repetitions of columns 1 and 3 and are meaningless, for sake of indexing
gamma_fit_0_act[cell_id, :] = [X0_act, Y0_act, Y0hist_act, spline_mat0_act, cov0_act, mu_0_act, v_0_act,
params_0_act]
gamma_fit_0_act_nohist[cell_id, :] = [X0_act, Y0_act, Y0_act, spline_mat0_act, spline_mat0_act, mu_0_act_nohist,
v_0_act_nohist, params_0_act_nohist]
gamma_fit_0_inact[cell_id, :] = [X0_inact, Y0_inact, Y0hist_inact, spline_mat0_inact, cov0_inact,
mu_0_inact, v_0_inact, params_0_inact]
gamma_fit_0_inact_nohist[cell_id, :] = [X0_inact, Y0_inact, Y0_inact, spline_mat0_inact, spline_mat0_inact,
mu_0_inact_nohist, v_0_inact_nohist, params_0_inact_nohist]
gamma_fit_1_act[cell_id, :] = [X1_act, Y1_act, Y1hist_act, spline_mat1_act, cov1_act, mu_1_act, v_1_act,
params_1_act]
gamma_fit_1_act_nohist[cell_id, :] = [X1_act, Y1_act, Y1_act, spline_mat1_act, spline_mat1_act, mu_1_act_nohist,
v_1_act_nohist, params_1_act_nohist]
gamma_fit_1_inact[cell_id, :] = [X1_inact, Y1_inact, Y1hist_inact, spline_mat1_inact, cov1_inact,
mu_1_inact, v_1_inact, params_1_inact]
gamma_fit_1_inact_nohist[cell_id, :] = [X1_inact, Y1_inact, Y1_inact, spline_mat1_inact, spline_mat1_inact,
mu_1_inact_nohist, v_1_inact_nohist, params_1_inact_nohist]
gamma_fit_0_all[cell_id, :] = [X0_all, Y0_all, Y0hist_all, spline_mat0_all, cov0_all, mu_0_all, v_0_all,
params_0_all]
gamma_fit_1_all[cell_id, :] = [X1_all, Y1_all, Y1hist_all, spline_mat1_all, cov1_all, mu_1_all, v_1_all,
params_1_all]
# Computing log-likelihoods based on different models (only models with history-dependent component)
for tr_id in trial_ids:
ind = np.where(VRData[:, 20] == tr_id)[0]
X_tr = VRData[ind, :]
X_tr = X_tr[:, 3]
Y_tr = F[cell_id, ind]
Y_hist_tr = compute_hist_cov(Y_tr, hist_wind)
X_tr = X_tr[hist_wind:]
Y_tr = Y_tr[hist_wind:]
ll_act0 = np.zeros(shape=X_tr.shape[0])
ll_inact0 = np.zeros(shape=X_tr.shape[0])
ll_act1 = np.zeros(shape=X_tr.shape[0])
ll_inact1 = np.zeros(shape=X_tr.shape[0])
ll_all0 = np.zeros(shape=X_tr.shape[0])
ll_all1 = np.zeros(shape=X_tr.shape[0])
for i in range(X_tr.shape[0]):
# Computing ll_act0 and ll_inact0
ind0 = find_nearest(X0_act, [X_tr[i]])
Y_hist_now = np.reshape(Y_hist_tr[i, :], newshape=[1, Y_hist_tr.shape[1]])
inp = np.concatenate((spline_mat0_act[ind0, :], Y_hist_now), axis=1)
mu_0_act_now = inp.dot(params_0_act)[0]
mu_0_act_now = max(.1, mu_0_act_now)
ll_act0[i] = -scipy.special.loggamma(v_0_act) + v_0_act * np.log(
v_0_act * Y_tr[i] / mu_0_act_now) - v_0_act * Y_tr[i] / mu_0_act_now - np.log(Y_tr[i])
sd_0_act_now = mu_0_act_now/np.sqrt(v_0_act)
ind0 = find_nearest(X0_inact, [X_tr[i]])
Y_hist_now = np.reshape(Y_hist_tr[i, :], newshape=[1, Y_hist_tr.shape[1]])
inp = np.concatenate((spline_mat0_inact[ind0, :], Y_hist_now), axis=1)
mu_0_inact_now = inp.dot(params_0_inact)[0]
mu_0_inact_now = max(.1, mu_0_inact_now)
ll_inact0[i] = -scipy.special.loggamma(v_0_inact) + v_0_inact * np.log(
v_0_inact * Y_tr[i] / mu_0_inact_now) - v_0_inact * Y_tr[i] / mu_0_inact_now - np.log(Y_tr[i])
sd_0_inact_now = mu_0_inact_now / np.sqrt(v_0_inact)
# Computing ll_act1 and ll_inact1
ind0 = find_nearest(X1_act, [X_tr[i]])
Y_hist_now = np.reshape(Y_hist_tr[i, :], newshape=[1, Y_hist_tr.shape[1]])
inp = np.concatenate((spline_mat1_act[ind0, :], Y_hist_now), axis=1)
mu_1_act_now = inp.dot(params_1_act)[0]
mu_1_act_now = max(.1, mu_1_act_now)
mu_1_act_now = inp.dot(params_1_act)
ll_act1[i] = -scipy.special.loggamma(v_1_act) + v_1_act * np.log(
v_1_act * Y_tr[i] / mu_1_act_now) - v_1_act * Y_tr[i] / mu_1_act_now - np.log(Y_tr[i])
sd_1_act_now = mu_1_act_now / np.sqrt(v_1_act)
ind0 = find_nearest(X1_inact, [X_tr[i]])
Y_hist_now = np.reshape(Y_hist_tr[i, :], newshape=[1, Y_hist_tr.shape[1]])
inp = np.concatenate((spline_mat1_inact[ind0, :], Y_hist_now), axis=1)
mu_1_inact_now = inp.dot(params_1_inact)[0]
mu_1_inact_now = max(.1, mu_1_inact_now)
ll_inact1[i] = -scipy.special.loggamma(v_1_inact) + v_1_inact * np.log(
v_1_inact * Y_tr[i] / mu_1_inact_now) - v_1_inact * Y_tr[i] / mu_1_inact_now - np.log(Y_tr[i])
sd_1_inact_now = mu_1_inact_now / np.sqrt(v_1_inact)
# Computing ll_all0 and ll_all1
ind0 = find_nearest(X0_all, [X_tr[i]])
Y_hist_now = np.reshape(Y_hist_tr[i, :], newshape=[1, Y_hist_tr.shape[1]])
inp = np.concatenate((spline_mat0_all[ind0, :], Y_hist_now), axis=1)
mu_0_all_now = inp.dot(params_0_all)[0]
mu_0_all_now = max(.1, mu_0_all_now)
ll_all0[i] = -scipy.special.loggamma(v_0_all) + v_0_all * np.log(
v_0_all * Y_tr[i] / mu_0_all_now) - v_0_all * Y_tr[i] / mu_0_all_now - np.log(Y_tr[i])
sd_0_all_now = mu_0_all_now / np.sqrt(v_0_all)
ind0 = find_nearest(X1_all, [X_tr[i]])
Y_hist_now = np.reshape(Y_hist_tr[i, :], newshape=[1, Y_hist_tr.shape[1]])
inp = np.concatenate((spline_mat1_all[ind0, :], Y_hist_now), axis=1)
mu_1_all_now = inp.dot(params_1_all)[0]
mu_1_all_now = max(.1, mu_1_all_now)
ll_all1[i] = -scipy.special.loggamma(v_1_all) + v_1_all * np.log(
v_1_all * Y_tr[i] / mu_1_all_now) - v_1_all * Y_tr[i] / mu_1_all_now - np.log(Y_tr[i])
sd_1_all_now = mu_1_all_now / np.sqrt(v_1_all)
goodness_of_fit[cell_id, tr_id, 0] = ll_all0
goodness_of_fit[cell_id, tr_id, 1] = ll_all1
# For each trial in ambiguous environments, assigning one spatial map for each original environment based
# on computed log-likelihoods
ll0 = ll_inact0
identified_activity0 = 'inactive'
if np.sum(ll_act0) > np.sum(ll_inact0):
identified_activity0 = 'active'
ll0 = ll_act0
ll1 = ll_inact1
identified_activity1 = 'inactive'
if np.sum(ll_act1) > np.sum(ll_inact1):
ll1 = ll_act1
identified_activity1 = 'active'
# Computing and normalizing likelihood from log-likelihood
L0 = np.exp(ll0)
L1 = np.exp(ll1)
denom = L0 + L1
L0 = L0/denom
L1 = L1/denom
ll_morph = np.array([ll0, ll1])
L_morph = np.array([L0, L1])
# Running the filtering algorithm to compute the decoded probability
p_morph_filt = np.zeros(shape=[2, X_tr.shape[0]])
for i in range(X_tr.shape[0]):
if i == 0:
p_morph_filt[0, i] = L0[i]
p_morph_filt[1, i] = L1[i]
if i > 0:
p_morph_filt[0, i] = L0[i] * ((1 - p) * p_morph_filt[0, i - 1] + p * p_morph_filt[1, i - 1])
p_morph_filt[1, i] = L1[i] * ((1 - p) * p_morph_filt[1, i - 1] + p * p_morph_filt[0, i - 1])
p_morph_filt[:, i] = p_morph_filt[:, i] / np.sum(p_morph_filt[:, i])
# Running the smoother algorithm to compute the decoded probability
p_morph_smooth = np.zeros(shape=[2, X_tr.shape[0]])
for i in range(X_tr.shape[0] - 1, -1, -1):
if i == X_tr.shape[0] - 1:
p_morph_smooth[0, i] = p_morph_filt[0, i]
p_morph_smooth[1, i] = p_morph_filt[1, i]
if i < X_tr.shape[0] - 1:
p_2step_0 = (1 - p) * p_morph_filt[0, i] + p * p_morph_filt[1, i]
p_2step_1 = (1 - p) * p_morph_filt[1, i] + p * p_morph_filt[0, i]
p_morph_smooth[0, i] = p_morph_filt[0, i] * (
(1 - p) * p_morph_smooth[0, i+1] / p_2step_0 + p * p_morph_smooth[1, i+1] / p_2step_1)
p_morph_smooth[1, i] = p_morph_filt[1, i]*(
(1 - p) * p_morph_smooth[1, i+1] / p_2step_1 + p * p_morph_smooth[0, i+1] / p_2step_0)
p_morph_smooth[:, i] = p_morph_smooth[:, i] / np.sum(p_morph_smooth[:, i])
p_morph[cell_id, tr_id, :] = [X_tr, Y_tr, p_morph_filt, p_morph_smooth, L_morph, ll_morph]
if visualize:
print('cell_id = {}, tri_id = {}'.format(cell_id, tr_id))
actual_morph = 1
if tr_id in morph_0_trials:
actual_morph = 0
if tr_id in morph_d25_trials:
actual_morph = .25
if tr_id in morph_d50_trials:
actual_morph = .50
if tr_id in morph_d75_trials:
actual_morph = .75
print('for morph0 identified as {}'.format(identified_activity0))
print('for morph1 identified as {}'.format(identified_activity1))
print('Actual morph: {}'.format(actual_morph))
if np.sum(ll_morph[0, :]) > np.sum(ll_morph[1, :]):
print('Decoded result: morph 0')
else:
print('Decoded result: morph 1')
if True:
plt.subplot(6, 2, 1)
plt.plot(X_tr, L_morph[0, :], color=orange1, label='morph = 0')
plt.plot(X_tr, L_morph[1, :], color=blue1, label='morph = 1')
plt.ylabel('likelihood')
plt.legend()
plt.subplot(6, 2, 2)
plt.plot(X_tr, L_morph[0, :], color=orange1)
plt.plot(X_tr, L_morph[1, :], color=blue1)
plt.subplot(6, 2, 3)
plt.plot(X_tr, p_morph_filt[0, :], color=orange1)
plt.plot(X_tr, p_morph_filt[1, :], color=blue1)
plt.ylabel('filter')
plt.subplot(6, 2, 4)
plt.plot(X_tr, p_morph_filt[0, :], color=orange1)
plt.plot(X_tr, p_morph_filt[1, :], color=blue1)
plt.subplot(6, 2, 5)
plt.plot(X_tr, p_morph_smooth[0, :], color=orange1)
plt.plot(X_tr, p_morph_smooth[1, :], color=blue1)
plt.ylabel('smoother')
plt.subplot(6, 2, 6)
plt.plot(X_tr, p_morph_smooth[0, :], color=orange1)
plt.plot(X_tr, p_morph_smooth[1, :], color=blue1)
if not history:
plt.subplot(6, 2, 7)
plt.plot(X0_act, mu_0_act_nohist, '.', markersize=1)
plt.plot(X0_act, mu_0_act_nohist + 1.96 * mu_0_act_nohist/np.sqrt(v_0_act_nohist), '.',
markersize=1)
plt.plot(X0_act, mu_0_act_nohist - 1.96 * mu_0_act_nohist/np.sqrt(v_0_act_nohist), '.',
markersize=1)
plt.plot(X_tr, Y_tr, ',')
plt.ylabel('active')
plt.subplot(6, 2, 9)
plt.plot(X0_inact, mu_0_inact_nohist, '.', markersize=1)
plt.plot(X0_inact, mu_0_inact_nohist + 1.96 * mu_0_inact_nohist / np.sqrt(v_0_inact_nohist),
'.', markersize=1)
plt.plot(X0_inact, mu_0_inact_nohist - 1.96 * mu_0_inact_nohist / np.sqrt(v_0_inact_nohist),
'.', markersize=1)
plt.plot(X_tr, Y_tr, ',')
plt.ylabel('inactive')
plt.xlabel('morph = 0')
plt.subplot(6, 2, 8)
plt.plot(X1_act, mu_1_act_nohist, '.', markersize=1)
plt.plot(X1_act, mu_1_act_nohist + 1.96 * mu_1_act_nohist / np.sqrt(v_1_act_nohist),
'.', markersize=1)
plt.plot(X1_act, mu_1_act_nohist - 1.96 * mu_1_act_nohist / np.sqrt(v_1_act_nohist),
'.', markersize=1)
plt.plot(X_tr, Y_tr, ',')
plt.subplot(6, 2, 10)
plt.plot(X1_inact, mu_1_inact_nohist, '.', markersize=1)
plt.plot(X1_inact, mu_1_inact_nohist + 1.96 * mu_1_inact_nohist / np.sqrt(v_1_inact_nohist),
'.', markersize=1)
plt.plot(X1_inact, mu_1_inact_nohist - 1.96 * mu_1_inact_nohist / np.sqrt(v_1_inact_nohist),
'.', markersize=1)
plt.plot(X_tr, Y_tr, ',')
plt.xlabel('morph = 1')
else:
plt.subplot(6, 2, 7)
plt.plot(X0_act, mu_0_act, '.', markersize=1)
plt.plot(X0_act, mu_0_act + 1.96 * mu_0_act/np.sqrt(v_0_act), '.', markersize=1)
plt.plot(X0_act, mu_0_act - 1.96 * mu_0_act/np.sqrt(v_0_act), '.', markersize=1)
plt.plot(X_tr, Y_tr, ',')
plt.ylabel('active')
plt.subplot(6, 2, 9)
plt.plot(X0_inact, mu_0_inact, '.', markersize=1)
plt.plot(X0_inact, mu_0_inact + 1.96 * mu_0_inact / np.sqrt(v_0_inact), '.', markersize=1)
plt.plot(X0_inact, mu_0_inact - 1.96 * mu_0_inact / np.sqrt(v_0_inact), '.', markersize=1)
plt.plot(X_tr, Y_tr, ',')
plt.ylabel('inactive')
plt.xlabel('morph = 0')
plt.subplot(6, 2, 8)
plt.plot(X1_act, mu_1_act, '.', markersize=1)
plt.plot(X1_act, mu_1_act + 1.96 * mu_1_act / np.sqrt(v_1_act), '.', markersize=1)
plt.plot(X1_act, mu_1_act - 1.96 * mu_1_act / np.sqrt(v_1_act), '.', markersize=1)
plt.plot(X_tr, Y_tr, ',')
plt.subplot(6, 2, 10)
plt.plot(X1_inact, mu_1_inact, '.', markersize=1)
plt.plot(X1_inact, mu_1_inact + 1.96 * mu_1_inact / np.sqrt(v_1_inact), '.', markersize=1)
plt.plot(X1_inact, mu_1_inact - 1.96 * mu_1_inact / np.sqrt(v_1_inact), '.', markersize=1)
plt.plot(X_tr, Y_tr, ',')
plt.xlabel('morph = 1')
plt.subplot(6, 2, 11)
plt.plot(X_tr, ll_morph[0, :] - ll_morph[1, :], color='m')
plt.plot(X_tr, np.zeros(X_tr.shape), color='gray')
plt.ylabel('loglike diff')
plt.xlabel('position')
plt.subplot(6, 2, 12)
plt.plot(X_tr, ll_morph[0, :] - ll_morph[1, :], color='m')
plt.plot(X_tr, np.zeros(X_tr.shape), color='gray')
plt.ylabel('loglike diff')
plt.xlabel('position')
plt.show()
if visualize2:
show_decode_results_all_trials(exp_id, [cell_id], p_morph)
np.save(os.getcwd() + '/Data/' + mode + '_p_morph_exp_' + str(exp_id) + '.npy', p_morph)
np.save(os.getcwd() + '/Data/' + mode + '_goodness_of_fit_exp_' + str(exp_id) + '.npy', goodness_of_fit)
np.save(os.getcwd() + '/Data/' + mode + '_gamma_fit_0_act_exp_' + str(exp_id) + '.npy', gamma_fit_0_act)
np.save(os.getcwd() + '/Data/' + mode + '_gamma_fit_0_act_nohist_exp_' + str(exp_id) + '.npy', gamma_fit_0_act_nohist)
np.save(os.getcwd() + '/Data/' + mode + '_gamma_fit_0_inact_exp_' + str(exp_id) + '.npy', gamma_fit_0_inact)
np.save(os.getcwd() + '/Data/' + mode + '_gamma_fit_0_inact_nohist_exp_' + str(exp_id) + '.npy', gamma_fit_0_inact_nohist)
np.save(os.getcwd() + '/Data/' + mode + '_gamma_fit_0_all_exp_' + str(exp_id) + '.npy', gamma_fit_0_all)
np.save(os.getcwd() + '/Data/' + mode + '_gamma_fit_1_act_exp_' + str(exp_id) + '.npy', gamma_fit_1_act)
np.save(os.getcwd() + '/Data/' + mode + '_gamma_fit_1_act_nohist_exp_' + str(exp_id) + '.npy', gamma_fit_1_act_nohist)
np.save(os.getcwd() + '/Data/' + mode + '_gamma_fit_1_inact_exp_' + str(exp_id) + '.npy', gamma_fit_1_inact)
np.save(os.getcwd() + '/Data/' + mode + '_gamma_fit_1_inact_nohist_exp_' + str(exp_id) + '.npy', gamma_fit_1_inact_nohist)
np.save(os.getcwd() + '/Data/' + mode + '_gamma_fit_1_all_exp_' + str(exp_id) + '.npy', gamma_fit_1_all)
def decode_morphs_joint(exp_id, p, mode, visualize):
# For each trial, use the log-likelihood values computed by function "decode_morphs" for individual cells to decode
# the represented environment based on the full-population activity
# exp_id: experiment id
# p: probability of jumping form one state to the other one in a first-order Markov chain
# mode: shows if we use small subset of data (mode = short) or all data (mode = all)
# visualize: determines if the function must show the full-population decoding results or not
# each row = [X_tr, Y_tr, p_morphs_filt, p_morph_smooth, p_morph_likelihood]
p_morph_joint = np.empty(shape=[ntrials, 6], dtype=object)
trial_ids = range(ntrials)
for tr_id in trial_ids:
ind = np.where(VRData[:, 20] == tr_id)[0]
X_tr = VRData[ind, 3]
Y_tr = np.mean(F[:, ind], axis=0)
X_tr = X_tr[hist_wind:]
Y_tr = Y_tr[hist_wind:]
p_morph_filt_joint = np.zeros(shape=[2, X_tr.shape[0]])
L_morph_joint = np.zeros(shape=[2, X_tr.shape[0]])
ll_morph_joint = np.zeros(shape=[2, X_tr.shape[0]])
for i in range(X_tr.shape[0]):
ll0 = 0
ll1 = 0
for cell_id in cells_under_study:
print('tr_id = {}, cell_id = {}'.format(tr_id, cell_id))
temp = p_morph[cell_id, tr_id, 5]
ll0 += temp[0, i]
ll1 += temp[1, i]
ll_morph_joint[:, i] = [ll0, ll1]
# Adding a constant for computational reasons (doesn't affect normalized log-likelihoods)
tmp = (ll0 + ll1) / 2
ll0 = ll0 - tmp
ll1 = ll1 - tmp
L0 = np.exp(ll0)
L1 = np.exp(ll1)
if i == 0:
p_morph_filt_joint[0, i] = L0
p_morph_filt_joint[1, i] = L1
if i > 0:
p_morph_filt_joint[0, i] = L0 * (
(1 - p) * p_morph_filt_joint[0, i - 1] + p * p_morph_filt_joint[1, i - 1])
p_morph_filt_joint[1, i] = L1 * (
(1 - p) * p_morph_filt_joint[1, i - 1] + p * p_morph_filt_joint[0, i - 1])
p_morph_filt_joint[:, i] = p_morph_filt_joint[:, i] / np.sum(p_morph_filt_joint[:, i])
L_morph_joint[0, i] = L0
L_morph_joint[1, i] = L1
L_morph_joint[:, i] = L_morph_joint[:, i] / np.sum(L_morph_joint[:, i])
p_morph_smooth_joint = np.zeros(shape=[2, X_tr.shape[0]])
for i in range(X_tr.shape[0] - 1, -1, -1):
if i == X_tr.shape[0] - 1:
p_morph_smooth_joint[0, i] = p_morph_filt_joint[0, i]
p_morph_smooth_joint[1, i] = p_morph_filt_joint[1, i]
if i < X_tr.shape[0] - 1:
p_2step_0 = (1 - p) * p_morph_filt_joint[0, i] + p * p_morph_filt_joint[1, i]
p_2step_1 = (1 - p) * p_morph_filt_joint[1, i] + p * p_morph_filt_joint[0, i]
p_morph_smooth_joint[0, i] = p_morph_filt_joint[0, i] * (
(1 - p) * p_morph_smooth_joint[0, i + 1] / p_2step_0 + p * p_morph_smooth_joint[
1, i + 1] / p_2step_1)
p_morph_smooth_joint[1, i] = p_morph_filt_joint[1, i] * (
(1 - p) * p_morph_smooth_joint[1, i + 1] / p_2step_1 + p * p_morph_smooth_joint[
0, i + 1] / p_2step_0)
p_morph_smooth_joint[:, i] = p_morph_smooth_joint[:, i] / np.sum(p_morph_smooth_joint[:, i])
p_morph_joint[tr_id, :] = [X_tr, Y_tr, p_morph_filt_joint, p_morph_smooth_joint, L_morph_joint, ll_morph_joint]
if visualize == True:
plt.subplot(4, 1, 1)
plt.plot(X_tr, L_morph_joint[0, :], color=orange1, label='morph = 0')
plt.plot(X_tr, L_morph_joint[1, :], color=blue1, label='morph = 1')
plt.ylabel('likelihood')
plt.legend()
plt.subplot(4, 1, 2)
plt.plot(X_tr, p_morph_filt_joint[0, :], color=orange1)
plt.plot(X_tr, p_morph_filt_joint[1, :], color=blue1)
plt.ylabel('filter')
plt.subplot(4, 1, 3)
plt.plot(X_tr, p_morph_smooth_joint[0, :], color=orange1)
plt.plot(X_tr, p_morph_smooth_joint[1, :], color=blue1)
plt.ylabel('smoother')
plt.subplot(4, 1, 4)
plt.plot(X_tr, Y_tr, ',')
plt.show()
np.save(os.getcwd() + '/Data/' + mode + '_p_morph_joint_exp_' + str(exp_id) + '.npy', p_morph_joint)
def decode_morphs_joint_selected(exp_id, p, mode, visualize, visualize2, visualize3, visualize4, selected_trial,
diff_trials, selected_cells):
# For each trial, use the log-likelihood values computed by function "decode_morphs" for individual cells to decode
# the represented environment based on activity of a subset of cells under study, called "selected cells".
# exp_id: experiment id
# p: probability of jumping form one state to the other one in a first-order Markov chain.
# mode: shows if we use shorted version of data (mode = short) or all data (mode = all)
# selected_cells: cells that we use to compute the joint decoding probability
# visualize: determines if the function must show the decoded results for each trial or not.
# visualize2: determines if the function must show a heatmap of decoded probabilities for all trials or not.
# visualize3: determines if the function must show a heatmap for contribution of different cells in the decoding
# results during a single trial called "selected trial".
# selected_trial: the trial used if the visualize3 is TRUE.
# visualize4: determines if the function must show a heatmap for contribution of different cells in the decoding
# results for multiple trials given in "diff_trial". Cells will be sorted based on the location of the maximum
# contribution for the first trial in vector "diff_trials".
# diff_trial: the vector of trial used if visualize4 is TRUE.
# Note: Both visualize3 and visualize4 shouldn't be TRUE simultaneously
for cell_id in selected_cells:
if cell_id not in cells_under_study:
print('WARNING: THE SELECTED CELL IS NOT IN UNDER STUDY CELLS!')
# each row = [X_tr, Y_tr, p_morphs_filt, p_morph_smooth, p_morph_likelihood]
p_morph_joint_selected = np.empty(shape=[ntrials, 6], dtype=object)
trial_ids = range(ntrials)
if visualize4:
tr_id = diff_trials[0]
ind = np.where(VRData[:, 20] == tr_id)[0]
X_tr = VRData[ind, 3]
Y_tr = np.mean(F[:, ind], axis=0)
X_tr = X_tr[hist_wind:]
Y_tr = Y_tr[hist_wind:]
p_morph_filt_joint = np.zeros(shape=[2, X_tr.shape[0]])
L_morph_joint = np.zeros(shape=[2, X_tr.shape[0]])
ll_morph_joint = np.zeros(shape=[2, X_tr.shape[0]])
log_ll = np.zeros(shape=[len(selected_cells), X_tr.shape[0]])
for i in range(X_tr.shape[0]):
cnt = 0
for cell_id in selected_cells:
temp = p_morph[cell_id, tr_id, 5]
log_ll[cnt, i] = temp[0, i] - temp[1, i]
cnt += 1
min_log_ll = np.argmin(log_ll, axis=1)
selected_cells = selected_cells[np.argsort(min_log_ll)]