forked from a-antoniades/Neuroformer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatasets.py
More file actions
182 lines (150 loc) · 5.86 KB
/
Copy pathdatasets.py
File metadata and controls
182 lines (150 loc) · 5.86 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
import sys
sys.path.append("./neuroformer")
import itertools
import json
import os
import pickle
import numpy as np
import pandas as pd
import torch
from neuroformer.dataset import build_dataloader
def split_data_by_interval(intervals, r_split=0.8, r_split_ft=0.1):
chosen_idx = np.random.choice(
len(intervals), int(len(intervals) * r_split), replace=False
)
train_intervals = intervals[chosen_idx]
test_intervals = np.array([i for i in intervals if i not in train_intervals])
finetune_intervals = np.array(
train_intervals[: int(len(train_intervals) * r_split_ft)]
)
# sum_intervals = len(train_intervals) + len(test_intervals) # finetune_intervals is part of train_intervals
# assert sum_intervals == len(intervals), f"Sum of intervals is not equal to the original intervals: {sum_intervals} != {len(intervals)}"
return train_intervals, test_intervals, finetune_intervals
def combo3_V1AL_callback(frames, frame_idx, n_frames, **kwargs):
"""
Shape of frames: [3, 640, 64, 112]
(3 = number of stimuli)
(0-20 = n_stim 0,
20-40 = n_stim 1,
40-60 = n_stim 2)
frame_idx: the frame_idx in question
n_frames: the number of frames to be returned
"""
trial = kwargs["trial"]
if trial <= 20:
n_stim = 0
elif trial <= 40:
n_stim = 1
elif trial <= 60:
n_stim = 2
if isinstance(frames, np.ndarray):
frames = torch.from_numpy(frames)
f_idx_0 = max(0, frame_idx - n_frames)
f_idx_1 = f_idx_0 + n_frames
chosen_frames = frames[n_stim, f_idx_0:f_idx_1].type(torch.float32).unsqueeze(0)
return chosen_frames
def visnav_callback(frames, frame_idx, n_frames, **args):
"""
frames: [n_frames, 1, 64, 112]
frame_idx: the frame_idx in question
n_frames: the number of frames to be returned
"""
if isinstance(frames, np.ndarray):
frames = torch.from_numpy(frames)
f_idx_0 = max(0, frame_idx - n_frames)
f_idx_1 = f_idx_0 + n_frames
chosen_frames = frames[f_idx_0:f_idx_1].type(torch.float32).unsqueeze(0)
return chosen_frames
def download_data():
print(f"Creating directory ./data and storing datasets!")
print("Downloading data...")
import gdown
url = "https://drive.google.com/drive/folders/1O6T_BH9Y2gI4eLi2FbRjTVt85kMXeZN5?usp=sharing"
gdown.download_folder(id=url, quiet=False, use_cookies=False, output="./data")
def load_V1AL(config, stimulus_path=None, response_path=None, top_p_ids=None):
if not os.path.exists("./data"):
download_data()
if stimulus_path is None:
# stimulus_path = "/home/antonis/projects/slab/git/slab/transformer_exp/code/data/SImNew3D/stimulus/tiff"
stimulus_path = "data/Combo3_V1AL/NF_1.5/Combo3_V1AL_stimulus.pt"
if response_path is None:
response_path = "data/Combo3_V1AL/NF_1.5/Combo3_V1AL.pkl"
data = {}
data["spikes"] = pickle.load(open(response_path, "rb"))
data["stimulus"] = torch.load(stimulus_path).transpose(1, 2).squeeze(1)
intervals = np.arange(0, 31, config.window.curr)
trials = list(set(data["spikes"].keys()))
combinations = np.array(list(itertools.product(intervals, trials)))
train_intervals, test_intervals, finetune_intervals = split_data_by_interval(
combinations, r_split=0.8, r_split_ft=0.01
)
return (
data,
intervals,
train_intervals,
test_intervals,
finetune_intervals,
combo3_V1AL_callback,
)
def load_visnav(version, config, selection=None):
if not os.path.exists("./data"):
download_data()
if version not in ["medial", "lateral"]:
raise ValueError("version must be either 'medial' or 'lateral'")
if version == "medial":
data_path = "./data/VisNav_VR_Expt/MedialVRDataset/"
elif version == "lateral":
data_path = "./data/VisNav_VR_Expt/LateralVRDataset/"
spikes_path = f"{data_path}/NF_1.5/spikerates_dt_0.01.npy"
speed_path = f"{data_path}/NF_1.5/behavior_speed_dt_0.05.npy"
stim_path = f"{data_path}/NF_1.5/stimulus.npy"
phi_path = f"{data_path}/NF_1.5/phi_dt_0.05.npy"
th_path = f"{data_path}/NF_1.5/th_dt_0.05.npy"
data = dict()
data["spikes"] = np.load(spikes_path)
data["speed"] = np.load(speed_path)
data["stimulus"] = np.load(stim_path)
data["phi"] = np.load(phi_path)
data["th"] = np.load(th_path)
if selection is not None:
selection = np.array(
pd.read_csv(os.path.join(data_path, f"{selection}.csv"), header=None)
).flatten()
data["spikes"] = data["spikes"][selection - 1]
spikes = data["spikes"]
intervals = np.arange(0, spikes.shape[1] * config.resolution.dt, config.window.curr)
train_intervals, test_intervals, finetune_intervals = split_data_by_interval(
intervals, r_split=0.8, r_split_ft=0.01
)
return (
data,
intervals,
train_intervals,
test_intervals,
finetune_intervals,
visnav_callback,
)
def experanto_callback(frames, frame_idx, n_frames, **args):
if isinstance(frames, np.ndarray):
frames = torch.from_numpy(frames)
f_idx_0 = max(0, frame_idx - n_frames)
f_idx_1 = f_idx_0 + n_frames
chosen_frames = frames[f_idx_0:f_idx_1].type(torch.float32).unsqueeze(0)
return chosen_frames
def load_experanto(config, data_path):
# load pickled data
with open(data_path, "rb") as f:
data = pickle.load(f)
total_timesteps = data["spikes"].shape[1]
intervals = np.arange(0, total_timesteps * config.resolution.dt, config.window.curr)
train_intervals, test_intervals, finetune_intervals = split_data_by_interval(
intervals, r_split=0.8, r_split_ft=0.001
)
return (
data,
intervals,
train_intervals,
test_intervals,
finetune_intervals,
experanto_callback,
)