-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmathfuncs.py
More file actions
2271 lines (1855 loc) · 77.6 KB
/
Copy pathmathfuncs.py
File metadata and controls
2271 lines (1855 loc) · 77.6 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 n
from scipy.ndimage import convolve1d
from scipy.ndimage import gaussian_filter1d, uniform_filter1d
from scipy import stats
from scipy import fft
from scipy.special import gamma as gammafunct
from scipy.special import kv
from scipy.stats import gennorm
from scipy.optimize import curve_fit
from statsmodels.nonparametric import smoothers_lowess as slw
# import sympy as sp
from scipy.special import kv as _besselk, gamma as _gammafunct
from scipy.sparse.linalg import eigs, eigsh
def var_explained(true, pred):
"""
Compute the fraction of variance explained by the model.
Args:
true (ndarray): True values. Can be 1D or 2D (n_cells x n_timepoints).
pred (ndarray): Predicted values. Same shape as true.
Returns:
float or ndarray:
- If input is 1D: single float with fraction of variance explained
- If input is 2D: array of shape (n_cells,) with variance explained for each cell
"""
true = n.asarray(true)
pred = n.asarray(pred)
if true.shape != pred.shape:
raise ValueError("True and predicted arrays must have the same shape.")
if true.ndim == 1:
# Original behavior for 1D arrays
ss_total = n.sum((true - n.mean(true)) ** 2)
ss_residual = n.sum((true - pred) ** 2)
return 1 - (ss_residual / ss_total)
elif true.ndim == 2:
# New behavior for 2D arrays (n_cells x n_timepoints)
# Compute variance explained for each cell (row)
ss_total = n.sum((true - n.mean(true, axis=1, keepdims=True)) ** 2, axis=1)
ss_residual = n.sum((true - pred) ** 2, axis=1)
# Handle case where ss_total is zero (constant true values)
var_exp = n.zeros(true.shape[0])
nonzero_mask = ss_total > 0
var_exp[nonzero_mask] = 1 - (ss_residual[nonzero_mask] / ss_total[nonzero_mask])
return var_exp
else:
raise ValueError("Input arrays must be 1D or 2D.")
def summarize_dist(vals, factor=None):
vals = n.asarray(vals)
vals = vals[~n.isnan(vals)]
if vals.ndim != 1:
raise ValueError("Input must be a 1D array.")
if len(vals) == 0:
print("#### EMPTY ARRAY ####")
return {}
# Scale the values
max_abs = n.max(n.abs(vals))
if factor is None:
factor = 10 ** n.floor(n.log10(max_abs / 100)) if max_abs > 100 else 10 ** n.ceil(n.log10(10 / max_abs)) if max_abs < 10 else 1
scaled = vals * factor
pcts = [0.1, 1, 5, 10, 25, 50, 75, 90, 95, 99, 99.9]
# Compute stats
stats = {
"mean": n.mean(scaled),
"median": n.median(scaled),
"std": n.std(scaled),
"min": n.min(scaled),
"max": n.max(scaled),
"range": n.max(scaled) - n.min(scaled),
"percentiles": {p: n.percentile(scaled, p) for p in pcts},
"scaling_factor": factor,
}
def fmt(x):
return f"{x:6.2f}"
# Prepare output lines
lines = [
"#### DISTRIBUTION SUMMARY ####",
f"Scaling factor: {factor:.1f}",
f"Mean: {fmt(stats['mean'])}" + f" Median: {fmt(stats['median'])}" + f" Std Dev: {fmt(stats['std'])}",
f"Min: {fmt(stats['min'])}" + f" Max: {fmt(stats['max'])}" + f" Range: {fmt(stats['range'])}",
"Percentiles:",
]
header = [0.1, 1, 5, 10, 25, 50, 75, 90, 95, 99, 99.9]
values = [stats["percentiles"][float(h)] for h in header]
header_str = " ".join(f"{fmt(h):>5}" for h in header)
value_str = " ".join(f"{fmt(v):>5}" for v in values)
lines.append(header_str)
lines.append(value_str)
print("\n".join(lines))
# Flatten percentiles into the dict
stats.update({f"percentile_{p}": v for p, v in stats["percentiles"].items()})
del stats["percentiles"]
return stats
def compute_lagcorrs(data, n_rows=50, tidxs=None):
"""
compute the lagged covariance matrix using FFT method.
lagcorrs[i,j,t] = E[data[i,tau] * data[j, tau + t]]
Args:
data (ndarray): nvar,nt
n_rows (int, optional): clip and use only the first n_rows rows of data. Defaults to 50.
tidxs (int, optional): clip the timepoints of the returned array. Defaults to None.
Returns:
lagcorrs: lagged covariance tensor
"""
nvar, nt = data.shape
# compute the fft of the cross-corr tensor in fourier space
f_a_fft = fft.fft(data[:n_rows,], axis=-1, n=2 * nt)
f_a_fft_conj = n.conj(f_a_fft)
cross_spec_tensor = n.einsum("ik,jk->ijk", f_a_fft, f_a_fft_conj)
lagged_corr_tensor = fft.ifft(cross_spec_tensor)[:, :].real
maxs = lagged_corr_tensor[n.diag_indices(n_rows)][:, 0]
norms = 0.5 * (maxs[n.newaxis] + maxs[:, n.newaxis])
norm_lagged_corr_tensor = lagged_corr_tensor / norms[:, :, n.newaxis]
if tidxs is None:
tidxs = norm_lagged_corr_tensor.shape[-1] // 2
lagcorrs = norm_lagged_corr_tensor[:, :, :tidxs]
return lagcorrs
def autocorrelation_fft(
data,
dt=1.0,
max_lag=None,
t_window=None,
demean=True,
unbiased=True,
normalize=True,
estimate_tau=False,
tau_exclude_zero_lag=True,
tau_min_points=5,
):
"""
Compute the autocorrelation function (ACF) for each timeseries using an FFT-based method.
Args:
data (ndarray): Array of shape (n_cells, n_time) or (n_time,). Each row is a timeseries.
dt (float, optional): Sampling interval. Used to generate the time axis. Defaults to 1.0.
max_lag (int, optional): Maximum lag (in samples) on either side of zero to return.
If None, returns the full range (nt-1) on each side.
t_window (float, optional): If provided, trims the ACF to lags within +/- t_window seconds.
Overrides max_lag if both are given.
demean (bool, optional): Subtract the per-series mean before computing ACF. Defaults to True.
unbiased (bool, optional): If True, divide by (N - lag) to remove finite-sample bias.
If False, divide by N (biased estimator). Defaults to True.
normalize (bool, optional): If True, divide each ACF by its zero-lag value so that ACF[:,0] = 1.
Defaults to True.
Extra options (time constant fit):
To also estimate a time constant per series by fitting an exponential decay to the
non‑negative lags, call with estimate_tau=True. See return values below.
Returns:
acf (ndarray): Shape (n_cells, Lc) array of autocorrelations for symmetric lags
from negative to positive centered at 0.
t (ndarray): Shape (Lc,) array of time lags (seconds) corresponding to acf columns, sorted ascending
from negative to positive and containing 0.
tau (ndarray, optional): If estimate_tau=True, shape (n_cells,) array of fitted time constants (seconds).
Notes:
- Uses zero-padding and the Wiener–Khinchin theorem: IFFT(|FFT(x)|^2) to get the linear/aperiodic ACF.
- Returns only non-negative lags (0..L-1). For symmetric lags, mirror as needed outside this function.
- If a series is constant (zero variance), the normalized ACF will be zeros except ACF[:,0]=1 if normalize=True.
"""
x = n.asarray(data)
if x.ndim == 1:
x = x[n.newaxis, :]
if x.ndim != 2:
raise ValueError("data must be 1D (nt,) or 2D (nc, nt)")
nc, nt = x.shape
# Optional de-meaning per series
if demean:
x = x - x.mean(axis=1, keepdims=True)
# Zero-pad to avoid circular correlation: length >= 2*nt-1 gives linear ACF for |lag|<=nt-1
nfft = 2 * nt
X = fft.fft(x, n=nfft, axis=-1)
S = X * n.conj(X)
acf_full = fft.ifft(S, axis=-1).real # shape (nc, 2*nt)
# Assemble full linear ACF for lags k = -(nt-1)..(nt-1)
# Non-negative lags are at indices [0:nt); negative lags are wrapped at the end
neg = acf_full[:, nfft - (nt - 1) : nfft]
pos = acf_full[:, :nt]
acf_lin = n.concatenate([neg, pos], axis=1) # shape (nc, 2*nt-1)
# Build lag index and counts for unbiased normalization
lags = n.arange(-(nt - 1), nt)
# Normalization across lags
if unbiased:
counts = (nt - n.abs(lags))[n.newaxis, :]
counts = n.maximum(counts, 1)
acf = acf_lin / counts
else:
acf = acf_lin / nt
if normalize:
# Normalize so that acf at lag 0 equals 1 when variance > 0
z = acf[:, lags == 0]
safe = n.where(z == 0.0, 1.0, z)
acf = acf / safe
acf[:, lags == 0] = 1.0
# Time axis in seconds, centered at 0
t = lags.astype(float) * float(dt)
# Optional trimming by time window or sample max_lag
if t_window is not None:
mask = n.abs(t) <= float(t_window) + 1e-12
acf = acf[:, mask]
t = t[mask]
elif max_lag is not None:
M = int(max_lag)
M = max(0, min(M, nt - 1))
mask = (lags >= -M) & (lags <= M)
acf = acf[:, mask]
t = t[mask]
# Optionally estimate a time constant per series by fitting y = offset + amp * exp(-t/tau)
if estimate_tau:
# Work on non-negative lags only (decay side)
pos_mask = t >= 0
if tau_exclude_zero_lag:
pos_mask = n.logical_and(pos_mask, t > 0)
tt = t[pos_mask]
taus = n.full((nc,), n.nan, dtype=float)
if tt.size >= tau_min_points:
# Bounds: tau>0; amp, offset unconstrained unless normalize
if normalize:
bounds = ((1e-12, -n.inf, -1.0), (n.inf, n.inf, 1.0))
else:
bounds = ((1e-12, -n.inf, -n.inf), (n.inf, n.inf, n.inf))
def model(t_, tau, amp, offset):
return offset + amp * n.exp(-t_ / tau)
for i in range(nc):
yy = acf[i, pos_mask]
# Heuristic initial guesses
# offset0: median of tail
tail_n = max(3, int(n.ceil(0.1 * yy.size)))
offset0 = n.median(yy[-tail_n:])
amp0 = yy[0] - offset0 if yy.size > 0 else 1.0
if not n.isfinite(amp0) or abs(amp0) < 1e-8:
amp0 = 1.0
# tau0 via log-linear ignoring offset (where yy > offset0)
msk = yy > offset0 + 1e-6
tau0 = None
if n.count_nonzero(msk) >= 2:
tsel = tt[msk]
ysel = yy[msk] - offset0
try:
slope, _ = n.polyfit(tsel, n.log(ysel), 1)
if slope < 0:
tau0 = -1.0 / slope
except Exception:
tau0 = None
if tau0 is None or not n.isfinite(tau0) or tau0 <= 0:
tau0 = max(1e-3, 0.2 * (tt[-1] - tt[0]))
p0 = (float(tau0), float(amp0), float(offset0))
try:
popt, _ = curve_fit(model, tt, yy, p0=p0, bounds=bounds, maxfev=10000)
taus[i] = float(popt[0])
except Exception:
taus[i] = n.nan
# Return with taus
return acf, t, taus
return acf, t
def correlate(array, vector):
"""
compute the correlation of each element in array with given vector
Args:
array (ndarray): n_cells, nt
vector (ndarray): nt
Returns:
correlation of each row of the array with the vector, size n_cells
"""
vector = n.squeeze(vector)
squeeze_output = False
if len(array.shape) == 1:
array = array[n.newaxis, :]
squeeze_output = True
array = array - array.mean(axis=1, keepdims=True)
vector = vector - vector.mean(axis=0)
cov = (array * vector[n.newaxis]).sum(axis=1)
var_arr = n.sqrt((array**2).sum(axis=1))
var_vec = n.sqrt((vector**2).sum(axis=0))
# print(vector.shape)
# print(cov.shape, var_arr.shape, var_vec.shape)
out = cov / (var_arr * var_vec)
if squeeze_output:
out = float(n.squeeze(out))
return out
def correlate_vectors(arr1, arr2):
"""
compute the correlation coefficient between two arrays of vectors
each array contains n_item vectors of length n_dim, and the output is n_item long
Args:
arr1 (ndarray): n_items, n_dim
arr2 (ndarray): n_items, n_dim
"""
arr1 = arr1 - arr1.mean(axis=1, keepdims=True)
arr2 = arr2 - arr2.mean(axis=1, keepdims=True)
cov = (arr1 * arr2).sum(axis=1)
var1 = n.sqrt((arr1**2).sum(axis=1))
var2 = n.sqrt((arr2**2).sum(axis=1))
corr = cov / (var1 * var2)
return corr
def cov_mat(arr, nan_diag=False, dtype=n.float32, eps=1e-6,):
"""
compute covariance matrix of a data matrix. Similar to n.cov
Args:
arr (ndarray): n_cells, n_timepoints
Returns:
cov: n_cells, n_cells
"""
arr = arr.astype(dtype)
arr = arr - arr.mean(axis=1, keepdims=True)
cov = arr @ arr.T / (arr.shape[1] - 1)
if nan_diag:
n.fill_diagonal(cov, n.nan)
return cov
def corr_mat(arr, nan_diag=False, dtype=n.float32, eps=1e-6):
"""
compute correlation matrix of a data matrix. Similar to n.corrcoef
Args:
arr (ndarray): n_cells, n_timepoints
Returns:
corr: n_cells, n_cells
"""
arr = arr.astype(dtype)
arr = arr - arr.mean(axis=1, keepdims=True)
cov = arr @ arr.T
var = (arr**2).sum(axis=1)
corr = cov / (n.sqrt(var[:, n.newaxis] @ var[n.newaxis]) + eps)
if nan_diag:
n.fill_diagonal(corr, n.nan)
return corr
def cv_cov_mat(arr0, arr1, dtype=n.float32):
"""
compute cross-validated covariance matrix to stimulus responses
Args:
arr0 (ndarray): n_cells_A, n_trials - first half
arr1 (ndarray): n_cells_B, n_trials - second half
Returns:
cv_cov: cross-validated covariance
"""
arr0 = arr0.astype(dtype)
arr1 = arr1.astype(dtype)
arr0 = arr0 - arr0.mean(axis=1, keepdims=True)
arr1 = arr1 - arr1.mean(axis=1, keepdims=True)
cov = arr0 @ arr1.T
return cov
def cv_corr_mat(arr0, arr1, dtype=n.float32):
"""
compute cross-validated corr matrix to stimulus responses
Args:
arr0 (ndarray): n_cells, n_trials - first half
arr1 (ndarray): n_cells, n_trials - second half
Returns:
cv_corr: cross-validated corr
"""
arr0 = arr0.astype(dtype)
arr1 = arr1.astype(dtype)
arr0 = arr0 - arr0.mean(axis=1, keepdims=True)
arr1 = arr1 - arr1.mean(axis=1, keepdims=True)
cov = arr0 @ arr1.T
var0 = (arr0**2).sum(axis=1)
var1 = (arr1**2).sum(axis=1)
cv_corr = cov / n.sqrt(var0[:, n.newaxis] @ var1[n.newaxis])
return cv_corr
def zscore(x, nax=0, m=None, std=None, return_params=False, auto_reshape=True, undo=False):
"""zscore a given axis of an n-dimensional array based on given or computed parameters.
If you have an array of shape x,y,z and nax=1, the activity will be average over all
x and z, so the mean and std will have shape 1,y,1.
Args:
x (ndarray): ndim array
nax (list or int, optional): Axes to *not* average over, typically the neuron axis. Defaults to 0.
m (ndarray, optional): mean. Defaults to computing from x.
std (ndarray, optional): std. Defaults to computing from x.
return_params (bool, optional): Return m and std in a tuple. Defaults to False.
auto_reshape (bool, optional): Automatically fix the shapes of m and std. Defaults to True.
"""
# x = n.squeeze(x)
ndim = len(x.shape)
if ndim == 1:
nax = [-1]
nax = n.array(nax).astype(int)
axes_to_reduce = n.array([i if i not in nax else n.nan for i in range(ndim)])
axes_to_reduce = tuple(n.array(axes_to_reduce)[~n.isnan(axes_to_reduce)].astype(int))
if m is None:
m = x.mean(axis=axes_to_reduce, keepdims=True)
if std is None:
std = x.std(axis=axes_to_reduce, keepdims=True)
std += 1e-6
if auto_reshape:
param_shape = n.ones(ndim).astype(int)
param_shape[nax] = n.array(x.shape)[nax]
# if they are a scalar don't reshape
if n.array(m).size > 1:
m = m.reshape(*param_shape)
if n.array(std).size > 1:
std = std.reshape(*param_shape)
if not undo:
xz = (x - m) / std
else:
xz = (x * std) + m
if return_params:
return xz, (m, std)
else:
return xz
def fill_nans(signal, method="linear", axis=0):
"""
Fill NaN values in a signal using specified method.
Args:
signal (ndarray): Input signal with NaN values.
method (str, optional): Method to fill NaNs. Options are 'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic'.
Defaults to 'linear'.
axis (int, optional): Axis along which to fill NaNs. Defaults to 0.
Returns:
ndarray: Signal with NaN values filled.
"""
from scipy.interpolate import interp1d
if n.isnan(signal).any():
# Create a mask for non-NaN values
mask = ~n.isnan(signal)
# Create an interpolating function
interp_func = interp1d(
n.arange(signal.shape[axis])[mask],
signal[mask],
kind=method,
axis=axis,
bounds_error=False,
fill_value="extrapolate",
)
# Apply the interpolation function
filled_signal = interp_func(n.arange(signal.shape[axis]))
return filled_signal
else:
return signal
def median_filter1d(signal, width=3, axis=0):
"""
apply a simple median filter to a 1d signal
Args:
signal (ndarray): ndim ndarray
width (int, optional): Width of filter. Defaults to 3.
axis (int, optional): axis to apply filter on. Defaults to 0.
Returns:
signal: same shape as input, filtered
"""
if width == 0:
return signal
from scipy.ndimage import median_filter
out = median_filter(signal, size=width, axis=axis)
return out
def area_within_points(xs, ys):
# using the shoelace formula https://en.wikipedia.org/wiki/Shoelace_formula
# xs, ys: (n_shapes, n_points)
xs = n.asarray(xs)
ys = n.asarray(ys)
if xs.shape != ys.shape:
raise ValueError("xs and ys must have the same shape")
# roll by -1 along the last axis for the polygon formula
area = 0.5 * n.abs(n.sum(xs * n.roll(ys, -1, axis=1) - ys * n.roll(xs, -1, axis=1), axis=1))
return area
def filt(signal, width=3, axis=0, mode="gaussian"):
"""
apply a simple filter to a 1d signal
Args:
signal (ndarray): ndim ndarray
width (int, optional): Width of filter. Defaults to 3.
axis (int, optional): axis to apply filter on. Defaults to 0.
mode (str, optional): Type of filter. 'gaussian' or 'uniform'
Returns:
signal: same shape as input, filtered
"""
if width == 0:
return signal
if mode == "gaussian":
out = gaussian_filter1d(signal, sigma=width, axis=axis)
elif mode == "uniform":
# print(width)
out = uniform_filter1d(signal, size=int(n.round(width)), axis=axis)
else:
assert False, "mode not implemented"
return out
def compute_signal_related_variance_ragged(resp, mean_center=True):
"""
Compute the fraction of signal-related variance (and SNR) for each cell
given ragged repeats per stimulus.
Args:
resp (list of arrays): A list of length n_stimuli. Each element resp[i]
is an array of shape (R_i, n_cells), where R_i
is the number of repeats for stimulus i (can vary
across stimuli).
mean_center (bool): Whether to subtract the grand mean of stimulus means
before computing signal variance.
Returns:
fraction_of_stimulus_variance (ndarray): shape (n_cells,), values in [0, 1].
stim_to_noise_ratio (ndarray): shape (n_cells,).
"""
n_stim = len(resp)
# Ensure all stimuli have 2D array (R_i, n_cells) and consistent n_cells
processed = []
n_cells = None
for i, arr in enumerate(resp):
arr = n.asarray(arr) # shape (R_i, n_cells)
if arr.ndim != 2:
raise ValueError(f"Stimulus {i} data must be 2D, got shape {arr.shape}")
Ri, nc = arr.shape
if n_cells is None:
n_cells = nc
elif nc != n_cells:
raise ValueError(f"All stimuli must have the same number of cells; stimulus {i} has {nc}, expected {n_cells}")
processed.append(arr)
# Compute per-stimulus means (mu_i) and per-stimulus noise sums
# mu_mat will be shape (n_stim, n_cells)
mu_mat = n.zeros((n_stim, n_cells), dtype=float)
# noise_accum[i] = (1/R_i) * sum_r (x_{i,r} - mu_i)^2 for each cell
noise_accum = n.zeros((n_stim, n_cells), dtype=float)
for i, arr in enumerate(processed):
Ri = arr.shape[0]
# mean across repeats for each cell
mu_i = arr.mean(axis=0) # shape (n_cells,)
mu_mat[i, :] = mu_i
# noise variance for this stimulus (per cell)
residuals = arr - mu_i # shape (R_i, n_cells)
noise_accum[i, :] = (residuals**2).sum(axis=0) / Ri # (1/R_i)*sum_r(...)
# Grand mean across stimuli for each cell
mu_bar = mu_mat.mean(axis=0) # shape (n_cells,)
# Compute signal variance: Var_i( mu_i )
if mean_center:
mu_centered = mu_mat - mu_bar # shape (n_stim, n_cells)
signal_var = (mu_centered**2).sum(axis=0) / n_stim # (1/n_stim)*sum_i (mu_i - mu_bar)^2
else:
signal_var = (mu_mat**2).sum(axis=0) / n_stim # (1/n_stim)*sum_i (mu_i)^2
# Compute noise variance: average of noise_accum across stimuli
noise_var = noise_accum.mean(axis=0) # (1/n_stim) * sum_i [ (1/R_i)*sum_r (x - mu_i)^2 ]
total_var = signal_var + noise_var
# Compute fraction and SNR
fraction_of_stimulus_variance = n.zeros_like(signal_var)
stim_to_noise_ratio = n.zeros_like(signal_var)
# Avoid division by zero
nonzero_mask = total_var > 0
fraction_of_stimulus_variance[nonzero_mask] = signal_var[nonzero_mask] / total_var[nonzero_mask]
# For cells with zero total variance, fraction remains zero
nonzero_noise = noise_var > 0
stim_to_noise_ratio[nonzero_noise] = signal_var[nonzero_noise] / noise_var[nonzero_noise]
# For cells with zero noise variance, SNR is set to zero by default
return fraction_of_stimulus_variance, stim_to_noise_ratio
def compute_signal_related_variance_ragged_per_stim(resp, mean_center=True):
"""
Compute the fraction of signal-related variance (and SNR) for each cell
given ragged repeats per stimulus, and also per-stimulus fraction of
stimulus-related variance for each neuron.
Args:
resp (list of arrays): A list of length n_stimuli. Each element resp[i]
is an array of shape (R_i, n_cells), where R_i
is the number of repeats for stimulus i (can vary
across stimuli).
mean_center (bool): Whether to subtract the grand mean of stimulus means
before computing signal variance.
Returns:
fraction_of_stimulus_variance (ndarray): shape (n_cells,), values in [0, 1].
stim_to_noise_ratio (ndarray): shape (n_cells,).
fraction_per_stim (ndarray): shape (n_stimuli, n_cells), where each element
is the fraction of variance for that stimulus
and cell attributed to the “signal” (the squared
deviation of the stimulus mean from the grand mean)
vs the total (signal + noise for that stimulus).
"""
n_stim = len(resp)
# Ensure all stimuli have 2D array (R_i, n_cells) and consistent n_cells
processed = []
n_cells = None
for i, arr in enumerate(resp):
arr = n.asarray(arr) # shape (R_i, n_cells)
if arr.ndim != 2:
raise ValueError(f"Stimulus {i} data must be 2D, got shape {arr.shape}")
Ri, nc = arr.shape
if n_cells is None:
n_cells = nc
elif nc != n_cells:
raise ValueError(f"All stimuli must have the same number of cells; stimulus {i} has {nc}, expected {n_cells}")
processed.append(arr)
# Compute per-stimulus means (mu_i) and per-stimulus noise variances
mu_mat = n.zeros((n_stim, n_cells), dtype=float)
noise_accum = n.zeros((n_stim, n_cells), dtype=float)
for i, arr in enumerate(processed):
Ri = arr.shape[0]
# mean across repeats for each cell
mu_i = arr.mean(axis=0) # shape (n_cells,)
mu_mat[i, :] = mu_i
# noise variance for this stimulus (per cell)
residuals = arr - mu_i # shape (R_i, n_cells)
noise_accum[i, :] = (residuals**2).sum(axis=0) / Ri # (1/R_i)*sum_r(...)
# Grand mean across stimuli for each cell
mu_bar = mu_mat.mean(axis=0) # shape (n_cells,)
# Compute per-stimulus "signal" numerator: (mu_i - mu_bar)^2 (if mean_center),
# else mu_i^2
if mean_center:
signal_per_stim = (mu_mat - mu_bar) ** 2 # shape: (n_stim, n_cells)
else:
signal_per_stim = mu_mat**2
# Fraction per stimulus per cell: signal_per_stim / (signal_per_stim + noise_accum)
fraction_per_stim = n.zeros_like(signal_per_stim)
total_per_stim = signal_per_stim + noise_accum
nonzero_mask_stim = total_per_stim > 0
fraction_per_stim[nonzero_mask_stim] = signal_per_stim[nonzero_mask_stim] / total_per_stim[nonzero_mask_stim]
# If total_per_stim == 0, fraction remains zero
# Now aggregate across stimuli to get overall signal_var and noise_var per cell
# signal_var = (1/n_stim) * sum_i signal_per_stim[i]
signal_var = signal_per_stim.mean(axis=0) # shape: (n_cells,)
# noise_var = (1/n_stim) * sum_i noise_accum[i]
noise_var = noise_accum.mean(axis=0) # shape: (n_cells,)
total_var = signal_var + noise_var
fraction_of_stimulus_variance = n.zeros_like(signal_var)
stim_to_noise_ratio = n.zeros_like(signal_var)
nonzero_mask = total_var > 0
fraction_of_stimulus_variance[nonzero_mask] = signal_var[nonzero_mask] / total_var[nonzero_mask]
nonzero_noise = noise_var > 0
stim_to_noise_ratio[nonzero_noise] = signal_var[nonzero_noise] / noise_var[nonzero_noise]
# fraction_per_stim[i, c] represents the fraction of variance for stimulus i
# and cell c that is attributed to the signal (i.e., the mean response of that
# cell to the stimulus) versus the total variance (signal + noise).
# Let:
# x_{i,r,c} = response of cell c to stimulus i on repeat r
# R_i = number of repeats for stimulus i
# μ_{i,c} = (1 / R_i) * sum_r x_{i,r,c} # mean response to stim i
# μ̄_c = (1 / n_stim) * sum_i μ_{i,c} # grand mean across stimuli
# σ²_noise_{i,c} = (1 / R_i) * sum_r (x_{i,r,c} - μ_{i,c})² # within-stimulus variance
# Then:
# If mean_center is True:
# signal_var_{i,c} = (μ_{i,c} - μ̄_c)²
# fraction_per_stim[i, c] = signal_var_{i,c} / (signal_var_{i,c} + σ²_noise_{i,c})
#
# If mean_center is False:
# signal_var_{i,c} = μ_{i,c}²
# fraction_per_stim[i, c] = μ_{i,c}² / (μ_{i,c}² + σ²_noise_{i,c})
return fraction_of_stimulus_variance, stim_to_noise_ratio, fraction_per_stim
def compute_signal_related_variance(resp_a, resp_b, mean_center=True, exclude_nan=True):
"""
compute the fraction of signal-related variance for each neuron,
as per Stringer et al Nature 2019. Cross-validated by splitting
responses into two halves. Note, this only is "correct" if resp_a
and resp_b are *not* averages of many trials.
Args:
resp_a (ndarray): n_stimuli, n_cells
resp_b (ndarray): n_stimuli, n_cells
Returns:
fraction_of_stimulus_variance: 0-1, 0 is non-stimulus-caring, 1 is only-stimulus-caring neurons
stim_to_noise_ratio: ratio of the stim-related variance to all other variance
"""
if len(resp_a.shape) > 2:
# if the stimulus is multi-dimensional, flatten across all stimuli
resp_a = resp_a.reshape(-1, resp_a.shape[-1])
resp_b = resp_b.reshape(-1, resp_b.shape[-1])
ns, nc = resp_a.shape
if exclude_nan:
# if any stimulus has nan responses, exclude it from both resp_a and b
nan_mask = n.any(n.isnan(resp_a), axis=1) | n.any(n.isnan(resp_b), axis=1)
resp_a = resp_a[~nan_mask]
resp_b = resp_b[~nan_mask]
if resp_a.shape[0] < 2:
print("Not enough valid stimuli to compute signal-related variance.")
return n.zeros(nc), n.zeros(nc)
if mean_center:
# mean-center the activity of each cell
resp_a = resp_a - resp_a.mean(axis=0)
resp_b = resp_b - resp_b.mean(axis=0)
# compute the cross-trial stimulus covariance of each cell
# dot-product each cell's (n_stim, ) vector from one half
# with its own (n_stim, ) vector on the other half
covariance = (resp_a * resp_b).sum(axis=0) / ns
# compute the variance of each cell across both halves
resp_a_variance = (resp_a**2).sum(axis=0) / ns
resp_b_variance = (resp_b**2).sum(axis=0) / ns
total_variance = (resp_a_variance + resp_b_variance) / 2
# compute the fraction of the total variance that is
# captured in the covariance
fraction_of_stimulus_variance = covariance / total_variance
# if you want, you can compute SNR as well:
stim_to_noise_ratio = fraction_of_stimulus_variance / (1 - fraction_of_stimulus_variance)
return fraction_of_stimulus_variance, stim_to_noise_ratio
def covariance_matrix(resp1, resp2, mean_subtract=False):
# resp1, resp2: n_samples x n_features
# returns: covmat: n_features x n_features
ns, nf = resp1.shape
if mean_subtract:
resp1 -= resp1.mean(axis=0)
resp2 -= resp2.mean(axis=0)
covmat = resp1.T @ resp2 / (ns - 1)
return covmat
def response_cov(x, y):
# x: n_stimuli, n_features
# y: n_stimuli, n_features
return ((x - x.mean(axis=0)) * (y - y.mean(axis=0))).mean(axis=0)
def proj(resp, vecs, subtract_mean=False):
# resp: n_stimuli x n_neurons
# vecs: n_vecs x n_neurons
# returns proj: n_stimuli x n_vecs
if subtract_mean:
respx = resp - resp.mean(axis=0)
else:
respx = resp
return respx @ vecs.T
# https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6758222/
# Ringach et al
def circular_variance(angles, responses):
"""
Compute the preferred orientation and circular variance of cells
as per Ringach et al. 2002
Args:
angles (ndarray): Angles used in experiment, in degrees
responses (ndarray): (n_angles, n_cells) responses of all cells to all angles
Returns:
preferred_angles: 0-180 degrees, favorite angle of each cell
circular_variance: 0 is very selective, 1 is not selective at all
"""
# responses should be of shape n_angles, n_cells
# angles is of shape n_angles IN DEGREES
angles_radians = n.deg2rad(angles)[:, n.newaxis]
numerator = (responses * n.exp(angles_radians * 2j)).sum(axis=0)
denominator = responses.sum(axis=0)
resultant = numerator / denominator
circular_variance = 1 - n.abs(resultant)
preferred_angles = n.rad2deg(n.angle(resultant))
preferred_angles = preferred_angles / 2 + 90
preferred_angles = n.mod(preferred_angles + 90, 180)
return preferred_angles, circular_variance
def fix_overflow(data, n_bytes=4):
exp = n_bytes * 8
max = 2**exp
thresh = 2 ** (exp - 1)
data[data > thresh] -= max
return data
def project(activity, vector):
vector_norm = vector / n.linalg.norm(vector)
activity_norm = n.linalg.norm(activity, axis=0)
proj = (activity.T @ vector_norm) / activity_norm
return proj
def dog_filt(vector, fwhm_1, fwhm_2, axis=-1):
"""
difference of gaussians filter, as implemented by Nguyen et al 2023
Args:
vector (ndarray): timeseries to filter, ndim
fwhm_1 (float): fwhm width of the first gaussian
fwhm_2 (float): fwhm width of the second gaussian
axis (int, optional): axis to filter over. Defaults to -1.
Returns:
filtered_vec: same size as input vector
"""
sigma_1 = fwhm_1 / (2 * n.sqrt(2 * n.log(2)))
sigma_2 = fwhm_2 / (2 * n.sqrt(2 * n.log(2)))
vec1 = gaussian_filter1d(vector, sigma_1, axis=axis)
vec2 = gaussian_filter1d(vector, sigma_2, axis=axis)
return vec1 - vec2
def bin2d(im, bin_size):
if type(bin_size) is tuple:
im = bin1d(bin1d(im, bin_size[0], axis=0), bin_size[1], axis=1)
elif bin_size is not None:
im = bin1d(bin1d(im, bin_size, axis=0), bin_size, axis=1)
return im
def bin1d(X, bin_size, axis=0):
# From rastermap! https://github.com/MouseLand/rastermap/blob/main/rastermap/utils.py
"""mean bin over axis of data with bin bin_size"""
if bin_size > 0:
size = list(X.shape)
Xb = X.swapaxes(0, axis)
Xb = n.nanmean(
Xb[: size[axis] // bin_size * bin_size].reshape((size[axis] // bin_size, bin_size, -1)),
axis=1,
)
Xb = Xb.swapaxes(axis, 0)
size[axis] = Xb.shape[axis]
Xb = Xb.reshape(size)
return Xb
else:
return X
def gaussian_rbf(scale, distance):
return n.exp(-((distance / scale) ** 2))
def exp_kernel(scale, distance):
return n.exp(-n.abs(distance) / scale)
def sample_generalized_normal(beta, size, loc=0, scale=1, seed=None):
"""
Sample from a generalized normal distribution.
beta = 1 is laplace
beta = 2 is normal
"""
rng = n.random.default_rng(seed)
return gennorm.rvs(beta, loc=loc, scale=scale, size=size, random_state=rng)
def matern_kernel_nd(x, scale, nu=0.5, D=1, n=n):
"""
Isotropic Matérn kernel k(r) where r = ||x|| in R^D.
Parameters
----------
x : array_like, shape (..., D) or (...,)
Spatial differences. If D>1, pass vectors in the last axis.
scale : positive float, length‐scale ℓ
nu : smoothness ν; ν=0.5 → exponential, ν→∞ → Gaussian
D : ambient spatial dimension (not used in k(r) itself, but kept for API)
n : numpy or torch module (must provide exp, sqrt, abs, exp, linalg.norm,
and, for the general ν, either scipy.special.kv/γ or torch.special.kv/lgamma)
"""
assert n is not None, "pass n=np or n=torch"
x = n.asarray(x)
# radial distance
if x.ndim > 0 and x.shape[-1] == D:
r = n.linalg.norm(x, axis=-1)
else:
r = n.abs(x)
# ν = 0.5 → exponential(ℓ): exp(−r/ℓ)
if nu == 0.5:
return n.exp(-r / scale)
# ν = ∞ → Gaussian(ℓ): exp(−½ (r/ℓ)²)