pytour 3.0.0__tar.gz

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/LICENSE ADDED
@@ -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.
pytour-3.0.0/PKG-INFO ADDED
@@ -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
pytour-3.0.0/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # tour | 托
2
+ A framework for boosting the implementation of stimulus-response research code in the field of cognitive science and neuroscience
@@ -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,19 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ pytour.egg-info/PKG-INFO
5
+ pytour.egg-info/SOURCES.txt
6
+ pytour.egg-info/dependency_links.txt
7
+ pytour.egg-info/requires.txt
8
+ pytour.egg-info/top_level.txt
9
+ tests/test_dataset.py
10
+ tour/__init__.py
11
+ tour/artifacts_removal.py
12
+ tour/backend.py
13
+ tour/package_manage.py
14
+ tour/torch_trainer.py
15
+ tour/vis.py
16
+ tour/dataclass/__init__.py
17
+ tour/dataclass/dataset.py
18
+ tour/dataclass/io.py
19
+ tour/dataclass/stim.py
@@ -0,0 +1,5 @@
1
+ mne
2
+ numpy
3
+ scipy
4
+ matplotlib
5
+ h5py
@@ -0,0 +1 @@
1
+ tour
pytour-3.0.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
pytour-3.0.0/setup.py ADDED
@@ -0,0 +1,41 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Sat Aug 31 00:52:16 2019
4
+
5
+ @author: Jin Dou
6
+ """
7
+
8
+ import setuptools
9
+ import re
10
+
11
+ with open("./README.md", "r", encoding='UTF-8') as fh:
12
+ long_description = fh.read()
13
+
14
+ with open("tour/__init__.py") as file:
15
+ for line in file.readlines():
16
+ m = re.match("__version__ *= *['\"](.*)['\"]", line)
17
+ if m:
18
+ version = m.group(1)
19
+
20
+ setuptools.setup(
21
+ name="pytour",
22
+ version=version,
23
+ author="Powerfulbean",
24
+ author_email="powerfulbean@gmail.com",
25
+ long_description=long_description,
26
+ long_description_content_type="text/markdown",
27
+ url="https://github.com/powerfulbean/pytour",
28
+ packages=setuptools.find_packages(),
29
+ classifiers=[
30
+ "Programming Language :: Python :: 3",
31
+ "License :: OSI Approved :: MIT License",
32
+ "Operating System :: OS Independent",
33
+ ],
34
+ install_requires=[
35
+ "mne",
36
+ "numpy",
37
+ "scipy",
38
+ "matplotlib",
39
+ "h5py"
40
+ ],
41
+ )
@@ -0,0 +1,141 @@
1
+ import os
2
+ import mne
3
+ import h5py
4
+ import json
5
+ import numpy as np
6
+ from collections import OrderedDict
7
+ from StellarInfra import siIO
8
+ from tour.dataclass.io import (
9
+ mne_montage_to_h5py_group,
10
+ mne_montage_from_h5py_group,
11
+ data_record_from_h5py_group,
12
+ data_record_to_h5py_group,
13
+ stim_dict_to_hdf5,
14
+ stim_dict_from_hdf5
15
+ )
16
+ from tour.dataclass.dataset import Dataset, DataRecord
17
+ from StimRespFlow.DataStruct.DataSet import CDataSet, CDataRecord
18
+
19
+
20
+ current_folder = os.path.dirname(os.path.abspath(__file__))
21
+
22
+ def to_impulses(vectors, timestamps, f:float,padding_s = 0):
23
+ '''
24
+ # align the vectors into impulses with specific sampling rate
25
+ '''
26
+ startTimes = timestamps[0]
27
+ endTimes = timestamps[1]
28
+ secLen = endTimes[-1] + padding_s
29
+ nLen = np.ceil( secLen * f).astype(int)
30
+ nDim = vectors.shape[0]
31
+ out = np.zeros((nDim,nLen))
32
+
33
+ timeIndices = np.round(startTimes * f).astype(int)
34
+ out[:,timeIndices] = vectors
35
+ return out
36
+
37
+ def test_save_mne_montage():
38
+ output_fd = os.environ['box_root']
39
+ montage = mne.channels.make_standard_montage('biosemi128')
40
+ fig = montage.plot(show = False)
41
+ fig.savefig(f"{current_folder}/target_montage.png")
42
+ # pos_dict = montage.get_positions()
43
+ with h5py.File(f"{output_fd}/Collab-Project/CompiledDataset/biosemi128_montage.h5", "w") as f:
44
+ mne_montage_to_h5py_group(montage, f)
45
+
46
+ def test_load_montage_in_mne():
47
+ output_fd = os.environ['box_root']
48
+ with h5py.File(f"{output_fd}/Collab-Project/CompiledDataset/biosemi128_montage.h5", "r") as f:
49
+ montage = mne_montage_from_h5py_group(f)
50
+ fig = montage.plot(show = False)
51
+ fig.savefig(f"{current_folder}/loaded_montage.png")
52
+
53
+
54
+ data_path = f"{os.environ['box_root']}/Collab-Project/CompiledDataset/ns.pkl"
55
+ dataset:CDataSet = CDataSet.load(siIO.loadObject(data_path))
56
+ # print(dataset.records[0])
57
+
58
+
59
+ dataset_name = 'lalorlab_oldman'
60
+ dataset_new = Dataset(
61
+ name = dataset_name,
62
+ srate = dataset.srate
63
+ )
64
+
65
+ stim_dict = dataset.stimuliDict
66
+ old_stim_ids = list(stim_dict.keys())
67
+ for old_stim_id in old_stim_ids:
68
+ values = stim_dict[old_stim_id]
69
+ # print(old_stim_id, values.keys())
70
+ new_stim_id = old_stim_id.replace('phonemes','oldman')
71
+ words = values['words']
72
+ timeinfo = values['lex_sur']['timeinfo']
73
+ x = values['lex_sur']['x']
74
+ uniqueness_point = values['uni_pnt']['x']
75
+ values['lexical_surprisal'] = {
76
+ 'tag': words,
77
+ 'timeinfo': timeinfo,
78
+ 'x': x
79
+ }
80
+ values['uniqueness_point'] = {
81
+ 'tag': words,
82
+ 'timeinfo': timeinfo,
83
+ 'x': uniqueness_point
84
+ }
85
+ values['lexical_surprisal_fs64'] = to_impulses(
86
+ x,
87
+ timeinfo,
88
+ dataset.srate
89
+ )
90
+ ones = np.ones(x.shape)
91
+ # print(x.shape, timeinfo.shape)
92
+ values['word_onset_fs64'] = to_impulses(
93
+ ones,
94
+ timeinfo,
95
+ dataset.srate
96
+ )
97
+ values['envelope_fs64'] = values['env']
98
+ del values['lex_sur']
99
+ del values['onset']
100
+ del values['words']
101
+ del values['env']
102
+ del values['uni_pnt']
103
+ stim_dict[new_stim_id] = stim_dict[old_stim_id]
104
+ del stim_dict[old_stim_id]
105
+
106
+ # print(stim_dict)
107
+ for record in dataset.records:
108
+ record:CDataRecord
109
+ data = record.data
110
+ old_info = record.descInfo
111
+ stim_id = 'oldman' + str(old_info['stim'])
112
+ trial_id = old_info['stim']
113
+ subj_id = old_info['subj']
114
+ meta_info = dict(
115
+ subj_id = subj_id,
116
+ trial_id = trial_id,
117
+ dataset_name = dataset_name
118
+ )
119
+ record_new = DataRecord(
120
+ data,
121
+ stim_id,
122
+ meta_info,
123
+ srate = dataset.srate
124
+ )
125
+ dataset_new.append(record_new)
126
+
127
+
128
+ stim_dict_to_hdf5(
129
+ f"{os.environ['box_root']}/Collab-Project/CompiledDataset/ns_unipnt_lexsur_env_onset.h5",
130
+ stim_dict
131
+ )
132
+
133
+ stim_dict_new = stim_dict_from_hdf5(
134
+ f"{os.environ['box_root']}/Collab-Project/CompiledDataset/ns_unipnt_lexsur_env_onset.h5",
135
+ )
136
+
137
+ # test_save_mne_montage()
138
+ # test_load_montage_in_mne()
139
+
140
+ dataset_new.dump(f"{os.environ['box_root']}/Collab-Project/CompiledDataset/ns.h5")
141
+ new_dataset_new = Dataset.load(f"{os.environ['box_root']}/Collab-Project/CompiledDataset/ns.h5")
@@ -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
+
@@ -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