pytour 3.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pytour-3.0.0.dist-info/METADATA +27 -0
- pytour-3.0.0.dist-info/RECORD +15 -0
- pytour-3.0.0.dist-info/WHEEL +5 -0
- pytour-3.0.0.dist-info/licenses/LICENSE +21 -0
- pytour-3.0.0.dist-info/top_level.txt +1 -0
- tour/__init__.py +1 -0
- tour/artifacts_removal.py +122 -0
- tour/backend.py +34 -0
- tour/dataclass/__init__.py +0 -0
- tour/dataclass/dataset.py +465 -0
- tour/dataclass/io.py +225 -0
- tour/dataclass/stim.py +33 -0
- tour/package_manage.py +13 -0
- tour/torch_trainer.py +339 -0
- tour/vis.py +201 -0
@@ -0,0 +1,27 @@
|
|
1
|
+
Metadata-Version: 2.4
|
2
|
+
Name: pytour
|
3
|
+
Version: 3.0.0
|
4
|
+
Home-page: https://github.com/powerfulbean/pytour
|
5
|
+
Author: Powerfulbean
|
6
|
+
Author-email: powerfulbean@gmail.com
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
9
|
+
Classifier: Operating System :: OS Independent
|
10
|
+
Description-Content-Type: text/markdown
|
11
|
+
License-File: LICENSE
|
12
|
+
Requires-Dist: mne
|
13
|
+
Requires-Dist: numpy
|
14
|
+
Requires-Dist: scipy
|
15
|
+
Requires-Dist: matplotlib
|
16
|
+
Requires-Dist: h5py
|
17
|
+
Dynamic: author
|
18
|
+
Dynamic: author-email
|
19
|
+
Dynamic: classifier
|
20
|
+
Dynamic: description
|
21
|
+
Dynamic: description-content-type
|
22
|
+
Dynamic: home-page
|
23
|
+
Dynamic: license-file
|
24
|
+
Dynamic: requires-dist
|
25
|
+
|
26
|
+
# tour | 托
|
27
|
+
A framework for boosting the implementation of stimulus-response research code in the field of cognitive science and neuroscience
|
@@ -0,0 +1,15 @@
|
|
1
|
+
pytour-3.0.0.dist-info/licenses/LICENSE,sha256=aVxJnzWLBuZmbL7MD59A84A1PGtZV70nAtEzjwwl5fQ,1064
|
2
|
+
tour/__init__.py,sha256=EPmgXOdWKks5S__ZMH7Nu6xpAeVrZpfxaFy4pykuyeI,22
|
3
|
+
tour/artifacts_removal.py,sha256=2x7EEJm-i8K9bWJnE3_KkpXcemHQrp7NCVX_jA9EymI,3630
|
4
|
+
tour/backend.py,sha256=TBPGxoEomAUsHC_sLanUxgxR-Uyq_NtAw0ZXGrMmM1I,739
|
5
|
+
tour/package_manage.py,sha256=zRGdiBbybdRkxZ04YL3kh-oCl5NpVdmo_Yr6j-hr_PE,235
|
6
|
+
tour/torch_trainer.py,sha256=YA6uT5l_OryxPWl5oB5e4Z0XYBypsCsAUGe5rnW8Wsc,10418
|
7
|
+
tour/vis.py,sha256=3Oju73imHh75Wh4CGJkPj41UjyrHp8nGpAinqJf-ogg,5871
|
8
|
+
tour/dataclass/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
9
|
+
tour/dataclass/dataset.py,sha256=gJcnajvAaDNXJ8KFAmvYqxBVzqJbQs5xY85x2Jza1wA,16131
|
10
|
+
tour/dataclass/io.py,sha256=To5o3zZ8VA9fAQtRGY6iInTG0egBwBwxXD4eIAZ_HB4,6367
|
11
|
+
tour/dataclass/stim.py,sha256=vTMqEiia_1XIZHEhJYpd8mGKx4SRtW0fcsis1CksDF0,996
|
12
|
+
pytour-3.0.0.dist-info/METADATA,sha256=MxKlAcJXyBFEoxvPEjAR4-atBxAbslawcWErwNJdGIQ,795
|
13
|
+
pytour-3.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
14
|
+
pytour-3.0.0.dist-info/top_level.txt,sha256=wpGbM2T_e0EA01E3oBcboTH5mSDsvn2HFUTwyaU6Br8,5
|
15
|
+
pytour-3.0.0.dist-info/RECORD,,
|
@@ -0,0 +1,21 @@
|
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2018 Jin Dou
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
13
|
+
copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21
|
+
SOFTWARE.
|
@@ -0,0 +1 @@
|
|
1
|
+
tour
|
tour/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
__version__ = "3.0.0"
|
@@ -0,0 +1,122 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
"""
|
3
|
+
Created on Thu Jul 8 14:41:55 2021
|
4
|
+
|
5
|
+
@author: Jin Dou
|
6
|
+
"""
|
7
|
+
import mne
|
8
|
+
import numpy as np
|
9
|
+
from scipy.stats import zscore
|
10
|
+
|
11
|
+
def mneWrap_lalorlab_detect_EEG_badChannels(mneraw:mne.io.RawArray, montage = None, nNearest = 10):
|
12
|
+
oRaw = mneraw.copy()
|
13
|
+
data = oRaw.get_data()
|
14
|
+
if montage is None:
|
15
|
+
badChansIdx = lalorlab_detect_EEG_badChannels(data,False)
|
16
|
+
else:
|
17
|
+
badChansIdx = lalorlab_detect_EEG_badChannels_covVarNear(data,montage, nNearest = nNearest)
|
18
|
+
oRaw.info['bads'] = [oRaw.info['ch_names'][i] for i in badChansIdx]
|
19
|
+
print(f'bad channels: {",".join(oRaw.info["bads"])}')
|
20
|
+
return oRaw
|
21
|
+
|
22
|
+
|
23
|
+
def lalorlab_detect_EEG_badChannels(eegarray,verbose = True):
|
24
|
+
'''
|
25
|
+
we assume the first dimension is channel dimension
|
26
|
+
|
27
|
+
Parameters
|
28
|
+
----------
|
29
|
+
eegarray : TYPE
|
30
|
+
DESCRIPTION.
|
31
|
+
|
32
|
+
Returns
|
33
|
+
-------
|
34
|
+
None.
|
35
|
+
|
36
|
+
'''
|
37
|
+
eegarray = np.array(eegarray)
|
38
|
+
assert len(eegarray.shape) == 2
|
39
|
+
stdChans = list()
|
40
|
+
badChansIdx = list()
|
41
|
+
for chan in eegarray:
|
42
|
+
stdChans.append(np.std(chan))
|
43
|
+
|
44
|
+
for idx,chan in enumerate(eegarray):
|
45
|
+
if np.std(chan) > 2.5 * np.mean(stdChans):
|
46
|
+
badChansIdx.append(idx)
|
47
|
+
|
48
|
+
stdChans.clear()
|
49
|
+
|
50
|
+
for idx,chan in enumerate(eegarray):
|
51
|
+
if idx not in badChansIdx:
|
52
|
+
stdChans.append(np.std(chan))
|
53
|
+
|
54
|
+
for idx,chan in enumerate(eegarray):
|
55
|
+
if np.std(chan) < np.mean(stdChans) / 2.5:
|
56
|
+
badChansIdx.append(idx)
|
57
|
+
|
58
|
+
if verbose:
|
59
|
+
print(badChansIdx)
|
60
|
+
|
61
|
+
return badChansIdx
|
62
|
+
|
63
|
+
def lalorlab_detect_EEG_badChannels_covVarNear(data, montage, th1 = 2, th2 = 2, nNearest = 6):
|
64
|
+
# data: (nChan, nSamples)
|
65
|
+
data = np.array(data)
|
66
|
+
assert data.ndim == 2
|
67
|
+
|
68
|
+
### prepare the nearest channels
|
69
|
+
if nNearest > 0:
|
70
|
+
chanloc = montage.get_positions()['ch_pos']
|
71
|
+
chnames = []
|
72
|
+
poses = []
|
73
|
+
for n,pos in chanloc.items():
|
74
|
+
chnames.append(n)
|
75
|
+
poses.append(pos)
|
76
|
+
|
77
|
+
assert data.shape[0] == len(chnames)
|
78
|
+
chanDistMat = np.zeros((len(chanloc), len(chanloc)))
|
79
|
+
|
80
|
+
fDist = lambda pos1,pos2: np.sqrt(np.sum((pos1 - pos2)**2))
|
81
|
+
|
82
|
+
for i in range(len(chnames)):
|
83
|
+
for j in range(len(chnames)):
|
84
|
+
chanDistMat[i,j] = fDist(poses[i], poses[j])
|
85
|
+
|
86
|
+
nearChanIdx = []
|
87
|
+
for i in range(len(chnames)):
|
88
|
+
nearChanIdx.append(np.argsort(chanDistMat[i])[1:nNearest+1])
|
89
|
+
else:
|
90
|
+
nearChanIdx = [None] * data.shape[1]
|
91
|
+
### find the bad channels
|
92
|
+
dataz = zscore(data, axis = 1)
|
93
|
+
XTX = np.matmul(dataz ,dataz.T)
|
94
|
+
stdXTX = np.std(XTX, axis = 1)
|
95
|
+
stdEEG = np.std(data, axis = 1)
|
96
|
+
|
97
|
+
badChans = []
|
98
|
+
if nNearest <=0 :
|
99
|
+
badChans.append(np.where(stdXTX < np.mean(stdXTX) / th1))
|
100
|
+
badChans.append(np.where(stdEEG > np.mean(stdEEG) * th2))
|
101
|
+
else:
|
102
|
+
for chanIdx in range(data.shape[0]):
|
103
|
+
# print(stdXTX[chanIdx],
|
104
|
+
# stdEEG[chanIdx],
|
105
|
+
# np.mean(stdXTX[nearChanIdx[chanIdx]]) / th1,
|
106
|
+
# np.mean(stdEEG[nearChanIdx[chanIdx]]) * th2)
|
107
|
+
if stdXTX[chanIdx] < np.mean(stdXTX[nearChanIdx[chanIdx]]) / th1:
|
108
|
+
badChans.append(chanIdx)
|
109
|
+
if stdEEG[chanIdx] > np.mean(stdEEG[nearChanIdx[chanIdx]]) * th2:
|
110
|
+
badChans.append(chanIdx)
|
111
|
+
|
112
|
+
return list(set(badChans))
|
113
|
+
|
114
|
+
def plotChanWithNamesAtIdx(montage, idxs):
|
115
|
+
chnames = montage.ch_names
|
116
|
+
montage.plot(show_names = [chnames[idx] for idx in idxs])
|
117
|
+
|
118
|
+
|
119
|
+
# def
|
120
|
+
|
121
|
+
|
122
|
+
|
tour/backend.py
ADDED
@@ -0,0 +1,34 @@
|
|
1
|
+
import numbers
|
2
|
+
from typing import TypeVar
|
3
|
+
|
4
|
+
try:
|
5
|
+
import torch
|
6
|
+
except:
|
7
|
+
torch = None
|
8
|
+
|
9
|
+
try:
|
10
|
+
import numpy as np
|
11
|
+
except:
|
12
|
+
np = None
|
13
|
+
|
14
|
+
Array = TypeVar("Array")
|
15
|
+
|
16
|
+
def get_numeric_backend(data: Array):
|
17
|
+
if isinstance(data, torch.Tensor):
|
18
|
+
return torch
|
19
|
+
elif isinstance(data, np.ndarray):
|
20
|
+
return np
|
21
|
+
elif isinstance(data, numbers.Number):
|
22
|
+
return np
|
23
|
+
else:
|
24
|
+
raise ValueError(f"input is not an numeric variable")
|
25
|
+
|
26
|
+
def is_tensor(data: Array):
|
27
|
+
if isinstance(data, torch.Tensor):
|
28
|
+
return True
|
29
|
+
elif isinstance(data, np.ndarray):
|
30
|
+
return False
|
31
|
+
elif isinstance(data, numbers.Number):
|
32
|
+
return False
|
33
|
+
else:
|
34
|
+
raise ValueError(f"input is not an numeric variable")
|
File without changes
|
@@ -0,0 +1,465 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
"""
|
3
|
+
Created on Thu Jan 16 12:44:20 2025
|
4
|
+
|
5
|
+
@author: jdou3
|
6
|
+
"""
|
7
|
+
import re
|
8
|
+
import io
|
9
|
+
import copy
|
10
|
+
import h5py
|
11
|
+
import json
|
12
|
+
import itertools
|
13
|
+
# import h5py
|
14
|
+
from typing import List
|
15
|
+
import numpy as np
|
16
|
+
|
17
|
+
from .io import (
|
18
|
+
data_record_from_h5py_group, data_record_to_h5py_group, _validate_stimuli_dict
|
19
|
+
)
|
20
|
+
|
21
|
+
#Note: please don't change the order, it matters for some functions using it
|
22
|
+
META_INFO_FORCED_FIELD = ['dataset_name', 'subj_id', 'trial_id']
|
23
|
+
|
24
|
+
|
25
|
+
def flatten_list_of_lists(list_of_lists:List[List]):
|
26
|
+
return list(itertools.chain.from_iterable(list_of_lists))
|
27
|
+
|
28
|
+
def k_folds(n_trials, n_folds):
|
29
|
+
id_trials = np.arange(n_trials)
|
30
|
+
splits = np.array_split(id_trials, n_folds)
|
31
|
+
for split_idx in range(len(splits)):
|
32
|
+
# print('cv fold', split_idx)
|
33
|
+
idx_val = splits[split_idx]
|
34
|
+
idx_train = np.concatenate(splits[:split_idx] + splits[split_idx + 1 :])
|
35
|
+
yield idx_train, idx_val
|
36
|
+
|
37
|
+
|
38
|
+
def _validate_meta_info(info:dict):
|
39
|
+
assert all([k in info for k in META_INFO_FORCED_FIELD])
|
40
|
+
for k, v in info.items():
|
41
|
+
if isinstance(v, np.integer):
|
42
|
+
info[k] = int(v)
|
43
|
+
for k,v in info.items():
|
44
|
+
assert isinstance(v, ((str, int, float, np.ndarray))), f"{k},{type(v)}"
|
45
|
+
return info
|
46
|
+
|
47
|
+
def align_data(*arrs):
|
48
|
+
arrs = list(arrs)
|
49
|
+
#assume arr have shape [nChannel, nSamples]
|
50
|
+
minLen = min([arr.shape[1] for arr in arrs])
|
51
|
+
for i, arr in enumerate(arrs):
|
52
|
+
arrs[i] = arr[:, :minLen]
|
53
|
+
return arrs
|
54
|
+
|
55
|
+
def i_split_kfold(tarList,cur_fold,n_folds, add_dev = True):
|
56
|
+
''' curFold starts from zero '''
|
57
|
+
kfList = [i for i in k_folds(len(tarList), n_folds)]
|
58
|
+
curTrainDevIdx = kfList[cur_fold][0]
|
59
|
+
curTestIdx = kfList[cur_fold][1]
|
60
|
+
curDevIdx = kfList[(cur_fold + 1) % n_folds][1]
|
61
|
+
if add_dev:
|
62
|
+
curTrainIdx = [i for i in curTrainDevIdx if i not in curDevIdx]
|
63
|
+
curTrain = [tarList[i] for i in curTrainIdx]
|
64
|
+
curDev = [tarList[i] for i in curDevIdx]
|
65
|
+
curTest = [tarList[i] for i in curTestIdx]
|
66
|
+
return curTrain, curDev, curTest
|
67
|
+
else:
|
68
|
+
curTrainDev = [tarList[i] for i in curTrainDevIdx]
|
69
|
+
curTest = [tarList[i] for i in curTestIdx]
|
70
|
+
return curTrainDev, [], curTest
|
71
|
+
|
72
|
+
def k_fold(dataset:'Dataset', cur_fold, n_folds, split_by = 'trial_id', add_dev = True, if_shuffle = False, seed = 42):
|
73
|
+
info_sets = sorted(
|
74
|
+
list(set(
|
75
|
+
[i.meta_info[split_by] for i in dataset.records]
|
76
|
+
)))
|
77
|
+
if if_shuffle:
|
78
|
+
rng = np.random.default_rng(seed)
|
79
|
+
inf_idxs = np.arange(len(info_sets))
|
80
|
+
rng.shuffle(inf_idxs)
|
81
|
+
info_sets = [info_sets[idx_] for idx_ in inf_idxs]
|
82
|
+
info_train_list, info_dev_list, info_test_list = i_split_kfold(
|
83
|
+
info_sets, cur_fold, n_folds, add_dev)
|
84
|
+
print(info_train_list, info_dev_list, info_test_list)
|
85
|
+
output = {}
|
86
|
+
output['train'] = dataset.subset_by_info({split_by:info_train_list})
|
87
|
+
if len(info_dev_list) > 0:
|
88
|
+
output['dev'] = dataset.subset_by_info({split_by:info_dev_list})
|
89
|
+
output['test'] = dataset.subset_by_info({split_by:info_test_list})
|
90
|
+
return output
|
91
|
+
|
92
|
+
|
93
|
+
def dump_dict_contains_nparray(state_dict):
|
94
|
+
output = {}
|
95
|
+
for key, value in state_dict.items():
|
96
|
+
if isinstance(value, np.ndarray):
|
97
|
+
buffer = io.BytesIO()
|
98
|
+
np.save(buffer, value)
|
99
|
+
t_value = buffer.getvalue()
|
100
|
+
elif isinstance(value, dict):
|
101
|
+
# print(key)
|
102
|
+
t_value = dump_dict_contains_nparray(value)
|
103
|
+
else:
|
104
|
+
t_value = value
|
105
|
+
output[key] = t_value
|
106
|
+
return output
|
107
|
+
|
108
|
+
def load_dict_contains_nparray(state_dict):
|
109
|
+
new_state = {}
|
110
|
+
for k,v in state_dict.items():
|
111
|
+
if isinstance(v, bytes):
|
112
|
+
buffer = io.BytesIO(v)
|
113
|
+
new_state[k] = np.load(buffer)
|
114
|
+
# new_state[k] = np.frombuffer(v)
|
115
|
+
elif isinstance(v, dict):
|
116
|
+
# print(k)
|
117
|
+
new_state[k] = load_dict_contains_nparray(v)
|
118
|
+
else:
|
119
|
+
new_state[k] = v
|
120
|
+
return new_state
|
121
|
+
|
122
|
+
def encode_record_key(meta_info:dict):
|
123
|
+
return "-".join(
|
124
|
+
[str(meta_info[k]) for k in META_INFO_FORCED_FIELD]
|
125
|
+
)
|
126
|
+
|
127
|
+
def decode_record_key(record_key:str):
|
128
|
+
strs = record_key.split('-')
|
129
|
+
return {
|
130
|
+
k:v for k,v in zip(META_INFO_FORCED_FIELD, strs)
|
131
|
+
}
|
132
|
+
|
133
|
+
class DataRecord:
|
134
|
+
|
135
|
+
def __init__(self, data, stim_id, meta_info:dict, srate:int):
|
136
|
+
self.srate = srate
|
137
|
+
self.data = data
|
138
|
+
self.stim_id = stim_id
|
139
|
+
self.meta_info = _validate_meta_info(meta_info)
|
140
|
+
|
141
|
+
def dump_to_dict(self):
|
142
|
+
return dump_dict_contains_nparray(self.__dict__)
|
143
|
+
|
144
|
+
def dump(self):
|
145
|
+
record_key = encode_record_key(self.meta_info)
|
146
|
+
return dict(
|
147
|
+
key = record_key,
|
148
|
+
data = self.data,
|
149
|
+
stim_id = self.stim_id,
|
150
|
+
meta_info = self.meta_info,
|
151
|
+
srate = self.srate,
|
152
|
+
)
|
153
|
+
|
154
|
+
@classmethod
|
155
|
+
def load(cls, new_state:dict):
|
156
|
+
obj = cls(**new_state)
|
157
|
+
return obj
|
158
|
+
|
159
|
+
@classmethod
|
160
|
+
def load_from_dict(cls, state:dict):
|
161
|
+
new_state = load_dict_contains_nparray(state)
|
162
|
+
obj = cls(**new_state)
|
163
|
+
# for key in state:
|
164
|
+
# obj.__dict__[key] = state[key]
|
165
|
+
return obj
|
166
|
+
|
167
|
+
def copy(self):
|
168
|
+
new = DataRecord(
|
169
|
+
self.data.copy(),
|
170
|
+
self.stim_id,
|
171
|
+
copy.deepcopy(self.meta_info),
|
172
|
+
self.srate
|
173
|
+
)
|
174
|
+
return new
|
175
|
+
|
176
|
+
class Dataset:
|
177
|
+
|
178
|
+
# data and stim have the shape (nChannels, nSamples)
|
179
|
+
# stim_id_cond: used when stimuli contains multiple conditions
|
180
|
+
|
181
|
+
def __init__(self, name:str, srate:int):
|
182
|
+
self.name = name
|
183
|
+
self.srate = srate
|
184
|
+
self.stim_feat_filter:list = []
|
185
|
+
self.resp_chan_filter:list = []
|
186
|
+
self.stim_id_cond:str|None = None
|
187
|
+
self.meta_info_filter:dict = {}
|
188
|
+
self._stimuli_dict:dict = {}
|
189
|
+
self._records:List[DataRecord] = []
|
190
|
+
self._preprocess_config = {}
|
191
|
+
|
192
|
+
def copy(self):
|
193
|
+
new_dataset = Dataset(
|
194
|
+
self.name,
|
195
|
+
self.srate
|
196
|
+
)
|
197
|
+
new_dataset.stim_feat_filter = copy.deepcopy(self.stim_feat_filter)
|
198
|
+
new_dataset.resp_chan_filter = copy.deepcopy(self.resp_chan_filter)
|
199
|
+
new_dataset.stim_id_cond = copy.deepcopy(self.stim_id_cond)
|
200
|
+
new_dataset.meta_info_filter = copy.deepcopy(self.meta_info_filter)
|
201
|
+
new_dataset._stimuli_dict = self._stimuli_dict
|
202
|
+
new_dataset._records = [r_.copy() for r_ in self._records]
|
203
|
+
return new_dataset
|
204
|
+
|
205
|
+
@property
|
206
|
+
def stimuli_dict(self):
|
207
|
+
return self._stimuli_dict
|
208
|
+
|
209
|
+
@stimuli_dict.setter
|
210
|
+
def stimuli_dict(self, x):
|
211
|
+
self._stimuli_dict = _validate_stimuli_dict(x)
|
212
|
+
|
213
|
+
@property
|
214
|
+
def records(self) -> List[DataRecord]:
|
215
|
+
if len(self.meta_info_filter) == 0:
|
216
|
+
return self._records
|
217
|
+
else:
|
218
|
+
return self._filter_records_by_info(self._records, self.meta_info_filter)
|
219
|
+
|
220
|
+
def _filter_records_by_info(self, records, meta_info_filter:dict):
|
221
|
+
output = list()
|
222
|
+
for record in records:
|
223
|
+
if all(
|
224
|
+
[
|
225
|
+
record.meta_info[k] == v if np.isscalar(v)
|
226
|
+
else record.meta_info[k] in v
|
227
|
+
for k,v in meta_info_filter.items()
|
228
|
+
]
|
229
|
+
):
|
230
|
+
output.append(record)
|
231
|
+
return output
|
232
|
+
|
233
|
+
def append(self, record:DataRecord):
|
234
|
+
assert record.srate == self.srate
|
235
|
+
self._records.append(record)
|
236
|
+
|
237
|
+
def _filter_stim_feat(self, stim_feat):
|
238
|
+
new_stim_feat = {}
|
239
|
+
if len(self.stim_feat_filter) == 0:
|
240
|
+
stim_feat_filter = stim_feat.keys()
|
241
|
+
else:
|
242
|
+
stim_feat_filter = self.stim_feat_filter
|
243
|
+
for i in stim_feat_filter:
|
244
|
+
new_stim_feat[i] = stim_feat[i]
|
245
|
+
return new_stim_feat
|
246
|
+
|
247
|
+
def _filter_resp_chan(self, resp):
|
248
|
+
if len(self.resp_chan_filter) > 0:
|
249
|
+
idxArr = np.array(self.resp_chan_filter)
|
250
|
+
output = resp[idxArr,:]
|
251
|
+
else:
|
252
|
+
output = resp
|
253
|
+
return output
|
254
|
+
|
255
|
+
def __getitem__(self, idx):
|
256
|
+
record:DataRecord = self.records[idx]
|
257
|
+
return self._unpack_record(record)
|
258
|
+
|
259
|
+
def _unpack_record(self, record:DataRecord):
|
260
|
+
stim_id, data = record.stim_id, record.data
|
261
|
+
if isinstance(stim_id, dict):
|
262
|
+
assert self.stim_id_cond is not None
|
263
|
+
stim_id = stim_id[self.stim_id_cond]
|
264
|
+
stim_feat = self._filter_stim_feat(self.stimuli_dict[stim_id])
|
265
|
+
data = self._filter_resp_chan(data)
|
266
|
+
return stim_feat, data, record.meta_info
|
267
|
+
|
268
|
+
def __len__(self):
|
269
|
+
return len(self.records)
|
270
|
+
|
271
|
+
def __iter__(self):
|
272
|
+
self.n = 0
|
273
|
+
return self
|
274
|
+
|
275
|
+
def __next__(self):
|
276
|
+
if self.n < len(self.records):
|
277
|
+
self.n += 1
|
278
|
+
return self.__getitem__(self.n-1)#self.records[self.n-1]
|
279
|
+
else:
|
280
|
+
raise StopIteration
|
281
|
+
|
282
|
+
def to_pairs(self, ifT = True):
|
283
|
+
allSubj = set([i.meta_info['subj_id'] for i in self.records])
|
284
|
+
filterKey = lambda x: x.meta_info['subj_id']
|
285
|
+
sortKey = lambda x : (
|
286
|
+
x.meta_info['dataset_name'],
|
287
|
+
x.meta_info['subj_id'],
|
288
|
+
x.meta_info['trial_id'],
|
289
|
+
)
|
290
|
+
|
291
|
+
records = sorted(self.records, key = sortKey)
|
292
|
+
|
293
|
+
transpose = lambda *arrs: [arr.T for arr in arrs]
|
294
|
+
def catstimarr(stim:dict):
|
295
|
+
keys = stim.keys()
|
296
|
+
# print(keys)
|
297
|
+
assert all([stim[k].shape[0] < stim[k].shape[1] for k in keys if isinstance(stim[k], np.ndarray)])
|
298
|
+
stim = [stim[k] for k in keys if isinstance(stim[k], np.ndarray)]
|
299
|
+
stim = align_data(*stim)
|
300
|
+
stim = np.concatenate(stim, axis = 0)
|
301
|
+
# print(stim.shape)
|
302
|
+
return stim
|
303
|
+
|
304
|
+
stims_subj = []
|
305
|
+
resps_subj = []
|
306
|
+
infoss = []
|
307
|
+
ks = []
|
308
|
+
for k, grp in itertools.groupby(records, filterKey):
|
309
|
+
stims, resps, infos = list(zip(*[self._unpack_record(g) for g in grp]))
|
310
|
+
# print(infos)
|
311
|
+
stims = list(map(catstimarr, stims))
|
312
|
+
stims, resps = list(zip(*map(align_data, stims, resps)))
|
313
|
+
if ifT:
|
314
|
+
stims, resps = list(zip(*map(transpose, stims, resps)))
|
315
|
+
stims_subj.append(stims)
|
316
|
+
resps_subj.append(resps)
|
317
|
+
infoss.append(infos)
|
318
|
+
ks.append(k)
|
319
|
+
|
320
|
+
return stims_subj, resps_subj, ks, infoss
|
321
|
+
|
322
|
+
def to_pairs_iter(self,sortKey = None):
|
323
|
+
allSubj = set([i.meta_info['subj_id'] for i in self.records])
|
324
|
+
|
325
|
+
filterKey = lambda x: x.meta_info['subj_id']
|
326
|
+
if sortKey is None:
|
327
|
+
sortKey = lambda x : (
|
328
|
+
x.meta_info['dataset_name'],
|
329
|
+
x.meta_info['subj_id'],
|
330
|
+
x.meta_info['trial_id'],
|
331
|
+
)
|
332
|
+
|
333
|
+
records = sorted(self.records, key = sortKey)
|
334
|
+
|
335
|
+
for k, grp in itertools.groupby(records, filterKey):
|
336
|
+
stims, resps, infos = list(zip(*[self._unpack_record(g) for g in grp]))
|
337
|
+
yield stims, resps, infos, k
|
338
|
+
|
339
|
+
|
340
|
+
|
341
|
+
def k_fold(self, cur_fold, n_folds, split_by, add_dev = True, if_shuffle = False):
|
342
|
+
return k_fold(self, cur_fold, n_folds, split_by, add_dev=add_dev, if_shuffle = if_shuffle)
|
343
|
+
|
344
|
+
def subset_by_info(self,meta_info_filter):
|
345
|
+
records = self._filter_records_by_info(
|
346
|
+
self._records, meta_info_filter)
|
347
|
+
state_dict = self.dump()
|
348
|
+
state_dict['_records'] = [l.dump() for l in records]
|
349
|
+
return self.__class__.load(state_dict)
|
350
|
+
|
351
|
+
def dump_record(self, file_path, record:DataRecord):
|
352
|
+
with h5py.File(file_path, "a") as f:
|
353
|
+
data_record_to_h5py_group(
|
354
|
+
f = f,
|
355
|
+
**record.dump(),
|
356
|
+
)
|
357
|
+
|
358
|
+
def dump_attr(self, file_path):
|
359
|
+
with h5py.File(file_path, "a") as f:
|
360
|
+
f.attrs["name"] = self.name
|
361
|
+
f.attrs["srate"] = self.srate
|
362
|
+
preprocess_config = json.dumps(self._preprocess_config)
|
363
|
+
f.attrs["preprocess_config_str"] = preprocess_config
|
364
|
+
|
365
|
+
def dump(self, file_path):
|
366
|
+
with h5py.File(file_path, "w") as f:
|
367
|
+
f.attrs["name"] = self.name
|
368
|
+
f.attrs["srate"] = self.srate
|
369
|
+
preprocess_config = json.dumps(self._preprocess_config)
|
370
|
+
f.attrs["preprocess_config_str"] = preprocess_config
|
371
|
+
for record in self._records:
|
372
|
+
data_record_to_h5py_group(
|
373
|
+
f = f,
|
374
|
+
**record.dump(),
|
375
|
+
)
|
376
|
+
|
377
|
+
@classmethod
|
378
|
+
def load(cls, file_path):
|
379
|
+
new_dataset = None
|
380
|
+
with h5py.File(file_path, "r") as f:
|
381
|
+
new_dataset = cls(
|
382
|
+
name = str(f.attrs['name']),
|
383
|
+
srate = int(f.attrs['srate']),
|
384
|
+
)
|
385
|
+
for k, grp in f['records'].items():
|
386
|
+
record_dict = data_record_from_h5py_group(grp)
|
387
|
+
new_record = DataRecord(**record_dict)
|
388
|
+
new_dataset.append(new_record)
|
389
|
+
return new_dataset
|
390
|
+
|
391
|
+
def dump_to_dict(self):
|
392
|
+
output = {}
|
393
|
+
output['_records'] = [l.dump() for l in self._records]
|
394
|
+
for k,v in self.__dict__.items():
|
395
|
+
if k != '_records':
|
396
|
+
if isinstance(v, dict):
|
397
|
+
output[k] = dump_dict_contains_nparray(v)
|
398
|
+
else:
|
399
|
+
output[k] = v
|
400
|
+
return output
|
401
|
+
|
402
|
+
@classmethod
|
403
|
+
def load_from_dict(cls, state):
|
404
|
+
output = cls(name = state['name'], srate = state['srate'])
|
405
|
+
for k,v in state.items():
|
406
|
+
if k == '_records':
|
407
|
+
output.__dict__['_records'] = [DataRecord.load(l) for l in state[k]]
|
408
|
+
else:
|
409
|
+
if isinstance(v, dict):
|
410
|
+
output.__dict__[k] = load_dict_contains_nparray(v)
|
411
|
+
else:
|
412
|
+
output.__dict__[k] = state[k]
|
413
|
+
return output
|
414
|
+
|
415
|
+
@classmethod
|
416
|
+
def load_subject(cls, file_path, subject_id):
|
417
|
+
with h5py.File(file_path, "r") as f:
|
418
|
+
all_keys = list(f['records'].keys())
|
419
|
+
all_keys = sorted(all_keys, key = lambda x: [decode_record_key(x)[k] for k in META_INFO_FORCED_FIELD])
|
420
|
+
cnter = 1
|
421
|
+
new_dataset = cls(
|
422
|
+
name = str(f.attrs['name']),
|
423
|
+
srate = int(f.attrs['srate']),
|
424
|
+
)
|
425
|
+
for key_idx, key in enumerate(all_keys):
|
426
|
+
if decode_record_key(key)['subj_id'] == subject_id:
|
427
|
+
record_dict = data_record_from_h5py_group(f['records'][key])
|
428
|
+
new_record = DataRecord(**record_dict)
|
429
|
+
new_dataset.append(new_record)
|
430
|
+
return new_dataset
|
431
|
+
|
432
|
+
@classmethod
|
433
|
+
def iter_load(cls, file_path, n_subjs = 10):
|
434
|
+
with h5py.File(file_path, "r") as f:
|
435
|
+
all_keys = list(f['records'].keys())
|
436
|
+
all_keys = sorted(all_keys, key = lambda x: [decode_record_key(x)[k] for k in META_INFO_FORCED_FIELD])
|
437
|
+
# print(all_keys)
|
438
|
+
cnter = 1
|
439
|
+
new_dataset = cls(
|
440
|
+
name = str(f.attrs['name']),
|
441
|
+
srate = int(f.attrs['srate']),
|
442
|
+
)
|
443
|
+
for key_idx, key in enumerate(all_keys):
|
444
|
+
|
445
|
+
record_dict = data_record_from_h5py_group(f['records'][key])
|
446
|
+
new_record = DataRecord(**record_dict)
|
447
|
+
new_dataset.append(new_record)
|
448
|
+
|
449
|
+
|
450
|
+
if key_idx == len(all_keys)-1:
|
451
|
+
yield new_dataset
|
452
|
+
else:
|
453
|
+
current_subj_id = decode_record_key(key)['subj_id']
|
454
|
+
next_subj_id = decode_record_key(all_keys[key_idx+1])['subj_id']
|
455
|
+
|
456
|
+
if current_subj_id != next_subj_id:
|
457
|
+
if cnter >= n_subjs:
|
458
|
+
yield new_dataset
|
459
|
+
new_dataset = cls(
|
460
|
+
name = str(f.attrs['name']),
|
461
|
+
srate = int(f.attrs['srate']),
|
462
|
+
)
|
463
|
+
cnter = 1
|
464
|
+
else:
|
465
|
+
cnter += 1
|