-
Notifications
You must be signed in to change notification settings - Fork 1
/
unit_lfp_comparison.py
1967 lines (1742 loc) · 92.9 KB
/
unit_lfp_comparison.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
"""
unit_lfp_comparison.py
Author
------
Daniel Schonhaut
Computational Memory Lab
University of Pennsylvania
daniel.schonhaut@gmail.com
Description
-----------
Compare unit spike times to LFP oscillations.
Last Edited
-----------
5/2/22
"""
import sys
import os.path as op
from glob import glob
# import mkl
# mkl.set_num_threads(1)
import numpy as np
import pandas as pd
from statsmodels.stats.api import multipletests
import astropy.stats.circstats as circstats
sys.path.append('/home1/dscho/code/general')
import data_io as dio
from helper_funcs import Timer, str_replace
sys.path.append('/home1/dscho/code/projects')
from time_cells import spike_preproc, events_proc, time_bin_analysis
def unit_to_lfp_phase_locking_gold_view(unit,
freqs=np.arange(1, 31),
n_rois=8,
n_samp_iter=10,
n_perm=1000,
alpha=0.05,
data_dir='/home1/dscho/projects/unit_activity_and_hpc_theta/data2/goldmine/nav',
output_dir=None,
save_output=True,
overwrite=False,
verbose=True):
"""Calculate oscillatory phase-locking gold view events.
Compare golds that were later dug or not dug, respectively.
Parameters
----------
unit : dict or series
Contains the spike times vector and identifying info for a unit.
freqs : array
Frequencies at which spike-phase relations are analyzed.
n_rois : int
Number of meta-regions to assign for categorization.
n_perm : int
Number of permutations drawn to construst the null distribution.
For each permutation, spike times are circ-shifted at random
within each event, and phase-locking values at each frequency
are recalculcated across events.
alpha : float
Defines the significance threshold for the phase-locking
empirical p-value.
data_dir : str
Filepath to the location where saved inputs are stored.
output_dir : str | None
Filepath to the location where the output file is saved.
save_output : bool
Output is saved only if True.
overwrite : bool
If False and saved output already exists, it is simply returned
at the top of this function. Otherwise phase-locking is
calculated and, if save_output is True, any existing output file
is overwritten.
verbose : bool
If True, some info is printed to the standard output.
Returns
-------
pl_mrls : dataframe
Each row corresponds to one unit -> LFPs from one microwire
bundle.
"""
timer = Timer()
# Load the output file if it exists.
output_b = '{}-{}-{}.pkl'.format(unit['subj_sess'], unit['chan'], unit['unit'])
if output_dir is None:
output_dir = op.join(data_dir, 'phase_locking', 'osc2mask')
output_f = op.join(output_dir, output_b)
if op.exists(output_f) and not overwrite:
if verbose:
print('Loading saved output: {}'.format(output_f))
return dio.open_pickle(output_f)
# Hard-coded params.
expmt = 'goldmine'
game_states = ['Encoding']
gold_keys = ['dug', 'not_dug']
# Get a list of LFP ROIs to process.
mont = spike_preproc.get_montage(unit['subj_sess'])
roi_map = spike_preproc.roi_mapping(n=n_rois)
hpc_rois = ['AH', 'MH', 'PH']
lfp_hemrois = np.unique([unit['hemroi']] + [hemroi for hemroi in mont.keys()
if hemroi[1:] in hpc_rois])
pl_mrls = []
for lfp_hemroi in lfp_hemrois:
# ------------------------------------
# Data loading
# Determine which regions we're looking at.
lfp_roi_gen = roi_map[lfp_hemroi[1:]]
if unit['roi_gen'] == 'HPC':
if lfp_roi_gen == 'HPC':
if unit['hemroi'] == lfp_hemroi:
edge = 'hpc-local'
else:
edge = 'hpc-hpc'
else:
edge = 'hpc-ctx'
else:
if lfp_roi_gen != 'HPC':
if unit['hemroi'] == lfp_hemroi:
edge = 'ctx-local'
else:
edge = 'ctx-ctx'
else:
edge = 'ctx-hpc'
same_hem = unit['hem'] == lfp_hemroi[0]
same_roi_gen = unit['roi_gen'] == lfp_roi_gen
# Load event_times.
event_times = load_event_times(unit['subj_sess'],
expmt=expmt,
game_states=game_states,
data_dir=data_dir)
# Calculate spike times relative to the start of each event.
event_time_spikes = load_event_time_spikes(event_times,
unit['spike_times'])
# Load phase values for each event.
basename_lfp = '{}-{}.pkl'.format(unit['subj_sess'], lfp_hemroi)
phase = dio.open_pickle(op.join(data_dir, 'spectral', 'phase', basename_lfp))
if (phase.buffer > 0) & (not phase.clip_buffer):
phase = phase.loc[:, :, :, phase.buffer:phase.time.size-phase.buffer-1]
phase.attrs['clip_buffer'] = True
lfp_chans = [chan for chan in phase.chan.values if chan not in [unit['chan']]]
if unit['chan'] in phase.chan:
phase = phase.loc[{'chan': lfp_chans}]
if not np.array_equal(phase.freq.values, freqs):
phase = phase.loc[{'freq': [freq for freq in phase.freq.values if freq in freqs]}]
if np.nanmax(phase.values) > np.pi:
phase -= np.pi # convert values back to -π to π, with -π being the trough
# Load the P-episode mask for each event.
osc_mask = dio.open_pickle(op.join(data_dir, 'p_episode', basename_lfp))
if (osc_mask.buffer > 0) & (not osc_mask.clip_buffer):
osc_mask = osc_mask.loc[:, :, :, osc_mask.buffer:osc_mask.time.size-osc_mask.buffer-1]
osc_mask.attrs['clip_buffer'] = True
if unit['chan'] in osc_mask.chan:
osc_mask = osc_mask.loc[{'chan': [chan for chan in osc_mask.chan.values
if chan not in [unit['chan']]]}]
if not np.array_equal(osc_mask.freq.values, freqs):
osc_mask = osc_mask.loc[{'freq': [freq for freq in osc_mask.freq.values
if freq in freqs]}]
osc_mask = osc_mask.sel(gameState='Encoding') # [trial, chan, freq, time]
# Load the gold-view mask for each event.
basename = '{}-gold_view_mask.pkl'.format(unit['subj_sess'])
gold_mask = dio.open_pickle(op.join(data_dir, 'events', basename)) # [gold_key][trial, time]
# Combine gold view and oscillatory masks.
osc_gold_mask = {key: (gold_mask[key][:, None, None, :] & osc_mask.values)
for key in gold_keys} # [gold_key][trial, chan, freq, time]
# Calculate P-episode at each frequency, across channels and events.
peps = {key: 100 * np.nanmean(osc_gold_mask[key], axis=(0, 1, 3))
for key in gold_keys}
max_pep = {key: np.nanmax(peps[key]) for key in gold_keys}
max_pep_freq = {key: np.nanargmax(peps[key]) for key in gold_keys}
# Get gold view spike phases at each freq. across events,
# for later dug and not dug golds.
event_dur = phase.time.size
spike_phases = {
key: np.ma.concatenate(
event_time_spikes.apply(
lambda x: get_spike_phases(x['spike_times'],
phase.values[x['event_idx'], :, :, :],
mask=np.invert(osc_gold_mask[key][x['event_idx'], :, :, :]),
event_dur=event_dur,
circshift=False),
axis=1).tolist(), axis=-1)
for key in gold_keys} # [gold_key][chan, freq, spike]
# Draw spikes from dug and not_dug gold view times.
# Calculate mean resultant lengths for each channel and frequency.
n_freq = phase.freq.size
n_chan = phase.chan.size
mrls = {key: np.nanmean([[[circstats.circmoment(np.random.choice(
spike_phases[key][iChan, iFreq, :].compressed(),
size=n_spike_samp, replace=True))[1]
for iFreq in range(n_freq)]
for iChan in range(n_chan)]
for ii in range(n_samp_iter)],
axis=(0, 1)).astype(np.float32) # [freq]
for key in gold_keys}
for key in gold_keys:
# ------------------------------------
# Calculate real phase-locking
# Get a masked array of spike phases, across events, during active
# oscillations at each channel and frequency.
spike_phases = np.ma.concatenate(event_time_spikes.apply(
lambda x: get_spike_phases(x['spike_times'],
phase.values[x['event_idx'], :, :, :],
mask=np.invert(osc_gold_mask[key].values[x['event_idx'], :, :, :]),
event_dur=event_dur,
circshift=False),
axis=1).tolist(), axis=-1) # chan x freq x spike
# Calculate mean resultant lengths for each channel and frequency.
mrls = np.nanmean([[circstats.circmoment(spike_phases[iChan, iFreq, :].compressed())[1]
for iFreq in range(spike_phases.shape[1])]
for iChan in range(spike_phases.shape[0])], axis=0).astype(np.float32) # (freq,)
# Log how many spikes were counted per frequency,
# taking the mean across channels.
n_spikes_mask = np.nanmean([[spike_phases[iChan, iFreq, :].flatten().compressed().size
for iFreq in range(spike_phases.shape[1])]
for iChan in range(spike_phases.shape[0])], axis=0).astype(np.float32) # (freq,)
# Get the preferred phase at each frequency, across channels.
pref_phases = np.array([circstats.circmoment(spike_phases[:, iFreq, :].flatten().compressed())[0]
for iFreq in range(spike_phases.shape[1])]).astype(np.float32) # (freq,)
# ------------------------------------
# Calculate null phase-locking
mrls_null = []
n_spikes_mask_null = []
for iPerm in range(n_perm):
# Get a masked array of spike phases, across events, during active
# oscillations at each channel and frequency.
_spike_phases_null = np.ma.concatenate(event_time_spikes.apply(
lambda x: get_spike_phases(x['spike_times'],
phase[x['event_idx'], :, :, :],
mask=np.invert(osc_mask[key][x['event_idx'], :, :, :]),
event_dur=event_dur,
circshift=True),
axis=1).tolist(), axis=-1) # chan x freq x spike
# Calculate mean resultant lengths for each channel and frequency.
_mrls_null = np.nanmean([[circstats.circmoment(_spike_phases_null[iChan, iFreq, :].compressed())[1]
for iFreq in range(_spike_phases_null.shape[1])]
for iChan in range(_spike_phases_null.shape[0])], axis=0).astype(np.float32)
mrls_null.append(_mrls_null.tolist())
_n_spikes_mask_null = np.nanmean([[_spike_phases_null[iChan, iFreq, :].flatten().compressed().size
for iFreq in range(_spike_phases_null.shape[1])]
for iChan in range(_spike_phases_null.shape[0])], axis=0).astype(np.float32)
n_spikes_mask_null.append(_n_spikes_mask_null)
mrls_null = np.array(mrls_null) # (perm, freq)
n_spikes_mask_null = np.array(n_spikes_mask_null) # (perm, freq)
# ------------------------------------
# Statistics
# Z-score MRLs against the null distribution,
# and calculate empirical P-values.
mean_mrls_null = np.nanmean(mrls_null, axis=0)
std_mrls_null = np.nanstd(mrls_null, axis=0)
z_mrls = (mrls - mean_mrls_null) / std_mrls_null # (freq,)
z_mrls_null = (mrls_null - mean_mrls_null[None, :]) / std_mrls_null[None, :] # (perm, freq)
max_z_mrl = np.nanmax(z_mrls)
max_z_mrl_freq = freqs[np.nanargmax(z_mrls)]
pval = (1 + np.nansum(np.nanmax(z_mrls_null, axis=1) >= max_z_mrl)) / (1 + n_perm)
sig = pval < alpha
mean_n_spikes_mask_null = np.nanmean(n_spikes_mask_null, axis=0)
std_n_spikes_mask_null = np.nanstd(n_spikes_mask_null, axis=0)
z_n_spikes_mask = (n_spikes_mask - mean_n_spikes_mask_null) / std_n_spikes_mask_null
# ------------------------------------
# Add results to dataframe.
pl_mrls.append([unit['subj'],
unit['subj_sess'],
'{}-{}'.format(unit['chan'], unit['unit']),
unit['hemroi'],
unit['roi_gen'],
unit['n_spikes'],
unit['fr'],
lfp_hemroi,
lfp_roi_gen,
lfp_chans,
edge,
same_hem,
same_roi_gen,
key,
peps,
max_pep,
max_pep_freq,
n_spikes_mask,
n_spikes_mask_null,
mrls,
mrls_null,
pref_phases,
z_n_spikes_mask,
z_mrls,
max_z_mrl,
max_z_mrl_freq,
pval,
sig])
# Create the output dataframe.
cols = ['subj', 'subj_sess', 'unit', 'unit_hemroi', 'unit_roi_gen', 'n_spikes', 'fr',
'lfp_hemroi', 'lfp_roi_gen', 'lfp_chans', 'edge', 'same_hem', 'same_roi_gen',
'mask', 'peps', 'max_pep', 'max_pep_freq', 'n_spikes_mask', 'n_spikes_mask_null',
'mrls', 'mrls_null', 'pref_phases',
'z_n_spikes_mask', 'z_mrls', 'max_z_mrl', 'max_z_mrl_freq', 'pval', 'sig']
pl_mrls = pd.DataFrame(pl_mrls, columns=cols)
# Save the output.
if save_output:
dio.save_pickle(pl_mrls, output_f, verbose)
if verbose:
print('pl_mrls: {}'.format(pl_mrls.shape))
print(timer)
return pl_mrls
def unit_to_lfp_phase_locking_goldmine_game_states(
unit,
n_rois=8,
keep_same_hem=[True, False],
keep_edges=['hpc-local', 'hpc-hpc', 'hpc-ctx', 'ctx-local', 'ctx-hpc', 'ctx-ctx'],
exclude_gen_rois=[],
mask_phase=True,
match_spikes=True,
n_perm=1000,
alpha=0.05,
data_dir='/home1/dscho/projects/unit_activity_and_hpc_theta/data2/goldmine',
output_dir='/home1/dscho/projects/unit_activity_and_hpc_theta/data2/goldmine/game_states/phase_locking',
save_output=True,
overwrite=True,
verbose=True
):
"""Calculate unit's phase-locking to LFP oscillations
across all 4 Goldmine game states (Delay1, Encoding, Delay2, Retrieval)
and in each state, separately (matched for spikes within each
channel, frequency pair).
Parameters
----------
unit : dict or series
Contains the spike times vector and identifying info for a unit.
expmt : str, 'goldmine' | 'ycab'
Indicates which dataset we're working with.
game_states : array
Event intervals to include in the analysis.
freqs : array
Frequencies at which spike-phase relations are analyzed.
n_rois : int
Number of meta-regions to assign for categorization.
keep_same_hem : list[bool]
Which hemispheric connections to process. Default is to run both
ipsilateral and contralateral.
keep_edges : list[str]
Define the edges to be processed. Default is to analyze all
electrode pairs.
exclude_gen_rois : list[str]
Exclude LFP gen_roi regions in this list.
match_spikes : bool
If True, will find the minimum number of spikes across game
states at each channel and frequency, and subsample that many
spikes (without replacement) from each mask.
n_perm : int
Number of permutations drawn to construst the null distribution.
For each permutation, spike times are circ-shifted at random
within each event, and phase-locking values at each frequency
are recalculcated across events.
alpha : float
Defines the significance threshold for the phase-locking
empirical p-value.
data_dir : str
Filepath to the location where saved inputs are stored.
output_dir : str | None
Filepath to the location where the output file is saved.
save_output : bool
Output is saved only if True.
overwrite : bool
If False and saved output already exists, it is simply returned
at the top of this function. Otherwise phase-locking is
calculated and, if save_output is True, any existing output file
is overwritten.
verbose : bool
If True, some info is printed to the standard output.
Returns
-------
pl_mrls : dataframe
Each row corresponds to one unit -> LFPs from one microwire
bundle.
"""
timer = Timer()
expmt = 'goldmine'
game_states = ['Delay1', 'Encoding', 'Delay2', 'Retrieval']
# Load the output file if it exists.
output_b = '{}-{}-{}.pkl'.format(unit['subj_sess'], unit['chan'], unit['unit'])
if output_dir is None:
output_dir = op.join(data_dir, 'game_states', 'phase_locking')
output_f = op.join(output_dir, output_b)
if op.exists(output_f) and not overwrite:
if verbose:
print('Loading saved output: {}'.format(output_f))
return dio.open_pickle(output_f)
# Get a list of LFP ROIs to process.
mont = spike_preproc.get_montage(unit['subj_sess'])
roi_map = spike_preproc.roi_mapping(n=n_rois)
process_pairs = _get_process_pairs(mont,
unit['hemroi'],
keep_same_hem,
keep_edges,
exclude_gen_rois,
roi_map)
pl_mrls = []
for (unit_hemroi, lfp_hemroi) in process_pairs:
# ------------------------------------
# Data loading
# Determine which regions we're looking at.
same_hem = (unit_hemroi[0] == lfp_hemroi[0])
edge = _get_edge(unit_hemroi, lfp_hemroi)
unit_roi_gen = roi_map[unit_hemroi[1:]]
lfp_roi_gen = roi_map[lfp_hemroi[1:]]
same_roi_gen = (unit_roi_gen == lfp_roi_gen)
event_times = {}
event_time_spikes = {}
phase = {}
osc_mask = {}
for game_state in game_states:
# Load event_times.
event_times[game_state] = load_event_times(unit['subj_sess'],
expmt=expmt,
game_states=[game_state])
# Calculate spike times relative to the start of each event.
event_time_spikes[game_state] = load_event_time_spikes(event_times[game_state],
unit['spike_times'])
delay_and_nav = np.all((np.any(np.isin(game_states, ['Delay1', 'Delay2'])),
np.any(np.isin(game_states, ['Encoding', 'Retrieval']))))
# Load phase values for each event.
_data_dir = op.join(data_dir, 'delay' if 'Delay' in game_state else 'nav')
basename_lfp = '{}-{}.pkl'.format(unit['subj_sess'], lfp_hemroi)
phase[game_state] = dio.open_pickle(op.join(_data_dir, 'spectral', 'phase', basename_lfp))
phase[game_state] = phase[game_state].sel(gameState=game_state)
if (phase[game_state].buffer > 0) & (not phase[game_state].clip_buffer):
phase[game_state] = phase[game_state].loc[:, :, :, phase[game_state].buffer:phase[game_state].time.size-phase[game_state].buffer-1]
phase[game_state].attrs['clip_buffer'] = True
lfp_chans = [chan for chan in phase[game_state].chan.values
if chan not in [unit['chan']]]
if unit['chan'] in phase[game_state].chan:
phase[game_state] = phase[game_state].loc[{'chan': lfp_chans}]
freqs = phase[game_state].freq.values
if not np.array_equal(phase[game_state].freq.values, freqs):
phase[game_state] = phase[game_state].loc[{'freq': [freq for freq in phase[game_state].freq.values
if freq in freqs]}]
if np.nanmax(phase[game_state].values) > np.pi:
phase[game_state] -= np.pi # convert values back to -π to π, with -π being the trough.
# Load the P-episode mask for each event.
osc_mask[game_state] = dio.open_pickle(op.join(_data_dir, 'p_episode', basename_lfp))
osc_mask[game_state] = osc_mask[game_state].sel(gameState=game_state)
if (osc_mask[game_state].buffer > 0) & (not osc_mask[game_state].clip_buffer):
osc_mask[game_state] = osc_mask[game_state].loc[:, :, :, osc_mask[game_state].buffer:osc_mask[game_state].time.size-osc_mask[game_state].buffer-1]
osc_mask[game_state].attrs['clip_buffer'] = True
if unit['chan'] in osc_mask[game_state].chan:
osc_mask[game_state] = osc_mask[game_state].loc[{'chan': lfp_chans}]
if not np.array_equal(osc_mask[game_state].freq.values, freqs):
osc_mask[game_state] = osc_mask[game_state].loc[{'freq': [freq for freq in osc_mask[game_state].freq.values
if freq in freqs]}]
# Ensure that phase, oscillation mask, and spike_times are all in the same event order.
assert np.array_equal(phase[game_state].trial.values, osc_mask[game_state].trial.values)
assert np.array_equal(phase[game_state].trial.values, event_time_spikes[game_state]['trial'].values)
# Remove channels that aren't common to all game states.
keep_chans = list(set(phase['Delay1'].chan.values) & set(phase['Encoding'].chan.values))
for game_state in game_states:
phase[game_state] = phase[game_state].loc[{'chan': keep_chans}]
osc_mask[game_state] = osc_mask[game_state].loc[{'chan': keep_chans}]
assert np.array_equal(phase['Delay2'].chan.values, osc_mask['Retrieval'].chan.values)
# Calculate P-episode at each frequency, across channels and events.
peps = {}
max_pep = {}
max_pep_freq = {}
for game_state in game_states:
peps[game_state] = 100 * osc_mask[game_state].mean(dim=('trial', 'chan', 'time')).values
max_pep[game_state] = peps[game_state].max()
max_pep_freq[game_state] = freqs[peps[game_state].argmax()]
for key in ['all', 'all_matched']:
peps[key] = np.mean([peps['Delay1'],
peps['Encoding'], peps['Encoding'], peps['Encoding'],
peps['Delay2'],
peps['Retrieval'], peps['Retrieval'], peps['Retrieval']],
axis=0)
max_pep[key] = peps[key].max()
max_pep_freq[key] = peps[key].argmax()
# ------------------------------------
# Calculate real phase-locking
n_chan = phase['Delay1'].chan.size
n_freq = phase['Delay1'].freq.size
mask_keys = ['all', 'all_matched'] + game_states
# Get a masked array of spike phases, across events, during active
# oscillations at each channel and frequency.
spike_phases = {}
for game_state in game_states:
event_dur = phase[game_state].time.size
if mask_phase:
spike_phases[game_state] = np.ma.concatenate(event_time_spikes[game_state].apply(
lambda x: get_spike_phases(x['spike_times'],
phase[game_state].values[x['event_idx'], :, :, :],
mask=np.invert(osc_mask[game_state].values[x['event_idx'], :, :, :]),
event_dur=event_dur,
circshift=False),
axis=1).tolist(), axis=-1) # chan x freq x spike
else:
spike_phases[game_state] = np.ma.concatenate(event_time_spikes[game_state].apply(
lambda x: get_spike_phases(x['spike_times'],
phase[game_state].values[x['event_idx'], :, :, :],
mask=None,
event_dur=event_dur,
circshift=False),
axis=1).tolist(), axis=-1) # chan x freq x spike
# Calculate mean resultant lengths for each channel and frequency.
mrls = {}
n_spikes_mask = {}
pref_phases = {}
mrls['all'] = np.nanmean([[
circstats.circmoment(np.concatenate([spike_phases[game_state][iChan, iFreq, :].compressed()
for game_state in game_states]))[1]
for iFreq in range(n_freq)]
for iChan in range(n_chan)],
axis=0).astype(np.float32) # (freq,)
# Log how many spikes were counted per frequency,
# taking the mean across channels.
n_spikes_mask['all'] = np.nanmean([[
np.concatenate([spike_phases[game_state][iChan, iFreq, :].compressed()
for game_state in game_states]).size
for iFreq in range(n_freq)]
for iChan in range(n_chan)],
axis=0).astype(np.float32) # (freq,)
# Get the preferred phase at each frequency, across channels.
pref_phases['all'] = np.array([
circstats.circmoment(np.concatenate([spike_phases[game_state][:, iFreq, :].flatten().compressed()
for game_state in game_states]))[0]
for iFreq in range(n_freq)]).astype(np.float32) # (freq,)
# Match the number of spikes sampled between game states, at each channel and frequency.
if match_spikes:
n_spikes = np.min([np.count_nonzero(~spike_phases[game_state].mask, axis=2)
for game_state in game_states], axis=0) # (chan, freq)
for game_state in game_states:
spike_phases[game_state].mask = subsample_mask(spike_phases[game_state].mask, size=n_spikes)
# Calculate mean resultant lengths for each channel and frequency.
mrls['all_matched'] = np.nanmean([[
circstats.circmoment(np.concatenate([spike_phases[game_state][iChan, iFreq, :].compressed()
for game_state in game_states]))[1]
for iFreq in range(n_freq)]
for iChan in range(n_chan)],
axis=0).astype(np.float32) # (freq,)
# Log how many spikes were counted per frequency,
# taking the mean across channels.
n_spikes_mask['all_matched'] = np.nanmean([[
np.concatenate([spike_phases[game_state][iChan, iFreq, :].compressed()
for game_state in game_states]).size
for iFreq in range(n_freq)]
for iChan in range(n_chan)],
axis=0).astype(np.float32) # (freq,)
# Get the preferred phase at each frequency, across channels.
pref_phases['all_matched'] = np.array([
circstats.circmoment(np.concatenate([
spike_phases[game_state][:, iFreq, :].flatten().compressed()
for game_state in game_states]))[0]
for iFreq in range(n_freq)]).astype(np.float32) # (freq,)
for game_state in game_states:
# Calculate mean resultant lengths for each channel and frequency.
mrls[game_state] = np.nanmean([[
circstats.circmoment(spike_phases[game_state][iChan, iFreq, :].compressed())[1]
for iFreq in range(spike_phases[game_state].shape[1])]
for iChan in range(spike_phases[game_state].shape[0])],
axis=0).astype(np.float32) # (freq,)
# Log how many spikes were counted per frequency,
# taking the mean across channels.
n_spikes_mask[game_state] = np.nanmean([[spike_phases[game_state][iChan, iFreq, :].flatten().compressed().size
for iFreq in range(spike_phases[game_state].shape[1])]
for iChan in range(spike_phases[game_state].shape[0])], axis=0).astype(np.float32) # (freq,)
# Get the preferred phase at each frequency, across channels.
pref_phases[game_state] = np.array([circstats.circmoment(spike_phases[game_state][:, iFreq, :].flatten().compressed())[0]
for iFreq in range(spike_phases[game_state].shape[1])]).astype(np.float32) # (freq,)
# ------------------------------------
# Calculate null phase-locking
mrls_null = {key: [] for key in mask_keys}
n_spikes_mask_null = {key: [] for key in mask_keys}
for iPerm in range(n_perm):
# Get a masked array of spike phases, across events, during active
# oscillations at each channel and frequency.
_spike_phases_null = {}
for game_state in game_states:
event_dur = phase[game_state].time.size
if mask_phase:
_spike_phases_null[game_state] = np.ma.concatenate(event_time_spikes[game_state].apply(
lambda x: get_spike_phases(x['spike_times'],
phase[game_state].values[x['event_idx'], :, :, :],
mask=np.invert(osc_mask[game_state].values[x['event_idx'], :, :, :]),
event_dur=event_dur,
circshift=True),
axis=1).tolist(), axis=-1) # chan x freq x spike
else:
_spike_phases_null[game_state] = np.ma.concatenate(event_time_spikes[game_state].apply(
lambda x: get_spike_phases(x['spike_times'],
phase[game_state].values[x['event_idx'], :, :, :],
mask=None,
event_dur=event_dur,
circshift=True),
axis=1).tolist(), axis=-1) # chan x freq x spike
# Calculate mean resultant lengths for each channel and frequency.
mrls_null['all'].append(np.nanmean([[
circstats.circmoment(np.concatenate([_spike_phases_null[game_state][iChan, iFreq, :].compressed()
for game_state in game_states]))[1]
for iFreq in range(n_freq)]
for iChan in range(n_chan)],
axis=0).astype(np.float32).tolist()) # (freq,)
# Log how many spikes were counted per frequency,
# taking the mean across channels.
n_spikes_mask_null['all'].append(np.nanmean([[
np.concatenate([_spike_phases_null[game_state][iChan, iFreq, :].compressed()
for game_state in game_states]).size
for iFreq in range(n_freq)]
for iChan in range(n_chan)],
axis=0).astype(np.float32).tolist()) # (freq,)
# Match the number of spikes sampled between game states, at each channel and frequency.
if match_spikes:
n_spikes_null = np.min([np.count_nonzero(~_spike_phases_null[game_state].mask, axis=2)
for game_state in game_states], axis=0) # (chan, freq)
for game_state in game_states:
_spike_phases_null[game_state].mask = subsample_mask(_spike_phases_null[game_state].mask, size=n_spikes_null)
# Calculate mean resultant lengths for each channel and frequency.
mrls_null['all_matched'].append(np.nanmean([[
circstats.circmoment(np.concatenate([_spike_phases_null[game_state][iChan, iFreq, :].compressed()
for game_state in game_states]))[1]
for iFreq in range(n_freq)]
for iChan in range(n_chan)],
axis=0).astype(np.float32).tolist()) # (freq,)
# Log how many spikes were counted per frequency,
# taking the mean across channels.
n_spikes_mask_null['all_matched'].append(np.nanmean([[
np.concatenate([_spike_phases_null[game_state][iChan, iFreq, :].compressed()
for game_state in game_states]).size
for iFreq in range(n_freq)]
for iChan in range(n_chan)],
axis=0).astype(np.float32).tolist()) # (freq,)
for game_state in game_states:
# Calculate mean resultant lengths for each channel and frequency.
mrls_null[game_state].append(np.nanmean([[
circstats.circmoment(_spike_phases_null[game_state][iChan, iFreq, :].compressed())[1]
for iFreq in range(_spike_phases_null[game_state].shape[1])]
for iChan in range(_spike_phases_null[game_state].shape[0])],
axis=0).astype(np.float32).tolist()) # (freq,)
# Log how many spikes were counted per frequency,
# taking the mean across channels.
n_spikes_mask_null[game_state].append(np.nanmean([[
_spike_phases_null[game_state][iChan, iFreq, :].flatten().compressed().size
for iFreq in range(_spike_phases_null[game_state].shape[1])]
for iChan in range(_spike_phases_null[game_state].shape[0])],
axis=0).astype(np.float32).tolist()) # (freq,)
mrls_null = {key: np.array(mrls_null[key]) for key in mrls_null} # (perm, freq)
n_spikes_mask_null = {key: np.array(n_spikes_mask_null[key]) for key in n_spikes_mask_null} # (perm, freq)
# ------------------------------------
# Statistics
# Z-score MRLs against the null distribution,
# and calculate empirical P-values.
mean_mrls_null = {key: np.nanmean(mrls_null[key], axis=0) for key in mask_keys}
std_mrls_null = {key: np.nanstd(mrls_null[key], axis=0) for key in mask_keys}
z_mrls = {key: (mrls[key] - mean_mrls_null[key]) / std_mrls_null[key] # (freq,)
for key in mask_keys}
z_mrls_null = {key: (mrls_null[key] - mean_mrls_null[key][None, :])
/ std_mrls_null[key][None, :] # (perm, freq)
for key in mask_keys}
max_z_mrl = {key: np.nanmax(z_mrls[key]) for key in mask_keys}
max_z_mrl_freq = {key: freqs[np.nanargmax(z_mrls[key])] for key in mask_keys}
pval = {key: (1 + np.nansum(np.nanmax(z_mrls_null[key], axis=1) >= max_z_mrl[key]))
/ (1 + n_perm)
for key in mask_keys}
sig = {key: pval[key] < alpha for key in mask_keys}
mean_n_spikes_mask_null = {key: np.nanmean(n_spikes_mask_null[key], axis=0)
for key in mask_keys}
std_n_spikes_mask_null = {key: np.nanstd(n_spikes_mask_null[key], axis=0)
for key in mask_keys}
z_n_spikes_mask = {key: (n_spikes_mask[key] - mean_n_spikes_mask_null[key])
/ std_n_spikes_mask_null[key]
for key in mask_keys}
# ------------------------------------
# Add results to dataframe.
for key in mask_keys:
pl_mrls.append([
unit['subj'],
unit['subj_sess'],
'{}-{}'.format(unit['chan'], unit['unit']),
unit['hemroi'],
unit['roi_gen'],
unit['n_spikes'],
unit['fr'],
lfp_hemroi,
lfp_roi_gen,
lfp_chans,
edge,
same_hem,
same_roi_gen,
key,
peps[key],
max_pep[key],
max_pep_freq[key],
n_spikes_mask[key],
n_spikes_mask_null[key],
mrls[key],
mrls_null[key],
mean_mrls_null[key].tolist(),
std_mrls_null[key].tolist(),
pref_phases[key],
z_n_spikes_mask[key],
z_mrls[key],
max_z_mrl[key],
max_z_mrl_freq[key],
pval[key],
sig[key]
])
# Create the output dataframe.
cols = ['subj', 'subj_sess', 'unit', 'unit_hemroi', 'unit_roi_gen', 'n_spikes', 'fr',
'lfp_hemroi', 'lfp_roi_gen', 'lfp_chans', 'edge', 'same_hem', 'same_roi_gen',
'mask', 'peps', 'max_pep', 'max_pep_freq', 'n_spikes_mask', 'n_spikes_mask_null',
'mrls', 'mrls_null', 'mean_mrls_null', 'std_mrls_null', 'pref_phases',
'z_n_spikes_mask', 'z_mrls', 'max_z_mrl', 'max_z_mrl_freq', 'pval', 'sig']
pl_mrls = pd.DataFrame(pl_mrls, columns=cols)
# Save the output.
if save_output:
dio.save_pickle(pl_mrls, output_f, verbose)
if verbose:
print('pl_mrls: {}'.format(pl_mrls.shape))
print(timer)
return pl_mrls
def unit_to_lfp_phase_locking_osc2mask(unit,
expmt='goldmine',
game_states=['Encoding', 'Retrieval'],
freqs=np.arange(1, 31),
n_rois=8,
keep_same_hem=[True, False],
keep_edges=['hpc-hpc', 'hpc-ctx', 'ctx-hpc', 'ctx-ctx'],
exclude_gen_rois=[],
match_spikes=False,
n_perm=1000,
alpha=0.05,
data_dir='/home1/dscho/projects/unit_activity_and_hpc_theta/data2/goldmine/nav',
output_dir=None,
save_output=True,
overwrite=False,
verbose=True):
"""Calculate unit's phase-locking to distal LFP oscillations when
local oscillations are present versus absent.
Parameters
----------
unit : dict or series
Contains the spike times vector and identifying info for a unit.
expmt : str, 'goldmine' | 'ycab'
Indicates which dataset we're working with.
game_states : array
Event intervals to include in the analysis.
freqs : array
Frequencies at which spike-phase relations are analyzed.
n_rois : int
Number of meta-regions to assign for categorization.
keep_same_hem : list[bool]
Which hemispheric connections to process. Default is to run both
ipsilateral and contralateral.
keep_edges : list[str]
Define the edges to be processed. Default is to analyze all
electrode pairs.
exclude_gen_rois : list[str]
Exclude LFP gen_roi regions in this list.
match_spikes : bool
If True, will find the minimum number of spikes between
'lfp_and_unit' and 'lfp_not_unit' masks at each channel and
frequency, and subsample that many spikes (without replacement)
from each mask.
n_perm : int
Number of permutations drawn to construst the null distribution.
For each permutation, spike times are circ-shifted at random
within each event, and phase-locking values at each frequency
are recalculcated across events.
alpha : float
Defines the significance threshold for the phase-locking
empirical p-value.
data_dir : str
Filepath to the location where saved inputs are stored.
output_dir : str | None
Filepath to the location where the output file is saved.
save_output : bool
Output is saved only if True.
overwrite : bool
If False and saved output already exists, it is simply returned
at the top of this function. Otherwise phase-locking is
calculated and, if save_output is True, any existing output file
is overwritten.
verbose : bool
If True, some info is printed to the standard output.
Returns
-------
pl_mrls : dataframe
Each row corresponds to one unit -> LFPs from one microwire
bundle.
"""
timer = Timer()
# Load the output file if it exists.
output_b = '{}-{}-{}.pkl'.format(unit['subj_sess'], unit['chan'], unit['unit'])
if output_dir is None:
output_dir = op.join(data_dir, 'phase_locking', 'osc2mask_{}perm'.format(n_perm))
output_f = op.join(output_dir, output_b)
if op.exists(output_f) and not overwrite:
if verbose:
print('Loading saved output: {}'.format(output_f))
return dio.open_pickle(output_f)
# Get a list of LFP ROIs to process.
if expmt == 'goldmine':
mont = spike_preproc.get_montage(unit['subj_sess'])
elif expmt == 'ycab':
subj_df = _get_subj_df()
subj_df['subj_sess'] = subj_df['subj_sess'].apply(
lambda x: str_replace(x, {'env': 'ses', '1a': '1'}))
mont = (subj_df.query("(subj_sess=='{}')".format(unit['subj_sess']))
.groupby(['location'])['chan']
.apply(lambda x: np.array([int(chan) for chan in x])))
roi_map = spike_preproc.roi_mapping(n=n_rois)
process_pairs = _get_process_pairs(mont,
unit['hemroi'],
keep_same_hem,
keep_edges,
exclude_gen_rois,
roi_map)
pl_mrls = []
for (unit_hemroi, lfp_hemroi) in process_pairs:
# ------------------------------------
# Data loading
# Determine which regions we're looking at.
comp_hemroi = None
if unit_hemroi == lfp_hemroi:
for (_unit_hemroi, _lfp_hemroi) in process_pairs:
if roi_map[_lfp_hemroi[1:]] == 'HPC':
comp_hemroi = _lfp_hemroi
break
if comp_hemroi is None:
continue
else:
comp_hemroi = unit['hemroi']
comp_roi_gen = roi_map[comp_hemroi[1:]]
same_hem = (unit_hemroi[0] == lfp_hemroi[0])
edge = _get_edge(unit_hemroi, lfp_hemroi)
unit_roi_gen = roi_map[unit_hemroi[1:]]
lfp_roi_gen = roi_map[lfp_hemroi[1:]]
same_roi_gen = (unit_roi_gen == lfp_roi_gen)
# Load event_times.
event_times = load_event_times(unit['subj_sess'],
expmt=expmt,
game_states=game_states,
data_dir=data_dir)
# Calculate spike times relative to the start of each event.
event_time_spikes = load_event_time_spikes(event_times,
unit['spike_times'])
# Load phase values for each event.
basename_lfp = '{}-{}.pkl'.format(unit['subj_sess'], lfp_hemroi)
phase = dio.open_pickle(op.join(data_dir, 'spectral', 'phase', basename_lfp))
if (phase.buffer > 0) & (not phase.clip_buffer):
phase = phase.loc[:, :, :, phase.buffer:phase.time.size-phase.buffer-1]
phase.attrs['clip_buffer'] = True
lfp_chans = [chan for chan in phase.chan.values if chan not in [unit['chan']]]
if unit['chan'] in phase.chan:
phase = phase.loc[{'chan': lfp_chans}]
if not np.array_equal(phase.freq.values, freqs):
phase = phase.loc[{'freq': [freq for freq in phase.freq.values if freq in freqs]}]
if np.nanmax(phase.values) > np.pi:
phase -= np.pi # convert values back to -π to π, with -π being the trough.
event_dur = phase.time.size
# Load the P-episode mask for each event.
roi_keys = ['comp_lfp', 'target_lfp']
mask_keys = ['target_and_comp', 'target_not_comp']
osc_mask = {}
for key in roi_keys:
hemroi = lfp_hemroi if key=='target_lfp' else comp_hemroi
basename = '{}-{}.pkl'.format(unit['subj_sess'], hemroi)
osc_mask[key] = dio.open_pickle(op.join(data_dir, 'p_episode', basename))
if (osc_mask[key].buffer > 0) & (not osc_mask[key].clip_buffer):
osc_mask[key] = osc_mask[key].loc[:, :, :, osc_mask[key].buffer:osc_mask[key].time.size-osc_mask[key].buffer-1]
osc_mask[key].attrs['clip_buffer'] = True
if unit['chan'] in osc_mask[key].chan:
osc_mask[key] = osc_mask[key].loc[{'chan': [chan for chan in osc_mask[key].chan.values
if chan not in [unit['chan']]]}]
if not np.array_equal(osc_mask[key].freq.values, freqs):
osc_mask[key] = osc_mask[key].loc[{'freq': [freq for freq in osc_mask[key].freq.values
if freq in freqs]}]
osc_mask['target_and_comp'] = osc_mask['target_lfp'].copy(data=osc_mask['target_lfp'].values & np.any(osc_mask['comp_lfp'].values, axis=1)[:, None, :, :])
osc_mask['target_not_comp'] = osc_mask['target_lfp'].copy(data=osc_mask['target_lfp'].values & ~np.any(osc_mask['comp_lfp'].values, axis=1)[:, None, :, :])
# Calculate P-episode at each frequency, across channels and events.
peps = {key: 100 * osc_mask[key].mean(dim=('event', 'chan', 'time')).values
for key in mask_keys}
max_pep = {key: np.nanmax(peps[key]) for key in mask_keys}
max_pep_freq = {key: np.nanargmax(peps[key]) for key in mask_keys}
# Ensure that phase, oscillation mask, and spike_times are all in the same event order.
assert np.array_equal(phase.event.values, osc_mask[key].event.values)
assert np.array_equal(phase.event.values,
np.array(event_time_spikes.apply(lambda x: (x['gameState'],
x['trial']),
axis=1).values))
# ------------------------------------
# Calculate real phase-locking
# Get a masked array of spike phases, across events, during active
# oscillations at each channel and frequency.
spike_phases = {key: np.ma.concatenate(event_time_spikes.apply(
lambda x: get_spike_phases(
x['spike_times'],
phase.values[x['event_idx'], :, :, :],
mask=np.invert(osc_mask[key].values[x['event_idx'], ...]),
event_dur=event_dur,
circshift=False),
axis=1).tolist(), axis=-1) # chan x freq x spike
for key in mask_keys}
# Match the number of spikes sampled between mask keys, at each channel and frequency.
if match_spikes: