-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiking_model_utils.py
More file actions
2566 lines (1924 loc) · 106 KB
/
spiking_model_utils.py
File metadata and controls
2566 lines (1924 loc) · 106 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
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
import numpy as np
import os
import torch
# import slicetca
import mat73
from sklearn.linear_model import LassoCV, RidgeCV, ElasticNetCV, LinearRegression
import h5py
import matplotlib.pyplot as plt
# import utils as ut
# import plot as pt
plt.rcParams.update({'font.size': 12,
'axes.spines.right': False,
'axes.spines.top': False,
'legend.frameon': False,})
import sys
from scipy.stats import sem
sys.path.append('/Users/michaelfinch/CA1-interneuron-GLM')
# from utils_TCA_clustering_scratchpad import *
# from GLM_regression_plotting import *
# from modelling_to_date_utils import *
# from SliceTCA_example import *
def flatten_data(neuron_dict):
flattened_data = {}
for var in neuron_dict:
flattened_data[var] = neuron_dict[var].flatten()
return flattened_data
def fit_GLM(animal_factors_dict, neuron_activity, regression='linear', alphas=None):
neuron_activity_flat = neuron_activity.flatten()
flattened_data = flatten_data(animal_factors_dict)
variable_names = [var for var in flattened_data]
design_matrix_X = np.stack([flattened_data[var] for var in variable_names], axis=1)
if regression == 'linear':
model = LinearRegression()
elif regression == 'lasso':
model = LassoCV(alphas=alphas, cv=None) if alphas is not None else LassoCV(cv=None)
elif regression == 'ridge':
model = RidgeCV(alphas=alphas if alphas is not None else [0.1, 1, 10, 100, 1000, 5000], cv=None)
elif regression == 'elastic':
l1_ratio = [0.1, 0.3, 0.5, 0.7, 0.9, 1]
model = ElasticNetCV(alphas=alphas if alphas is not None else [0.1, 1, 10, 100, 1000, 5000],
l1_ratio=l1_ratio, cv=None)
model.fit(design_matrix_X, neuron_activity_flat)
neuron_predicted_activity = model.predict(design_matrix_X)
trialavg_neuron_activity = np.mean(neuron_activity, axis=1)
trialavg_predicted_activity = np.mean(neuron_predicted_activity.reshape(neuron_activity.shape), axis=1)
pearson_R = np.corrcoef(trialavg_predicted_activity, trialavg_neuron_activity)[0, 1]
neuron_GLM_params = {}
neuron_GLM_params['weights'] = {var: model.coef_[idx] for idx, var in enumerate(variable_names)}
neuron_GLM_params['intercept'] = model.intercept_
neuron_GLM_params['alpha'] = model.alpha_ if regression == 'ridge' else None
neuron_GLM_params['l1_ratio'] = model.l1_ratio_ if regression == 'elastic' else None
neuron_GLM_params['R2'] = model.score(design_matrix_X, neuron_activity_flat)
neuron_GLM_params['pearson_R'] = pearson_R
neuron_GLM_params['model'] = model
return neuron_GLM_params, neuron_predicted_activity
def get_residual_activity_dict(activity_dict, predicted_activity_dict):
residual_activity_dict = {}
for animal in activity_dict:
residual_activity_dict[animal] = {}
for neuron in activity_dict[animal]:
residual_activity_dict[animal][neuron] = activity_dict[animal][neuron] - predicted_activity_dict[animal][neuron]
return residual_activity_dict
def fit_GLM_population(factors_dict, activity_dict, quintile=None, regression='ridge', alphas=None):
GLM_params = {}
predicted_activity_dict = {}
for animal in factors_dict:
GLM_params[animal] = {}
predicted_activity_dict[animal] = {}
animal_factors_dict = factors_dict[animal].copy()
if quintile is not None:
num_trials = animal_factors_dict['Activity'].shape[1]
start_idx, end_idx = get_quintile_indices(num_trials, quintile)
for var in animal_factors_dict:
animal_factors_dict[var] = animal_factors_dict[var][:, start_idx:end_idx]
for neuron_idx in activity_dict[animal]:
neuron_activity = activity_dict[animal][neuron_idx]
neuron_GLM_params, neuron_predicted_activity = fit_GLM(animal_factors_dict, neuron_activity, regression, alphas)
GLM_params[animal][neuron_idx] = neuron_GLM_params
predicted_activity_dict[animal][neuron_idx] = neuron_predicted_activity.reshape(activity_dict[animal][neuron_idx].shape)
return GLM_params, predicted_activity_dict
def subset_variables_from_data(factors_dict, variables_to_keep=["Velocity"]):
filtered_factors_dict = {}
for animal in factors_dict:
filtered_factors_dict[animal] = {}
for variable in variables_to_keep:
filtered_factors_dict[animal][variable] = factors_dict[animal][variable]
return filtered_factors_dict
def preprocess_data2(filepath, normalize=True, new_NDNF=False):
factors_dict = {}
activity_dict = {}
if new_NDNF:
with h5py.File(filepath, 'r') as f:
animal_group = f['animal']
shiftR_refs = animal_group['ShiftR'][:]
shiftRunning_refs = animal_group['ShiftRunning'][:]
shiftL_refs = animal_group['ShiftL'][:]
shiftV_refs = animal_group['ShiftV'][:]
for animal_idx in range(len(shiftR_refs)):
delta_f = np.array(f[shiftR_refs[animal_idx][0]])
delta_f = delta_f.swapaxes(0, 2)
velocity = np.array(f[shiftRunning_refs[animal_idx][0]]).T
lick_rate = np.array(f[shiftL_refs[animal_idx][0]]).T
reward_loc = np.array(f[shiftV_refs[animal_idx][0]]).T
if delta_f.shape[1] > 1:
delta_f = delta_f[:, 1:, :] # remove duplicate neuron
num_trials = min(delta_f.shape[1], velocity.shape[1], lick_rate.shape[1], reward_loc.shape[1])
delta_f = delta_f[:, :num_trials, :]
velocity = velocity[:, :num_trials]
lick_rate = lick_rate[:, :num_trials]
reward_loc = reward_loc[:, :num_trials]
nan_trials = (
np.any(np.isnan(lick_rate), axis=0) |
np.any(np.isnan(reward_loc), axis=0) |
np.any(np.isnan(velocity), axis=0) |
np.any(np.isnan(delta_f), axis=(0, 2))
)
animal_key = f'animal_{animal_idx + 1}'
factors_dict[animal_key] = {
"Licks": lick_rate[:, ~nan_trials],
"Reward_loc": reward_loc[:, ~nan_trials],
"Velocity": velocity[:, ~nan_trials]
}
if normalize:
for var in factors_dict[animal_key]:
factors_dict[animal_key][var] = ((factors_dict[animal_key][var] - np.min(factors_dict[animal_key][var])) /
(np.max(factors_dict[animal_key][var]) - np.min(factors_dict[animal_key][var])))
activity_dict[animal_key] = {}
for neuron_idx in range(delta_f.shape[2]): # loop over neurons
neuron_activity = delta_f[:, :, neuron_idx] # (trial, bin)
if np.all(np.isnan(neuron_activity)) or np.all(neuron_activity == 0):
continue
cleaned_activity = neuron_activity[:, ~nan_trials]
if normalize:
cleaned_activity = (cleaned_activity - np.mean(cleaned_activity)) / np.std(cleaned_activity)
neuron_key = f'cell_{neuron_idx + 1}'
activity_dict[animal_key][neuron_key] = cleaned_activity
else:
data_dict = mat73.loadmat(filepath)
# Setup position variables
num_spatial_bins = 10
position_matrix = np.zeros((50, num_spatial_bins))
bin_size = 50 // num_spatial_bins
for i in range(num_spatial_bins):
position_matrix[i * bin_size:(i + 1) * bin_size, i] = 1
for animal_idx, (delta_f, velocity, lick_rate, reward_loc) in enumerate(
zip(data_dict['animal']['ShiftR'], data_dict['animal']['ShiftRunning'], data_dict['animal']['ShiftLrate'], data_dict['animal']['ShiftV'])):
num_trials = min(delta_f.shape[1], lick_rate.shape[1], reward_loc.shape[1], velocity.shape[1])
delta_f = delta_f[:, :num_trials, :]
velocity = velocity[:, :num_trials]
lick_rate = lick_rate[:, :num_trials]
reward_loc = reward_loc[:, :num_trials]
nan_trials = (
np.any(np.isnan(lick_rate), axis=0) |
np.any(np.isnan(reward_loc), axis=0) |
np.any(np.isnan(velocity), axis=0) |
np.any(np.isnan(delta_f), axis=(0, 2)))
animal_key = f'animal_{animal_idx + 1}'
factors_dict[animal_key] = {
"Licks": lick_rate[:, ~nan_trials],
"Reward_loc": reward_loc[:, ~nan_trials],
"Velocity": velocity[:, ~nan_trials]}
# Add position info
num_trials = factors_dict[animal_key]["Velocity"].shape[1]
for bin_idx in range(num_spatial_bins):
bin_key = f"Position_{bin_idx + 1}"
factors_dict[animal_key][bin_key] = np.tile(position_matrix[:, bin_idx][:, np.newaxis], num_trials)
if normalize:
for var in factors_dict[animal_key]:
factors_dict[animal_key][var] = (
(factors_dict[animal_key][var] - np.min(factors_dict[animal_key][var])) /
(np.max(factors_dict[animal_key][var]) - np.min(factors_dict[animal_key][var])))
activity_dict[animal_key] = {}
for neuron_idx in range(delta_f.shape[2]):
neuron_activity = delta_f[:, :, neuron_idx]
if np.all(np.isnan(neuron_activity)) or np.all(neuron_activity == 0):
continue
cleaned_activity = neuron_activity[:, ~nan_trials]
if normalize:
cleaned_activity = (cleaned_activity - np.mean(cleaned_activity)) / np.std(cleaned_activity)
neuron_key = f'cell_{neuron_idx + 1}'
activity_dict[animal_key][neuron_key] = cleaned_activity
return activity_dict, factors_dict
def load_data_regular(file_path=r"C:\Users\Msfin\cloned_repositories\CA1-interneuron-GLM", name="NDNFanalC", new_NDNF=True):
file_path = file_path
filename = name
filepath = os.path.join(file_path, "datasets", filename + ".mat")
activity_dict, factors_dict = preprocess_data2(filepath, normalize=True, new_NDNF=new_NDNF)
filtered_factors_dict = subset_variables_from_data(factors_dict, variables_to_keep=["Velocity"])
GLM_params, double_predicted_activity_dict_NDNF_new = fit_GLM_population(filtered_factors_dict, activity_dict, quintile=None, regression='linear')
double_residual_activity_dict_NDNF_new = get_residual_activity_dict(activity_dict, double_predicted_activity_dict_NDNF_new)
return GLM_params, activity_dict, double_predicted_activity_dict_NDNF_new, factors_dict, filtered_factors_dict, double_residual_activity_dict_NDNF_new
def add_vel_contribution_to_residuals(scaled_data_Hz_dict, GLM_params, animal_velocity_dict):
animal_dict={}
for animal in scaled_data_Hz_dict:
cell_dict = {}
for cell in scaled_data_Hz_dict[animal]:
animal_velocity = animal_velocity_dict[animal]
data = scaled_data_Hz_dict[animal][cell]
weights = GLM_params[animal][cell]['weights']["Velocity"]
intercept = GLM_params[animal][cell]['intercept']
data = data + (weights * animal_velocity) + intercept
cell_dict[cell] = data
animal_dict[animal] = cell_dict
return animal_dict
def get_scaled_data_Hz_dict(activity_dict_EC, Hz_SF=50.0, eps=1e-12):
out = {}
num_cells_per_animal = {}
for animal in activity_dict_EC:
counter=0
per_cell = {}
for cell in activity_dict_EC[animal]:
data = activity_dict_EC[animal][cell]
normalized_data = (data - np.max(data)) / (np.max(data) - np.min(data))
counter+=1
per_cell[cell] = normalized_data
num_cells_per_animal[animal] = counter
out[animal] = per_cell
return out, num_cells_per_animal
# if make_it_spike:
# SEED = 42
# np.random.seed(SEED)
# random.seed(SEED)
# rng = np.random.default_rng(SEED)
# n_EC = 792
# weights_EC = sample_weights(dist, n_EC, rng=rng)
# EC_input_matrix = np.stack(dend_list_EC[:n_EC], axis=0)
# L_prev=500
# precomputed_prepend = np.array(random_timeseries(np.mean(EC_input_matrix), np.std(EC_input_matrix), L_prev))
# v_safe = np.apply_along_axis(_sanitize_velocity_cm_s, 0, an_velocity)
# n_pos = EC_input_matrix.shape[1]
# n_trials = EC_input_matrix.shape[2]
# dx = 180.0 / n_pos
# dt_s_all = dx / v_safe
# time_points_all = np.cumsum(dt_s_all, axis=0)
# total_time_per_trial = time_points_all[-1, :] # (n_trials,)
# T_warp_per_trial = np.floor(total_time_per_trial / dt_constant + 1e-12).astype(int)
# dend_vm_holder = np.zeros((n_trials, 50000))
# t_axis_list = [np.arange(T_warp_per_trial[t], dtype=np.float64) * dt_constant for t in range(n_trials)]
# T2_per_trial = L_prev + T_warp_per_trial
# dt_ms = dt_constant * 1000.0
# for t in range(n_trials):
# start_time = time.time()
# T_warp = int(T_warp_per_trial[t])
# T2 = int(T2_per_trial[t])
# t_axis = t_axis_list[t]
# time_points = time_points_all[:, t] # precomputed
# t_ms = np.arange(T2, dtype=np.float32) * dt_ms
# rows = np.zeros((n_EC, T_warp), dtype=np.float32)
# rate_buf = np.empty(T2, dtype=np.float32)
# rate_buf[:L_prev] = precomputed_prepend[:L_prev]
# for cell in range(n_EC):
# firing = EC_input_matrix[cell, :, t]
# valid = np.isfinite(firing)
# if valid.sum() < 2:
# continue
# warped = np.interp(t_axis, time_points[valid], firing[valid]).astype(np.float32, copy=False)
# # guaranteed len(warped) == T_warp because t_axis came from T_warp
# rate_buf[L_prev:L_prev+T_warp] = warped
# spike_times = get_inhom_poisson_spike_times_by_thinning(rate_buf[:T2], t_ms, dt=dt_ms, refractory=3., rng=rng).astype(int)
# st_curr = spike_times[spike_times >= L_prev] - L_prev
# rows[cell, :T_warp] = epsps_event_add(st_curr, T_warp, kernel).astype(np.float32, copy=False)
# end_time = time.time()
# print(f"total trial time trial {t} time {end_time-start_time}")
# dend_vm_over_time = weights_EC @ rows #X_trial
# dend_vm_holder[t,:len(dend_vm_over_time)] = dend_vm_over_time
# SEED = 42
# np.random.seed(SEED)
# random.seed(SEED)
# rng = np.random.default_rng(SEED)
# n_EC = 792
# n_SST = 75
# n_NDNF = 115
# n_dendrites=100
# EC_input_matrix = np.stack(dend_list_EC[:n_EC], axis=0)
# SST_input_matrix = np.stack(dend_list_SST[:n_SST], axis=0)
# NDNF_input_matrix = np.stack(dend_list_NDNF[:n_NDNF], axis=0)
# n_pos = EC_input_matrix.shape[1]
# n_trials = EC_input_matrix.shape[2]
# dx = 180.0 / n_pos
# vel = an_velocity
# if vel.shape != (n_pos, n_trials):
# raise ValueError(f"velocity shape {vel.shape} != {(n_pos, n_trials)}")
# L_prev = 500
# precomputed_prepend = random_timeseries(np.mean(EC_input_matrix), np.std(EC_input_matrix) ,L_prev)
# weights_EC = sample_weights(dist, n_EC, rng=rng)
# max_length = 0
# dend_vm_list = [] # list of (n_EC, T_fixed)
# for t in range(EC_input_matrix.shape[2]):
# start_time = time.time()
# v_cm_s = _sanitize_velocity_cm_s(an_velocity[:, t])
# dt_s = dx / v_cm_s
# edges_s = np.concatenate(([0.0], np.cumsum(dt_s)))
# total_time = float(edges_s[-1])
# # constant-time axis in seconds
# t_axis = np.arange(0.0, total_time, dt_constant, dtype=np.float64)
# max_time_over_cells = 0
# firing_example = EC_input_matrix[0, :, t].astype(np.float64, copy=False)
# valid = np.isfinite(firing_example)
# time_points = np.cumsum(dt_s)
# warped_example = np.interp(t_axis, time_points[valid], firing_example[valid]).astype(np.float32, copy=False)
# two_track_length_example = np.concatenate([precomputed_prepend, warped_example], axis=0)
# t_ms = np.arange(two_track_length_example.shape[0]) * dt_ms
# rows= []
# for cell in range(n_EC):
# firing = EC_input_matrix[cell, :, t].astype(np.float64, copy=False)
# valid = np.isfinite(firing)
# if valid.sum() >= 2:
# time_points = np.cumsum(dt_s) # length n_pos
# # start_time = time.time()
# warped = np.interp(t_axis, time_points[valid], firing[valid]).astype(np.float32, copy=False)
# # end_time = time.time()
# # print(f"interpolation_time = {end_time-start_time} ")
# else:
# warped = np.full(1, np.nan, dtype=np.float32)
# two_track_length = np.concatenate([precomputed_prepend, warped], axis=0)
# spike_times = get_inhom_poisson_spike_times_by_thinning(two_track_length, t_ms, dt=dt_ms, refractory=3., generator=None, rng=rng).astype(int)
# st_curr = spike_times[spike_times >= L_prev] - L_prev
# spike_train = np.zeros(warped.shape, dtype=np.uint8)
# spike_train[st_curr] = 1
# # start_time = time.time()
# epsps = epsps_event_add(st_curr, warped.shape[0], kernel)
# if len(epsps) > max_time_over_cells:
# max_time_over_cells = len(epsps)
# print(f"trial {t} len(epsps) {len(epsps)}")
# rows.append(epsps.astype(np.float32, copy=False))
# X_trial = np.stack(rows, axis=0) # (n_EC, padded time)
# dend_vm_over_time = weights_EC @ X_trial
# if len(dend_vm_over_time) > max_length:
# max_length = len(dend_vm_over_time)
# dend_vm_list.append(dend_vm_over_time)
# end_time = time.time()
# print(f"total time {end_time-start_time}")
# dend_vm_padded_list = []
# for trial in range(len(dend_vm_list)):
# dend_vm = dend_vm_list[trial]
# if len(dend_vm) < max_length:
# padded_dend = np.pad(dend_vm, np.nan)
# dend_vm_padded_list.append(padded_dend)
# dend_vm_padded_array = np.array(dend_vm_padded_list)
# # 1. Pre-allocate the final array with NaNs.
# # The shape should be (number of trials, max_length).
# num_trials = len(dend_vm_list)
# dend_vm_padded_array = np.full((num_trials, max_length), np.nan, dtype=np.float32)
# # 2. Iterate and copy the data into the pre-allocated array.
# for trial_index, dend_vm in enumerate(dend_vm_list):
# current_length = len(dend_vm)
# if current_length <= max_length:
# dend_vm_padded_array[trial_index, :current_length] = dend_vm
# def get_scaled_data_Hz_dict(activity_dict_EC, Hz_SF=50):
# scaled_data_Hz_dict={}
# for animal in activity_dict_EC:
# scaled_data_Hz_dict_cell = {}
# for cell in activity_dict_EC[animal]:
# activity = activity_dict_EC[animal][cell][:,:58]
# min_max_actiivty_list = []
# for i in range(activity.shape[1]):
# trial_activity = activity[:, i]
# min_max_actiivty = (trial_activity - (np.min(trial_activity))) / (np.max(trial_activity) - (np.min(trial_activity)))
# scaled_data_Hz = min_max_actiivty * Hz_SF
# min_max_actiivty_list.append(scaled_data_Hz)
# min_max_actiivty_array = np.array(min_max_actiivty_list)
# scaled_data_Hz_dict_cell[cell] = min_max_actiivty_array.T
# scaled_data_Hz_dict[animal] = scaled_data_Hz_dict_cell
# return scaled_data_Hz_dict
# def do_the_interpolation(scaled_data_Hz_dict, an_velocity=None):
# padded_warped_activity_dict = {}
# dt_constant = 0.001 # 1 ms
# total_time_sec = 4.71657036
# npos = 50
# dt_nominal = total_time_sec / npos
# dx = 180 / npos
# for animal in scaled_data_Hz_dict:
# padded_cell = {}
# for cell in scaled_data_Hz_dict[animal]:
# firing_mat = scaled_data_Hz_dict[animal][cell] # shape (npos, n_trials)
# vel = an_velocity # (npos, n_trials)
# # velocity in cm/s
# with np.errstate(divide='ignore', invalid='ignore'):
# proper_velocity = vel * 100.0
# # replace invalid or tiny velocities with NaN so we can skip those trials
# proper_velocity = np.where(
# ~(np.isfinite(proper_velocity)) | (proper_velocity <= 1e-6),
# np.nan, proper_velocity
# )
# dt = dx / proper_velocity # seconds/position bin
# # cumulative time axis per trial
# time_bins = np.cumsum(dt, axis=0) # shape (npos, n_trials)
# # require strictly finite & increasing time axis
# ok_trial = []
# trial_warped_activity = []
# max_len = 0
# num_trials = firing_mat.shape[1]
# for t in range(num_trials):
# tb = time_bins[:, t]
# if (not np.all(np.isfinite(tb))) or (np.any(np.diff(tb) <= 0)):
# # bad velocity for this trial → skip
# continue
# time_axis = np.arange(0.0, tb[-1], dt_constant)
# firing = firing_mat[:, t]
# # guard: if firing has NaNs, drop this trial
# if not np.all(np.isfinite(firing)):
# continue
# warped = np.interp(time_axis, tb, firing)
# # final guard
# if not np.all(np.isfinite(warped)) or warped.size == 0:
# continue
# trial_warped_activity.append(warped)
# max_len = max(max_len, warped.size)
# ok_trial.append(t)
# # if you need padded arrays, you can pad here; otherwise keep list
# print(f"len(trial_warped_activity {len(trial_warped_activity)}")
# padded_cell[cell] = trial_warped_activity
# padded_warped_activity_dict[animal] = padded_cell
# return padded_warped_activity_dict, an_velocity
# def do_the_interpolation(scaled_data_Hz_dict, an_velocity=None, dt_constant=0.001):
# """
# Keep EXACTLY n_trials outputs per cell by repairing velocity rather than skipping trials.
# Returns:
# padded_warped_activity_dict[animal][cell] -> list of length n_trials (each 1D float32)
# an_velocity (unchanged)
# """
# padded_warped_activity_dict = {}
# npos = 50
# dx = 180.0 / npos # cm per bin (match your units)
# for animal in scaled_data_Hz_dict:
# padded_cell = {}
# for cell in scaled_data_Hz_dict[animal]:
# firing_mat = scaled_data_Hz_dict[animal][cell] # (npos, n_trials)
# vel_mat = an_velocity # (npos, n_trials)
# n_pos, n_trials = firing_mat.shape
# assert n_pos == npos, f"expected {npos} pos bins, got {n_pos}"
# trial_warped_activity = []
# for t in range(n_trials):
# firing = firing_mat[:, t].astype(np.float64, copy=False)
# vel_cm = (vel_mat[:, t] * 100.0).astype(np.float64, copy=False)
# # 1) repair velocity (no zeros/NaNs)
# vel_cm = _sanitize_velocity_cm_s(vel_cm)
# if np.any(np.isnan(vel_cm)):
# print('oops nan')
# if np.any(np.any(vel_cm==0)):
# print('oops vel')
# # 2) build strictly increasing time edges
# dt_s = dx / vel_cm
# edges = np.concatenate(([0.0], np.cumsum(dt_s)))
# total_time = float(edges[-1])
# # 3) constant time axis and interpolate
# if np.isfinite(total_time) and total_time > 0 and np.isfinite(firing).sum() >= 2:
# t_axis = np.arange(0.0, total_time, dt_constant, dtype=np.float64)
# # use bin centers for interpolation (edges[1:] are the bin ends)
# time_pts = edges[1:] # length n_pos
# warped = np.interp(t_axis, time_pts, firing)
# warped = warped.astype(np.float32, copy=False)
# if warped.size == 0 or not np.isfinite(warped).any():
# warped = np.full(1, np.nan, dtype=np.float32)
# else:
# print("problem")
# # placeholder if something is still wrong
# warped = np.full(1, np.nan, dtype=np.float32)
# trial_warped_activity.append(warped)
# if np.any(np.isnan(warped)):
# # IMPORTANT: we return a list with length == n_trials
# padded_cell[cell] = trial_warped_activity
# padded_warped_activity_dict[animal] = padded_cell
# return padded_warped_activity_dict, an_velocity
def do_the_interpolation(
scaled_data_Hz_dict,
an_velocity=None,
dt_constant=0.001, # seconds
min_vel_cm_s=1e-3, # clamp ultra small velocities
use_bin_centers=True,
verbose=True,
log_limit=30,
fallback_mode="zero" # "zero" | "first" | "nan"
):
"""
Returns:
padded_warped_activity_dict[animal][cell] -> list of length n_trials (each 1D float32)
an_velocity (unchanged)
"""
assert isinstance(an_velocity, np.ndarray) and an_velocity.ndim == 2, "an_velocity must be (npos, n_trials)"
npos = 50
assert an_velocity.shape[0] == npos, f"an_velocity must have npos={npos} rows"
dx = 180.0 / npos # cm per bin
def _log(msg):
if verbose and (len(bad_trials) < log_limit):
print(msg)
padded_warped_activity_dict = {}
bad_trials = [] # collect a few bad ones to summarize once
for animal in scaled_data_Hz_dict:
padded_cell = {}
for cell in scaled_data_Hz_dict[animal]:
firing_mat = scaled_data_Hz_dict[animal][cell] # (npos, n_trials)
assert firing_mat.shape[0] == npos, f"[{animal}][{cell}] firing_mat shape {firing_mat.shape}, expected ({npos}, n_trials)"
n_pos, n_trials = firing_mat.shape
assert an_velocity.shape[1] == n_trials, f"[{animal}][{cell}] vel trials {an_velocity.shape[1]} != firing trials {n_trials}"
trial_warped_activity = []
for t in range(n_trials):
firing = firing_mat[:, t].astype(np.float64, copy=False)
vel_cm = (an_velocity[:, t]).astype(np.float64, copy=False) # cm/s
# (A) Velocity checks (you said no NaNs/zeros; still guard & clamp tiny)
vel_bad = (~np.isfinite(vel_cm)) | (vel_cm <= 0)
if vel_bad.any():
_log(f"[interp][{animal}][{cell}][t={t}] velocity non-finite or <=0 at {vel_bad.sum()} bins")
# clamp tiny to avoid huge dt_s
vel_cm = np.nan_to_num(vel_cm, nan=min_vel_cm_s, posinf=min_vel_cm_s, neginf=min_vel_cm_s)
vel_cm = np.clip(vel_cm, min_vel_cm_s, None)
# (B) Firing checks
finite_firing = np.isfinite(firing)
n_finite = int(finite_firing.sum())
if n_finite < 2:
_log(f"[interp][{animal}][{cell}][t={t}] firing has only {n_finite} finite samples (need >=2)")
firing_for_interp = np.where(finite_firing, firing, 0.0) # prevent interp NaNs
# (C) Build time grid
dt_s = dx / vel_cm # seconds per bin
edges = np.concatenate(([0.0], np.cumsum(dt_s)))
total_time = float(edges[-1])
# centers are safer; ends also ok if strictly increasing
time_pts = 0.5*(edges[:-1] + edges[1:]) if use_bin_centers else edges[1:]
# quick domain sanity
monotonic = np.all(np.diff(time_pts) > 0)
if not monotonic:
_log(f"[interp][{animal}][{cell}][t={t}] time_pts not strictly increasing (velocity grid issue)")
# (D) Build uniform t_axis
if np.isfinite(total_time) and total_time > 0:
t_axis = np.arange(0.0, total_time, dt_constant, dtype=np.float64)
else:
t_axis = np.array([], dtype=np.float64)
# (E) Diagnose common NaN causes
if t_axis.size == 0:
# total_time < dt_constant or invalid → the classic "empty grid" cause
_log(f"[interp][{animal}][{cell}][t={t}] empty t_axis: total_time={total_time:.6g}, dt={dt_constant}, "
f"vel[min,max]=({vel_cm.min():.3g},{vel_cm.max():.3g}), dt_s[min,max]=({dt_s.min():.3g},{dt_s.max():.3g})")
# (F) Interpolate or fallback
if t_axis.size >= 1 and monotonic and n_finite >= 2:
# np.interp never returns NaNs if inputs are finite; we ensured that
warped = np.interp(t_axis, time_pts, firing_for_interp).astype(np.float32, copy=False)
else:
# fallback — choose policy
if fallback_mode == "zero":
warped = np.zeros(1, dtype=np.float32)
elif fallback_mode == "first":
# pick first finite firing (or 0)
fv = firing[finite_firing][0] if n_finite >= 1 else 0.0
warped = np.array([fv], dtype=np.float32)
else: # "nan"
warped = np.full(1, np.nan, dtype=np.float32)
bad_trials.append((animal, cell, t))
# Final assert: keep no-NaN if you want to protect downstream
if not np.isfinite(warped).all():
_log(f"[interp][{animal}][{cell}][t={t}] warped still has NaNs (likely due to fallback='nan').")
trial_warped_activity.append(warped)
padded_cell[cell] = trial_warped_activity
padded_warped_activity_dict[animal] = padded_cell
if verbose and bad_trials:
print(f"[interp] {len(bad_trials)} trials used fallback (most common cause: tiny total_time < dt). "
f"Examples (up to {log_limit}):")
for a, c, t in bad_trials[:log_limit]:
print(f" animal={a}, cell={c}, trial={t}")
return padded_warped_activity_dict, an_velocity
def get_plateau_and_cumulative_ragged(
padded_warped_activity_dict,
dend_threshold,
plateau_len=300, # samples (300 @ 1 ms = 300 ms)
refractory=800, # samples
scan_step=100 # samples
):
plateau_dict_animal = {}
counts_dict_animal = {}
for animal, cells in padded_warped_activity_dict.items():
plateau_dict_cell = {}
counts_dict_cell = {}
for cell, trials in cells.items(): # trials: List[np.ndarray] (ragged)
plateau_arrays = []
starts_per_trial = []
for x in trials:
# guard for bad/empty trials
if not isinstance(x, np.ndarray) or x.size == 0 or ~np.isfinite(x).any():
plateau_arrays.append(np.zeros(1, dtype=np.uint8))
starts_per_trial.append(0)
continue
x = np.asarray(x, dtype=float)
marks = np.zeros_like(x, dtype=np.uint8)
i = 0
N = x.size
n_starts = 0
while i < N:
if x[i] > dend_threshold:
end = min(i + plateau_len, N)
marks[i:end] = 1
n_starts += 1
i += refractory
else:
i += scan_step
plateau_arrays.append(marks)
starts_per_trial.append(n_starts)
# ----- PAD & STACK to get a true 2-D array (trials × timebins) -----
if len(plateau_arrays) == 0:
plateau_2d = np.zeros((0, 0), dtype=np.uint8)
cumulative = np.zeros((0,), dtype=int)
else:
max_len = max(arr.size for arr in plateau_arrays)
if max_len == 0:
plateau_2d = np.zeros((len(plateau_arrays), 0), dtype=np.uint8)
else:
plateau_2d = np.zeros((len(plateau_arrays), max_len), dtype=np.uint8)
for i, arr in enumerate(plateau_arrays):
plateau_2d[i, :arr.size] = arr # pad with 0s to the right
cumulative = np.cumsum(np.asarray(starts_per_trial, dtype=int))
plateau_dict_cell[cell] = plateau_2d # shape: (n_trials, max_len)
counts_dict_cell[cell] = cumulative # shape: (n_trials,)
plateau_dict_animal[animal] = plateau_dict_cell
counts_dict_animal[animal] = counts_dict_cell
return plateau_dict_animal, counts_dict_animal
def get_inhom_poisson_spike_times_by_thinning(rate, t, dt=0.02, refractory=3., generator=None, rng=None):
"""
Given a time series of instantaneous spike rates in Hz, produce a spike train consistent with an inhomogeneous
Poisson process with a refractory period after each spike.
:param rate: instantaneous rates in time (Hz)
:param t: corresponding time values (ms)
:param dt: temporal resolution for spike times (ms)
:param refractory: absolute deadtime following a spike (ms)
:param generator: :class:'random.Random()'
:return: list of m spike times (ms)
"""
if generator is None:
generator = rng
interp_t = np.arange(t[0], t[-1] + dt, dt)
interp_rate = np.interp(interp_t, t, rate)
interp_rate /= 1000.
non_zero = np.where(interp_rate > 0.)[0]
interp_rate[non_zero] = 1. / (1. / interp_rate[non_zero] - refractory)
spike_times = []
max_rate = np.max(interp_rate)
i = 0
ISI_memory = 0.
while i < len(interp_t):
x = generator.random()
if x > 0.:
ISI = -np.log(x) / max_rate
i += int(ISI / dt)
ISI_memory += ISI
if (i < len(interp_t)) and (generator.random() <= interp_rate[i] / max_rate) and ISI_memory >= 0.:
spike_times.append(interp_t[i])
ISI_memory = -refractory
return np.array(spike_times)
def exp_kernel(tau_ms, dt_ms, n_taus=5, norm="area", target=1.0):
"""
Create a causal exponential kernel e^{-t/tau}.
norm: "area" -> sum(kernel) == 1
"peak" -> max(kernel) == 1
target: scales the chosen normalization (e.g., target mV or arbitrary units).
"""
klen = int(np.ceil(n_taus * tau_ms / dt_ms))
t = np.arange(klen) * dt_ms
k = np.exp(-t / tau_ms)
if norm == "area":
k /= k.sum() + 1e-12 # unit L1
elif norm == "peak":
k /= k.max() + 1e-12 # unit peak
else:
raise ValueError("norm must be 'area' or 'peak'")
return k * target # final amplitude per spike
def get_velocity_array(factors_dict_EC, factors_dict_SST, fixed_filtered_factors_dict_NDNF_newest, which_type=None):
if which_type == "EC_animal_average":
an_velocity_real_list = []
for animal in factors_dict_EC:
an_velocity_real_list.append(factors_dict_EC[animal]["Velocity"][:,:58])
an_velocity_real_array = np.array(an_velocity_real_list)
an_velocity_real_array_mean_animal = np.nanmean(an_velocity_real_array, axis=0)
return an_velocity_real_array_mean_animal
elif which_type == "repeated_waveform":
an_velocity_real_list_all = []
for animal in factors_dict_EC:
an_velocity_real_list_all.append(factors_dict_EC[animal]["Velocity"][:,:58])
for animal in factors_dict_SST:
an_velocity_real_list_all.append(factors_dict_SST[animal]["Velocity"][:,:58])
for animal in fixed_filtered_factors_dict_NDNF_newest:
an_velocity_real_list_all.append(fixed_filtered_factors_dict_NDNF_newest[animal]["Velocity"][:,:58])
an_velocity_real_array_all = np.array(an_velocity_real_list_all)
an_velocity_real_array_mean_animal_all = np.mean(an_velocity_real_array_all, axis=0)
mean_velocity = np.mean(an_velocity_real_array_mean_animal_all, axis=1)
mean_vel_2d = np.tile(mean_velocity[:,None], (1,58))
return mean_vel_2d
elif which_type == "constant":
constant_vel = np.full((50,58), 0.43)
return constant_vel
def get_epsp_dict(padded_warped_activity_dict, tau_ms=None, amp=None, seed=None):
dt_constant = 0.001
dt_ms = dt_constant * 1000.0 # 1 ms
tau_ms = tau_ms
dt_ms = dt_constant * 1000.0 # 1 ms
AMP = amp # mV
MODE = "peak" # "area" or "peak"
kernel = exp_kernel(tau_ms, dt_ms, n_taus=5, norm=MODE, target=AMP)
rng = np.random.default_rng(seed)
animal_dict = {}
for animal in padded_warped_activity_dict:
cell_dict = {}
for cell in padded_warped_activity_dict[animal]:
epsps_dict= {}
spike_times_dict = {}
spike_train_dict = {}
padded_warped_activity = padded_warped_activity_dict[animal][cell]
for trial in range(len(padded_warped_activity)):
example_padded_warped_activity = padded_warped_activity[trial]
if trial > 0:
example_previous_pad = padded_warped_activity[trial-1]
else:
example_previous_pad = padded_warped_activity[trial+1]
L_prev = example_previous_pad.shape[0]
L_curr = example_padded_warped_activity.shape[0]
two_track_length = np.concatenate([example_previous_pad, example_padded_warped_activity], axis=0)
t_ms = np.arange(two_track_length.shape[0]) * dt_ms
spike_times = get_inhom_poisson_spike_times_by_thinning(two_track_length, t_ms, dt=dt_ms, refractory=3., generator=None, rng=rng).astype(int)
st_curr = spike_times[spike_times >= L_prev] - L_prev
spike_times_dict[trial] = st_curr
spike_train = np.zeros(two_track_length.shape, dtype=np.uint8)
spike_train[spike_times] = 1
spike_train_curr = spike_train[L_prev : L_prev + L_curr]
spike_train_dict[trial] = spike_train_curr
epsps = np.convolve(spike_train, kernel, mode='full')[:len(spike_train)]
epsps_curr = epsps[L_prev : L_prev + L_curr]
epsps_dict[trial] = epsps_curr
# epsps_scaled = epsps-60
# dendrite.append(epsps_scaled)
cell_dict[cell] = {"epsps":epsps_dict,
"spike_times":spike_times_dict,
"spike_train":spike_train_dict}
animal_dict[animal] = cell_dict
return animal_dict, kernel
# def get_dend_vm(epsp_dict, Vrest=-60.0, epsp_sf=0.1):
# cell_epsp_mats = []
# cell_spike_mats = []
# # --- per cell: build (n_trials, T_cell) as float so we can NaN-pad ---
# for animal in epsp_dict:
# for cell in epsp_dict[animal]:
# epsp = epsp_dict[animal][cell]["epsps"] # dict: trial -> 1D array (float)
# spik = epsp_dict[animal][cell]["spike_train"] # dict: trial -> 1D array (uint8)
# if not epsp: # skip truly empty cells
# continue
# # Per-cell max lengths (time)
# max_len_epsp = max(len(epsp[t]) for t in epsp)
# max_len_spik = max(len(spik[t]) for t in spik)
# # EPSPs -> (n_trials, max_len_epsp), float with NaN padding
# epsp_trials = []
# for t in range(len(epsp)):
# v = np.asarray(epsp[t], dtype=np.float32)
# if v.size < max_len_epsp:
# v = np.pad(v, (0, max_len_epsp - v.size), mode="constant", constant_values=np.nan)
# epsp_trials.append(v)
# epsp_mat = np.vstack(epsp_trials).astype(np.float32, copy=False)
# cell_epsp_mats.append(epsp_mat)
# # Spikes -> (n_trials, max_len_spik), cast to float before NaN padding
# spk_trials = []
# for t in range(len(spik)):
# v = np.asarray(spik[t], dtype=np.float32) # cast BEFORE padding so NaN is valid
# if v.size < max_len_spik:
# v = np.pad(v, (0, max_len_spik - v.size), mode="constant", constant_values=np.nan)
# spk_trials.append(v)
# spk_mat = np.vstack(spk_trials).astype(np.float32, copy=False)
# cell_spike_mats.append(spk_mat)
# if not cell_epsp_mats:
# raise ValueError("No EPSP matrices were built (empty epsp_dict?).")
# # --- across cells: pad to GLOBAL (n_trials, T) so we can stack cleanly ---
# global_T = max(m.shape[1] for m in cell_epsp_mats)
# global_N = max(m.shape[0] for m in cell_epsp_mats)
# def pad_to_global(mat):
# n, t = mat.shape
# dn = global_N - n
# dt = global_T - t
# if dn > 0 or dt > 0:
# mat = np.pad(mat, ((0, max(dn,0)), (0, max(dt,0))),
# mode="constant", constant_values=np.nan)
# return mat.astype(np.float32, copy=False)