-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime_bin_analysis.py
3374 lines (3095 loc) · 113 KB
/
time_bin_analysis.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
"""
time_bin_analysis.py
Author
------
Daniel Schonhaut
Computational Memory Lab
University of Pennsylvania
Description
-----------
Functions for analyzing firing rate data within time bins.
Last Edited
-----------
3/19/21
"""
import sys
import os.path as op
import copy
from glob import glob
from collections import OrderedDict as od
import itertools
import warnings
import random
import numpy as np
import scipy.stats as stats
from scipy.ndimage.filters import gaussian_filter1d
import pandas as pd
import statsmodels.api as sm
from statsmodels.formula.api import ols
from sklearn.preprocessing import minmax_scale
from sklearn.model_selection import KFold
from sklearn.svm import LinearSVC
from sklearn.multiclass import OneVsRestClassifier
sys.path.append("/home1/dscho/code/general")
from helper_funcs import str_replace, strip_space
import data_io as dio
sys.path.append("/home1/dscho/code/projects")
from time_cells import events_proc, spike_preproc
class EventSpikes(object):
"""The event_spikes dataframe and its properties and methods.
EventSpikes combines the behavioral by time bin info contained in
events_behav dataframe within the Events class with spike counts
by time bin for each neuron in a session.
"""
def __init__(
self, subj_sess, proj_dir="/home1/dscho/projects/time_cells", filename=None
):
"""Initialize event_spikes for a testing session."""
self.subj_sess = subj_sess
self.proj_dir = proj_dir
if filename is None:
self.filename = op.join(
self.proj_dir,
"analysis",
"events",
"{}-EventSpikes.pkl".format(self.subj_sess),
)
else:
self.filename = filename
self._set_event_spikes()
self._set_column_map()
def __str__(self):
_s = "{} neurons\n".format(self.n_neurons)
return _s
def get_spike_mat(
self,
neuron,
game_state,
index="trial",
column="time_bin",
apply_f=np.sum,
qry=None,
):
"""Return a trial x time_bin dataframe of spikes within game state.
Parameters
----------
neuron : str
e.g. '17-1' is channel 17, unit 1.
game_state : str
Delay1, Encoding, ReturnToBase1, Delay2, Retrieval, or ReturnToBase2.
index : str
event_spikes column whose unique values will form the rows of the output dataframe.
column : str
event_spikes column whose unique values will form the columns of the output dataframe.
apply_f : func
The function to apply over grouped values.
qry : str
Gets passed to event_spikes.query() to select a subset of rows within the game state
(e.g. when time_penalty==1).
"""
spike_mat = self.event_spikes.query(
"(gameState=='{}')".format(game_state)
).copy()
if qry is not None:
spike_mat = spike_mat.query(qry)
spike_mat = (
spike_mat.groupby([index, column])[neuron].apply(apply_f).unstack(column)
)
return spike_mat
def _set_column_map(self):
"""Organize event_spikes columns into behavioral and neural ID lists."""
cols = od(
{
"icpt": ["icpt"],
"trial": [
col for col in self.event_spikes.columns if col.startswith("trial-")
],
"time": ["time-{}".format(_i) for _i in range(1, 11)],
"place": [
col for col in self.event_spikes.columns if col.startswith("place-")
],
"hd": [
col for col in self.event_spikes.columns if col.startswith("hd-")
],
"is_moving": ["is_moving"],
"base_in_view": ["base_in_view"],
"gold_in_view": ["gold_in_view"],
"dig_performed": ["dig_performed"],
}
)
# Add an unnested version of all behavioral columns.
cols["behav"] = list(itertools.chain.from_iterable(cols.values()))
# Add a column for neuron IDs.
cols["neurons"] = []
for col in self.event_spikes.columns:
# Neuron ID columns are stored like 'channel-unit';
# e.g. '16-2' is the second unit on channel 16.
try:
assert len([int(x) for x in col.split("-")]) == 2
cols["neurons"].append(col)
except (ValueError, AssertionError):
continue
self.column_map = cols
def _set_event_spikes(self):
"""Create the event spikes dataframe.
event_spikes is an extension of the behav_events dataframe
(see events_proc.Events.log_events_behav) in which each row
contains behavioral variables for one 500ms time bin in a
testing session. Here we add on a column for each neuron in
the session in which we count the number of spikes within each
time bin.
Also, categorical variable columns are one-hot-coded
in preparation to use event_spikes for regression model
construction.
"""
events = events_proc.load_events(
self.subj_sess, proj_dir=self.proj_dir, verbose=False, run_all=True
)
event_spikes = events.events_behav.copy()
# Add an intercept column for regression fitting.
event_spikes["icpt"] = 1
# Format column values.
event_spikes["maze_region"] = event_spikes["maze_region"].apply(
lambda x: x.replace(" ", "_")
)
game_states = [
"Delay1",
"Encoding",
"ReturnToBase1",
"Delay2",
"Retrieval",
"ReturnToBase2",
]
game_state_cat = pd.CategoricalDtype(game_states, ordered=True)
event_spikes["gameState"] = event_spikes["gameState"].astype(game_state_cat)
# Convert discrete value columns into one-hot-coded columns.
time_step_loc, time_step_vals = (
event_spikes.columns.tolist().index("time_step"),
event_spikes["time_step"].tolist(),
)
maze_region_loc, maze_region_vals = (
event_spikes.columns.tolist().index("maze_region"),
event_spikes["maze_region"].tolist(),
)
head_direc_loc, head_direc_vals = (
event_spikes.columns.tolist().index("head_direc"),
event_spikes["head_direc"].tolist(),
)
trial_loc, trial_vals = (
event_spikes.columns.tolist().index("trial"),
event_spikes["trial"].tolist(),
)
event_spikes = pd.get_dummies(
event_spikes,
prefix_sep="-",
prefix={
"time_step": "time",
"maze_region": "place",
"head_direc": "hd",
"trial": "trial",
},
columns=["time_step", "maze_region", "head_direc", "trial"],
)
event_spikes.insert(time_step_loc, "time_step", time_step_vals)
event_spikes.insert(maze_region_loc, "maze_region", maze_region_vals)
event_spikes.insert(head_direc_loc, "head_direc", head_direc_vals)
event_spikes.insert(trial_loc, "trial", trial_vals)
# Only count the base as being in view when player is outside the base.
event_spikes.loc[
(event_spikes["place-Base"] == 1) & (event_spikes["base_in_view"] == 1),
"base_in_view",
] = 0
# Convert gold_in_view nans at Retrieval to 0.
event_spikes.loc[
(event_spikes["gameState"] == "Retrieval")
& (np.isnan(event_spikes["gold_in_view"])),
"gold_in_view",
] = 0
# Sort rows.
event_spikes = event_spikes.sort_values(
["trial", "gameState", "time_bin"]
).reset_index(drop=True)
# Get neurons from the session.
globstr = op.join(
self.proj_dir,
"analysis",
"spikes",
"{}-*-spikes.pkl".format(self.subj_sess),
)
spike_files = {spike_preproc.unit_from_file(_f): _f for _f in glob(globstr)}
neurons = list(spike_files.keys())
# Add a column with spike counts for each neuron.
for neuron in neurons:
spike_times = dio.open_pickle(spike_files[neuron])["spike_times"]
event_spikes[neuron] = spikes_per_timebin(event_spikes, spike_times)
self.n_neurons = len(neurons)
self.event_spikes = event_spikes
def save_event_spikes(event_spikes, overwrite=False, verbose=True):
"""Pickle an EventSpikes instance."""
if op.exists(event_spikes.filename) and not overwrite:
print("Cannot save {} as it already exists".format(event_spikes.filename))
else:
dio.save_pickle(event_spikes, event_spikes.filename, verbose)
def load_event_spikes(
subj_sess,
proj_dir="/home1/dscho/projects/time_cells",
filename=None,
overwrite=False,
verbose=True,
):
"""Return EventSpikes from saved file or by instantiating anew."""
if filename is None:
filename = op.join(
proj_dir, "analysis", "events", "{}-EventSpikes.pkl".format(subj_sess)
)
if op.exists(filename) and not overwrite:
if verbose:
print("Loading saved EventSpikes file")
event_spikes = dio.open_pickle(filename)
else:
if verbose:
print("Creating EventSpikes")
event_spikes = EventSpikes(subj_sess, proj_dir=proj_dir, filename=filename)
return event_spikes
def get_ols_delay_formulas(neuron, df):
"""Define model formulas for single-unit to behavior comparisons.
Parameters
----------
neuron : str
e.g. '5-2' would be channel 5, unit 2
df : DataFrame
Contains the dependent variable and all independent variables.
Returns
-------
Xy : dataframe
Contains the dependent variable and independent variables, with
all categorical variables deviation-coded.
Xycols : dict[list]
Xy column names, grouped by variable type.
formulas : dict[str]
Full and reduced model formulas.
"""
# Setup the full model.
param_map = {
"neuron": neuron,
"gameState": "C(gameState, Sum)",
"time": "C(time_step, Sum)",
}
formula = strip_space(
"Q('{_[neuron]}') ~ 1 + {_[gameState]} + {_[time]} + {_[gameState]}:{_[time]}".format(
_=param_map
)
)
full_mod = ols(formula, data=df)
# Get the expanded predictor matrix of deviation-coded parameters,
# and insert the dependent variable column.
Xy = pd.concat(
(
pd.Series(full_mod.endog, name=neuron),
pd.DataFrame(full_mod.exog, columns=full_mod.exog_names),
),
axis=1,
)
Xy.drop(columns=["Intercept"], inplace=True)
# Rename columns for the Xy dataframe.
Xycols_old = od(
[
("neuron", [neuron]),
(
"gameState",
[
col
for col in Xy.columns
if np.all(
[
("gameState" in col),
("time_step" not in col),
(":" not in col),
]
)
],
),
(
"time",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" in col),
(":" not in col),
]
)
],
),
(
"gameState:time",
[
col
for col in Xy.columns
if np.all([("time" in col), ("gameState" in col), (":" in col)])
],
),
]
)
Xycols_new = od([])
param_map = od([])
for cols in Xycols_old:
Xycols_new[cols] = str_replace(
Xycols_old[cols],
{
"C(gameState, Sum)[S.": "gameState_",
"C(time_step, Sum)[S.": "time_",
"]": "",
},
)
Xy.rename(
columns=pd.Series(index=Xycols_old[cols], data=Xycols_new[cols]).to_dict(),
inplace=True,
)
param_map[cols] = " + ".join(Xycols_new[cols])
Xycols = Xycols_new
# --------------------------------------------
# --------------------------------------------
# Define formulas for full and reduced models.
formulas = od([])
# ---------------------------------------------------------
# full models firing rate as a function of gameState, time,
# and their interaction.
formulas["full"] = strip_space(
"Q('{_[neuron]}') ~ 1 + {_[gameState]} + {_[time]} + {_[gameState:time]}".format(
_=param_map
)
)
# Fixed firing rate differences between encoding and retrieval, holding constant time and its interaction with gameState.
formulas["full-gameState"] = strip_space(
"Q('{_[neuron]}') ~ 1 + {_[time]} + {_[gameState:time]}".format(
_=param_map
)
)
# Time cells, with or without remapping, holding constant fixed differences between encoding and retrieval firing.
formulas["full-time,gameState:time"] = strip_space(
"Q('{_[neuron]}') ~ 1 + {_[gameState]} ".format(
_=param_map
)
)
# Context-invariant time cells, holding constant gameState and its interaction with time.
formulas["full-time"] = strip_space(
"Q('{_[neuron]}') ~ 1 + {_[gameState]} + {_[gameState:time]}".format(
_=param_map
)
)
# Trial state remapping time cells, holding constant time and gameState main effects.
formulas["full-gameState:time"] = strip_space(
"Q('{_[neuron]}') ~ 1 + {_[gameState]} + {_[time]} ".format(
_=param_map
)
)
return Xy, Xycols, formulas, param_map
def run_ols_delay(
subj_sess_unit,
formula_func=get_ols_delay_formulas,
game_states=["Delay1", "Delay2"],
n_perm=1000,
alpha=0.05,
mod_names=None,
mult_by=1,
proj_dir="/home1/dscho/projects/time_cells",
save_output=True,
overwrite=True,
verbose=False,
):
"""Run time regression analysis for one neuron.
Returns
-------
mod_pairs : dataframe
Likelihood ratio and empirical p-value for each model comparison.
ols_weights : dataframe
Beta weights and Z-scored weights for full model parameters.
"""
# Load event and neuron info.
subj_sess, *neuron = subj_sess_unit.split("-")
neuron = "-".join(neuron)
event_spikes = load_event_spikes(subj_sess, proj_dir=proj_dir, verbose=verbose)
hem, *roi = spike_preproc.roi_lookup(
subj_sess, neuron.split("-")[0], proj_dir=proj_dir
)
roi = "".join(roi)
# List the models that we want to extract weights for.
if mod_names is None:
mod_names = ["full"]
# Fit models to real data.
ols_mods, Xy, Xycols, *_ = get_ols_delay_mods(
neuron,
event_spikes,
formula_func=formula_func,
game_states=game_states,
circshift_frs=False,
)
paired_comps = _get_paired_comps("delay")
mod_pairs = get_ols_mod_pairs(ols_mods, paired_comps)
ols_weights = get_ols_weights(
ols_mods, Xycols, mod_names=mod_names, mult_by=mult_by
)
# Fit null models.
mod_pairs_null = []
ols_weights_null = []
for iPerm in range(n_perm):
_ols_mods_null, *_ = get_ols_delay_mods(
neuron,
event_spikes,
formula_func=formula_func,
game_states=game_states,
circshift_frs=True,
)
mod_pairs_null.append(get_ols_mod_pairs(_ols_mods_null, paired_comps))
ols_weights_null.append(
get_ols_weights(
_ols_mods_null, Xycols, mod_names=mod_names, mult_by=mult_by
)
)
mod_pairs_null = pd.concat(mod_pairs_null, axis=0).reset_index(drop=True)
ols_weights_null = pd.concat(ols_weights_null, axis=0).reset_index(drop=True)
# Test significance and Z-score weights against the null distribution.
mod_pairs[["z_lr", "emp_pval"]] = mod_pairs.apply(
lambda x: _get_emp_pval(x, mod_pairs_null), axis=1
).tolist()
mod_pairs["sig"] = mod_pairs["emp_pval"].apply(lambda x: x < alpha)
ols_weights["z_weight"] = ols_weights.apply(
lambda x: _zscore_weights(x, ols_weights_null), axis=1
)
# Add unique identifiers.
for _df in (mod_pairs, ols_weights):
_df.insert(0, "subj_sess_unit", subj_sess_unit)
_df.insert(1, "hem", hem)
_df.insert(2, "roi", roi)
_df.insert(3, "gameState", "-".join(game_states))
# Save outputs.
if save_output:
mod_pairs_file = op.join(
proj_dir,
"analysis",
"unit_to_behav",
"{}-{}-{}-ols_model_pairs.pkl".format(
subj_sess, neuron, "_".join(game_states)
),
)
ols_weights_file = op.join(
proj_dir,
"analysis",
"unit_to_behav",
"{}-{}-{}-ols_weights.pkl".format(subj_sess, neuron, "_".join(game_states)),
)
if overwrite or not op.exists(mod_pairs_file):
dio.save_pickle(mod_pairs, mod_pairs_file, verbose)
if overwrite or not op.exists(ols_weights_file):
dio.save_pickle(ols_weights, ols_weights_file, verbose)
return mod_pairs, ols_weights
def get_ols_delay_mods(
neuron,
event_spikes,
formula_func,
game_states=["Delay1", "Delay2"],
event_spikes_idx=None,
circshift_frs=False,
):
"""Find the most important time bin.
Fit firing rates using OLS regression, iteratively removing
each time step from the data and recording
Parameters
----------
neuron : str
e.g. '5-2' would be channel 5, unit 2
event_spikes : pd.DataFrame
EventSpikes instance that contains the event_spikes dataframe,
an expanded version of the behav_events dataframe with columns
added for each neuron.
game_states : list[str]
Delay1, Encoding, Delay2, or Retrieval.
event_spikes_idx : list
Only event_spikes rows that correspond to the provided index
labels are used in the regression model. Overrides querying
by gameState.
Returns
-------
ols_mods : dict[statsmodels.regression.linear_model.OLS]
Xy : dataframe
Contains the dependent variable and independent variables, with
all categorical variables deviation-coded.
Xycols : dict[list]
Xy column names, grouped by variable type.
formulas : dict[str]
Full and reduced model formulas.
"""
# Select rows for the chosen game states.
if type(game_states) == str:
game_states = [game_states]
if event_spikes_idx is None:
_event_spikes = event_spikes.event_spikes.query(
"(gameState=={})".format(game_states)
).copy()
else:
_event_spikes = event_spikes.event_spikes.loc[event_spikes_idx].copy()
_event_spikes["gameState"] = _event_spikes["gameState"].astype(str)
# For delays, sum spikes across time bins within each time step, within each trial.
_event_spikes = (
_event_spikes.groupby(["gameState", "trial", "time_step"])
.agg({neuron: np.sum})
.reset_index()
)
# Circ-shift firing rates within each trial interval,
# then shuffle trial intervals across game states.
if circshift_frs:
_event_spikes[neuron] = _circshift_shuffle(
_event_spikes, neuron, ["trial", "gameState"]
)
# Fit the model.
Xy, Xycols, formulas, param_map = formula_func(neuron, _event_spikes)
ols_mods = od([])
for mod, formula in formulas.items():
ols_mods[mod] = ols(formula, data=Xy)
return ols_mods, Xy, Xycols, formulas, param_map
def get_ols_nav_formulas(neuron, df):
"""Define model formulas for single-unit to behavior comparisons.
Parameters
----------
neuron : str
e.g. '5-2' would be channel 5, unit 2
df : DataFrame
Contains the dependent variable and all independent variables.
Returns
-------
Xy : dataframe
Contains the dependent variable and independent variables, with
all categorical variables deviation-coded.
Xycols : dict[list]
Xy column names, grouped by variable type.
formulas : dict[str]
Full and reduced model formulas.
"""
# ------------------------------------------------------------------------
# Setup a model with all parameters that we want to use across all models.
param_map = {
"neuron": neuron,
"gameState": "C(gameState, Sum)",
"time": "C(time_step, Sum)",
"place": "C(maze_region, Sum)",
"headDirec": "C(head_direc, Sum)",
"isMoving": "C(is_moving, Sum(0))",
"baseView": "C(base_in_view, Sum(0))",
"goldView": "C(gold_in_view, Sum(0))",
"digAction": "C(dig_performed, Sum(0))",
"penalty": "C(time_penalty, Sum(0))",
"goldDug": "gold_dug",
}
formula = strip_space(
"Q('{_[neuron]}') ~ 1 + {_[gameState]} + {_[time]} + {_[place]} + "
" {_[penalty]} + {_[goldDug]} + {_[headDirec]} + "
" {_[isMoving]} + {_[baseView]} + {_[goldView]} + "
" {_[digAction]} + "
" {_[gameState]}:{_[time]} + {_[gameState]}:{_[place]} + {_[time]}:{_[place]} + "
" {_[gameState]}:{_[penalty]} + {_[time]}:{_[penalty]} + {_[place]}:{_[penalty]} + "
" {_[gameState]}:{_[goldDug]} + {_[time]}:{_[goldDug]} + {_[place]}:{_[goldDug]} + "
" {_[gameState]}:{_[headDirec]} + {_[gameState]}:{_[isMoving]} + {_[gameState]}:{_[baseView]} ".format(
_=param_map
)
)
mod = ols(formula, data=df)
# Get the expanded predictor matrix of deviation-coded parameters,
# and insert the dependent variable column.
Xy = pd.concat(
(
pd.Series(mod.endog, name=neuron),
pd.DataFrame(mod.exog, columns=mod.exog_names),
),
axis=1,
)
Xy.drop(columns=["Intercept"], inplace=True)
# ------------------------------------
# Rename columns for the Xy dataframe.
Xycols_old = od(
[
("neuron", [neuron]),
(
"gameState",
[
col
for col in Xy.columns
if np.all(
[
("gameState" in col),
("time_step" not in col),
("maze_region" not in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" not in col),
("gold_dug" not in col),
(":" not in col),
]
)
],
),
(
"time",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" in col),
("maze_region" not in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" not in col),
("gold_dug" not in col),
(":" not in col),
]
)
],
),
(
"place",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" not in col),
("maze_region" in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" not in col),
("gold_dug" not in col),
(":" not in col),
]
)
],
),
(
"penalty",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" not in col),
("maze_region" not in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" in col),
("gold_dug" not in col),
(":" not in col),
]
)
],
),
(
"goldDug",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" not in col),
("maze_region" not in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" not in col),
("gold_dug" in col),
(":" not in col),
]
)
],
),
(
"headDirec",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" not in col),
("maze_region" not in col),
("head_direc" in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" not in col),
("gold_dug" not in col),
(":" not in col),
]
)
],
),
(
"isMoving",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" not in col),
("maze_region" not in col),
("head_direc" not in col),
("is_moving" in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" not in col),
("gold_dug" not in col),
(":" not in col),
]
)
],
),
(
"baseView",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" not in col),
("maze_region" not in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" not in col),
("gold_dug" not in col),
(":" not in col),
]
)
],
),
(
"goldView",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" not in col),
("maze_region" not in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" in col),
("dig_performed" not in col),
("time_penalty" not in col),
("gold_dug" not in col),
(":" not in col),
]
)
],
),
(
"digAction",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" not in col),
("maze_region" not in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" in col),
("time_penalty" not in col),
("gold_dug" not in col),
(":" not in col),
]
)
],
),
(
"gameState:time",
[
col
for col in Xy.columns
if np.all(
[
("gameState" in col),
("time_step" in col),
("maze_region" not in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" not in col),
("gold_dug" not in col),
(":" in col),
]
)
],
),
(
"gameState:place",
[
col
for col in Xy.columns
if np.all(
[
("gameState" in col),
("time_step" not in col),
("maze_region" in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" not in col),
("gold_dug" not in col),
(":" in col),
]
)
],
),
(
"time:place",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" in col),
("maze_region" in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" not in col),
("gold_dug" not in col),
(":" in col),
]
)
],
),
(
"gameState:penalty",
[
col
for col in Xy.columns
if np.all(
[
("gameState" in col),
("time_step" not in col),
("maze_region" not in col),
("head_direc" not in col),
("is_moving" not in col),
("base_in_view" not in col),
("gold_in_view" not in col),
("dig_performed" not in col),
("time_penalty" in col),
("gold_dug" not in col),
(":" in col),
]
)
],
),
(
"time:penalty",
[
col
for col in Xy.columns
if np.all(
[
("gameState" not in col),
("time_step" in col),
("maze_region" not in col),
("head_direc" not in col),