├── HDDM_Example
├── .local
│ └── share
│ │ └── jupyter
│ │ └── runtime
│ │ └── notebook_cookie_secret
├── Hddm_test_parallel.ipynb
├── Readme.txt
├── df_example.csv
└── hddm.yml
├── MNE_workshop
├── Behavioral
│ ├── all_raw_marker.csv
│ └── condition_marker
│ │ ├── 10_marker_lists.csv
│ │ └── 9_marker_lists.csv
├── README.md
├── Scripts
│ ├── ERP_plot_statisctics.py
│ ├── ERP_preprocessing_single_event.py
│ ├── __pycache__
│ │ ├── event_test.cpython-37.pyc
│ │ └── settings.cpython-37.pyc
│ ├── event_test.py
│ ├── list_rearrange.py
│ ├── mne_bids_test.py
│ └── settings.py
└── example_scripts.ipynb
├── Machine_learning_in_neuroimaging_using_python_LiChao
├── .ipynb_checkpoints
│ └── workshop-checkpoint.ipynb
├── BNA_subregions.xlsx
├── README.html
├── README.md
├── classification_performances.pdf
├── easylearn交流群.jpg
├── easylearn操作视频.zip
├── fc_triu.npy
├── outputs.pickle
├── requirements.txt
├── szVShc.json
├── targets.xlsx
├── workshop.ipynb
├── workshop.py
└── 一般流程.png
├── PsychoPy
├── Python在实验程序编写中的应用——Ryan.pdf
├── ReadMe.md
├── gonogo.psyexp
├── gonogo.py
├── gonogo_test.py
├── stimuli_list.xlsx
├── stroop.psyexp
├── 微信公众号.png
├── 扫码_搜索联合传播样式-微信标准绿版.png
└── 群二维码.png
├── PythonPipeline_DataAnalysis_Psychology_HaiyangGeng
├── PythonPipeline_DataAnalysis_Psychology_DemoCode1118.ipynb
├── README.md
├── SE-QPE_40_demo1118.xlsx
├── SE_all_demo1118.xlsx
├── SE_basic_infor_demo1118.xlsx
└── SE_scale_demo1118.xlsx
├── README.md
└── fMRIPrep
├── README.md
├── ds003030_select
├── CHANGES
├── dataset_description.json
├── participants.tsv
├── sub-01
│ ├── anat
│ │ ├── sub-01_T1w.json
│ │ └── sub-01_T1w.nii.gz
│ └── func
│ │ ├── sub-01_task-FlickeringCheckerBoard_run-1_bold.json
│ │ ├── sub-01_task-FlickeringCheckerBoard_run-1_bold.nii.gz
│ │ └── sub-01_task-FlickeringCheckerBoard_run-1_events.tsv
└── sub-02
│ ├── anat
│ ├── sub-02_T1w.json
│ └── sub-02_T1w.nii.gz
│ └── func
│ ├── sub-02_task-FlickeringCheckerBoard_run-1_bold.json
│ ├── sub-02_task-FlickeringCheckerBoard_run-1_bold.nii.gz
│ └── sub-02_task-FlickeringCheckerBoard_run-1_events.tsv
└── output
└── README.md
/HDDM_Example/.local/share/jupyter/runtime/notebook_cookie_secret:
--------------------------------------------------------------------------------
1 | MPSqnBJKX0wU1bho9V4kA2c4pUvtlMIp4vbP6QklcV8=
2 |
--------------------------------------------------------------------------------
/HDDM_Example/Readme.txt:
--------------------------------------------------------------------------------
1 | Please visit here for the installation of docker image of HDDM:
2 | https://github.com/hcp4715/hddm_docker
3 |
--------------------------------------------------------------------------------
/HDDM_Example/hddm.yml:
--------------------------------------------------------------------------------
1 | name: hddm
2 | channels:
3 | - conda-forge
4 | - defaults
5 | dependencies:
6 | - _libgcc_mutex=0.1=main
7 | - attrs=19.3.0=py_0
8 | - backcall=0.1.0=py37_0
9 | - blas=1.0=mkl
10 | - bleach=3.1.4=py_0
11 | - ca-certificates=2020.1.1=0
12 | - certifi=2020.4.5.1=py37_0
13 | - dbus=1.13.14=hb2f20db_0
14 | - decorator=4.4.2=py_0
15 | - defusedxml=0.6.0=py_0
16 | - entrypoints=0.3=py37_0
17 | - expat=2.2.6=he6710b0_0
18 | - fontconfig=2.13.0=h9420a91_0
19 | - freetype=2.9.1=h8a8886c_1
20 | - glib=2.63.1=h3eb4bd4_1
21 | - gmp=6.1.2=h6c8ec71_1
22 | - gst-plugins-base=1.14.0=hbbd80ab_1
23 | - gstreamer=1.14.0=hb31296c_0
24 | - icu=58.2=he6710b0_3
25 | - importlib-metadata=1.6.0=py37_0
26 | - importlib_metadata=1.6.0=0
27 | - intel-openmp=2020.1=217
28 | - ipykernel=5.1.4=py37h39e3cac_0
29 | - ipyparallel=6.3.0=py37hc8dfbb8_0
30 | - ipython=7.13.0=py37h5ca1d4c_0
31 | - ipython_genutils=0.2.0=py37_0
32 | - ipywidgets=7.5.1=py_0
33 | - jedi=0.17.0=py37_0
34 | - jinja2=2.11.2=py_0
35 | - jpeg=9b=h024ee3a_2
36 | - jsonschema=3.2.0=py37_0
37 | - jupyter=1.0.0=py37_7
38 | - jupyter_client=6.1.3=py_0
39 | - jupyter_console=6.1.0=py_0
40 | - jupyter_core=4.6.3=py37_0
41 | - kiwisolver=1.2.0=py37hfd86e86_0
42 | - ld_impl_linux-64=2.33.1=h53a641e_7
43 | - libedit=3.1.20181209=hc058e9b_0
44 | - libffi=3.3=he6710b0_1
45 | - libgcc-ng=9.1.0=hdf63c60_0
46 | - libgfortran-ng=7.3.0=hdf63c60_0
47 | - libpng=1.6.37=hbc83047_0
48 | - libsodium=1.0.16=h1bed415_0
49 | - libstdcxx-ng=9.1.0=hdf63c60_0
50 | - libuuid=1.0.3=h1bed415_2
51 | - libxcb=1.13=h1bed415_1
52 | - libxml2=2.9.9=hea5a465_1
53 | - markupsafe=1.1.1=py37h7b6447c_0
54 | - matplotlib-base=3.1.3=py37hef1b27d_0
55 | - mistune=0.8.4=py37h7b6447c_0
56 | - mkl=2020.1=217
57 | - mkl-service=2.3.0=py37he904b0f_0
58 | - mkl_fft=1.0.15=py37ha843d7b_0
59 | - mkl_random=1.1.1=py37h0573a6f_0
60 | - nbconvert=5.6.1=py37_0
61 | - nbformat=5.0.6=py_0
62 | - ncurses=6.2=he6710b0_1
63 | - notebook=6.0.3=py37_0
64 | - numpy-base=1.18.1=py37hde5b4d6_1
65 | - openssl=1.1.1g=h7b6447c_0
66 | - pandoc=2.2.3.2=0
67 | - pandocfilters=1.4.2=py37_1
68 | - parso=0.7.0=py_0
69 | - pcre=8.43=he6710b0_0
70 | - pexpect=4.8.0=py37_0
71 | - pickleshare=0.7.5=py37_0
72 | - pip=20.0.2=py37_3
73 | - prometheus_client=0.7.1=py_0
74 | - prompt-toolkit=3.0.5=py_0
75 | - prompt_toolkit=3.0.5=0
76 | - ptyprocess=0.6.0=py37_0
77 | - pymc==2.3.8
78 | - pygments=2.6.1=py_0
79 | - pyparsing=2.4.7=py_0
80 | - pyqt=5.9.2=py37h05f1152_2
81 | - pyrsistent=0.16.0=py37h7b6447c_0
82 | - python=3.7.7=hcff3b4d_5
83 | - python-dateutil=2.8.1=py_0
84 | - python_abi=3.7=1_cp37m
85 | - pytz=2020.1=py_0
86 | - pyzmq=18.1.1=py37he6710b0_0
87 | - qt=5.9.7=h5867ecd_1
88 | - qtconsole=4.7.4=py_0
89 | - qtpy=1.9.0=py_0
90 | - readline=8.0=h7b6447c_0
91 | - scipy=1.4.1=py37h0b6359f_0
92 | - seaborn=0.10.1=py_0
93 | - send2trash=1.5.0=py37_0
94 | - setuptools=46.4.0=py37_0
95 | - sip=4.19.8=py37hf484d3e_0
96 | - sqlite=3.31.1=h62c20be_1
97 | - terminado=0.8.3=py37_0
98 | - testpath=0.4.4=py_0
99 | - tk=8.6.8=hbc83047_0
100 | - tornado=6.0.4=py37h7b6447c_1
101 | - traitlets=4.3.3=py37_0
102 | - wcwidth=0.1.9=py_0
103 | - webencodings=0.5.1=py37_1
104 | - wheel=0.34.2=py37_0
105 | - widgetsnbextension=3.5.1=py37_0
106 | - xz=5.2.5=h7b6447c_0
107 | - zeromq=4.3.1=he6710b0_3
108 | - zipp=3.1.0=py_0
109 | - zlib=1.2.11=h7b6447c_3
110 | - pip:
111 | - cycler==0.10.0
112 | - hddm==0.8.0
113 | - kabuki==0.6.3
114 | - matplotlib==3.2.1
115 | - numpy==1.18.5
116 | - pandas==1.0.4
117 | - patsy==0.5.1
118 | - six==1.15.0
119 |
120 |
--------------------------------------------------------------------------------
/MNE_workshop/Behavioral/all_raw_marker.csv:
--------------------------------------------------------------------------------
1 | trigger
2 | 1
3 | 2
4 | 3
5 | 4
6 | 5
7 | 6
8 | 7
9 | 8
10 | 9
11 | 10
12 | 11
13 | 12
14 | 13
15 | 14
16 | 15
17 | 16
18 | 17
19 | 18
20 | 19
21 | 20
22 | 21
23 | 22
24 | 23
25 | 24
26 | 25
27 | 26
28 | 27
29 | 28
30 | 29
31 | 30
32 | 31
33 | 32
34 | 33
35 | 34
36 | 35
37 | 36
38 |
--------------------------------------------------------------------------------
/MNE_workshop/Behavioral/condition_marker/10_marker_lists.csv:
--------------------------------------------------------------------------------
1 | Positive,Control,Cue_only
2 | 17,32,9
3 | 19,33,11
4 | 14,28,10
5 | 22,29,8
6 | 21,34,1
7 | 15,27,2
8 | 13,31,7
9 | 16,26,12
10 | 18,30,6
11 | 24,25,5
12 | 20,35,4
13 | 23,36,3
14 |
--------------------------------------------------------------------------------
/MNE_workshop/Behavioral/condition_marker/9_marker_lists.csv:
--------------------------------------------------------------------------------
1 | Positive,Control,Cue_only
2 | 35,5,14
3 | 32,4,18
4 | 30,6,21
5 | 27,1,17
6 | 36,10,19
7 | 33,11,20
8 | 31,7,15
9 | 34,2,23
10 | 28,8,24
11 | 29,9,13
12 | 26,3,16
13 | 25,12,22
14 |
--------------------------------------------------------------------------------
/MNE_workshop/README.md:
--------------------------------------------------------------------------------
1 | MNE-Python MNE-BIDS ERP工作坊
2 |
3 | MNE-Python的安装 https://mne.tools/stable/install/mne_python.html
4 |
5 | MNE-BIDS的安装 https://mne.tools/mne-bids/stable/index.html
6 |
7 | MNElab的安装 https://github.com/cbrnr/mnelab
8 |
9 | MNE-BIDS demo数据下载链接: https://pan.baidu.com/s/16T6MGoi_ydXe7or5Dnl9Tg 提取码: yvjj
10 |
--------------------------------------------------------------------------------
/MNE_workshop/Scripts/ERP_plot_statisctics.py:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | import mne
5 | import pandas as pd
6 | import os
7 | import settings
8 |
9 |
10 | #%%
11 | os.chdir(settings.base_dir_init())
12 |
13 | epoch_fname=('Raw_data/epochs/')
14 |
15 | epochs_list=os.listdir(epoch_fname)
16 | condition_marker_file=os.listdir('Behavioral/condition_marker/')
17 | condition_marker=pd.read_csv('Behavioral/condition_marker/' + condition_marker_file[0])
18 | conditions=condition_marker.columns.values
19 | #%%
20 | evoked_list1=[]
21 | evoked_list2=[]
22 | evoked_list3=[]
23 |
24 | condition_list=[evoked_list1,evoked_list2,evoked_list3]
25 |
26 | for i in range(0,len(epochs_list))[0:7]:
27 | epochs=mne.read_epochs(epoch_fname+epochs_list[i],preload=True)
28 | epochs.apply_baseline(baseline=(None,0))
29 | for j in conditions:
30 | q=j + '_evoked'
31 | globals()[q]=epochs[j].average()
32 |
33 | for k,j in zip(condition_list,conditions):
34 | k.append(globals()[j+'_evoked'])
35 |
36 |
37 | picks=[epochs.ch_names.index(ch)for ch in ['Oz','POz','O1','O2']]
38 | condition_index={'Positive':evoked_list1,'Control':evoked_list2,'Cue_only':evoked_list3}
39 | mne.viz.plot_compare_evokeds(condition_index,picks=picks,ci=None,combine='mean',show_sensors='upper right')
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/MNE_workshop/Scripts/ERP_preprocessing_single_event.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Created on Mon Sep 28 22:51:24 2020
4 |
5 | @author: Xia Tao
6 | """
7 | #%% import the module that will be used
8 | #%matplotlib qt
9 | import mne
10 | import os
11 | from mne.preprocessing import (ICA, create_eog_epochs)
12 | from mne_bids import read_raw_bids, BIDSPath
13 | from autoreject import Ransac #
14 | from autoreject.utils import interpolate_bads #
15 | from pyprep.find_noisy_channels import NoisyChannels
16 | import pandas as pd
17 | import numpy as np
18 | import settings
19 | import event_test
20 | #%% define the data path##
21 |
22 |
23 | subjetc_file=settings.bids_root_path_init()
24 | marker_file=settings.marker_list_path_init()
25 |
26 | os.chdir(settings.base_dir_init())
27 |
28 | os.makedirs('Raw_data/raw_ica/',exist_ok=True)
29 | os.makedirs('Raw_data/epochs/',exist_ok=True)
30 | #%% read the subject list from mne-bids path and remove the participants that predefined
31 | raw_files=os.listdir(subjetc_file)
32 | raw_file_list=[]
33 | for raw_file in raw_files:
34 | if raw_file.split('-')[0]=='sub':
35 | raw_file_list.append(raw_file)
36 |
37 | for i in settings.rm_sub_list:
38 | raw_file_list.remove(i)
39 |
40 | #%%
41 | marker_lists=pd.read_csv('Behavioral/all_raw_marker.csv')['trigger'].to_list()
42 |
43 | raw_events_id=event_test.raw_marker_create(marker_list=marker_lists)
44 |
45 | condition_marker_file=os.listdir('Behavioral/condition_marker/')
46 |
47 | #%%
48 | for q in range(0,len(raw_file_list)):
49 | subject_id=raw_file_list[q].split('-')[1]
50 | bids_path = BIDSPath(subject=subject_id, task=settings.task, root=settings.bids_root_path_init(),session=settings.session,datatype='eeg',suffix='eeg')
51 | raw=read_raw_bids(bids_path=bids_path,extra_params=dict(preload=True))
52 | raw.info['bads']=['FT7','FT8','T7','T8','TP7','TP8','AF7','AF8','M1','M2','BIP1','BIP2','BIP3','BIP4','BIP5','BIP6','BIP7','BIP8','BIP9','BIP10','BIP11','BIP12','BIP13','BIP14',
53 | 'BIP15','BIP16','BIP17','BIP18','BIP19','BIP20','BIP21','BIP22','BIP23','BIP24']
54 | raw.drop_channels(ch_names=raw.info['bads'])
55 | montage=mne.channels.make_standard_montage('standard_1020')
56 | raw.set_montage(montage)
57 | filt_raw=raw.copy()
58 | filt_raw.drop_channels('EOG')
59 | nd=NoisyChannels(filt_raw)
60 | nd.find_bad_by_ransac(n_samples=50,channel_wise=True)
61 | raw.info['bads']=nd.bad_by_ransac
62 | raw.notch_filter(np.arange(50,250,50))
63 | filt_raw.notch_filter(np.arange(50,250,50))
64 | raw.filter(l_freq=settings.high_filter,h_freq=settings.low_filter,fir_design='firwin')
65 | filt_raw.filter(l_freq=1, h_freq=settings.low_filter)
66 | filt_raw.info['bads']=raw.info['bads']
67 | raw.interpolate_bads(reset_bads=True,mode='accurate')
68 | filt_raw.interpolate_bads(reset_bads=True,mode='accurate')
69 | raw.resample(200,npad='auto')
70 | filt_raw.resample(200,npad='auto')
71 | raw.set_eeg_reference('average')
72 | filt_raw.set_eeg_reference('average')
73 | eog_evoked = create_eog_epochs(raw).average()
74 | raw.plot(block=True,n_channels=31,duration=30)
75 | ica=ICA(n_components=53,method='picard').fit(filt_raw, reject_by_annotation=True)
76 | eog_indices, eog_scores=ica.find_bads_eog(raw,threshold=0.2,measure='correlation')
77 | ica.exclude = eog_indices
78 | ica.plot_scores(eog_scores,exclude=ica.exclude,axhline=[-0.2,0.2],labels='eog')
79 | ica.plot_properties(raw, picks=eog_indices)
80 | ica.plot_sources(raw,block=True)
81 | ica.plot_sources(eog_evoked)
82 | ica.plot_sources(raw,block=True)
83 | ica.plot_overlay(raw,picks='eeg')
84 | ica.apply(raw)
85 | raw.save('Raw_data/raw_ica/'+raw_file_list[q]+'_raw.fif',overwrite=True)
86 | events,events_id=mne.events_from_annotations(raw,event_id=raw_events_id)
87 | condition_marker=pd.read_csv('Behavioral/condition_marker/' + condition_marker_file[q])
88 | conditions=condition_marker.columns.values
89 | new_events,new_marker_list=event_test.event_operation(events,conditions_name=conditions,condition_marker=condition_marker)
90 | new_marker_list=list(set(new_marker_list))
91 | new_events_id=dict(zip(conditions.tolist(),new_marker_list))
92 | epochs=mne.Epochs(raw,events=new_events,event_id=new_events_id,baseline=None,preload=True,
93 | tmin=settings.epochs_tmin,tmax=settings.epochs_tmax,reject=dict(eeg=300e-6),flat=dict(eeg=1e-6))
94 | epochs.plot(block=True)
95 | epochs.save('Raw_data/epochs/' + raw_file_list[q] +'-epo.fif',overwrite=True)
96 |
97 |
98 |
99 |
--------------------------------------------------------------------------------
/MNE_workshop/Scripts/__pycache__/event_test.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/MNE_workshop/Scripts/__pycache__/event_test.cpython-37.pyc
--------------------------------------------------------------------------------
/MNE_workshop/Scripts/__pycache__/settings.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/MNE_workshop/Scripts/__pycache__/settings.cpython-37.pyc
--------------------------------------------------------------------------------
/MNE_workshop/Scripts/event_test.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Created on Mon Nov 2 21:40:12 2020
4 |
5 | @author: Tao XIA
6 | """
7 |
8 | def event_operation(raw_events,conditions_name,condition_marker):
9 | j=0
10 | new_marker_list=[]
11 | new_events=[]
12 | while j < len(conditions_name):
13 | for i in range(0,len(raw_events)):
14 | print(i)
15 | if raw_events[i][2] in condition_marker[conditions_name[j]].to_list():
16 | raw_events[i][2]=j+200
17 | new_marker_list.append(j+200)
18 | new_events.append(raw_events[i])
19 | j=j+1
20 | return new_events,new_marker_list
21 |
22 | def raw_marker_create(marker_list):
23 | key_list=[]
24 | for j in marker_list:
25 | b='Stimulus/s'+str(j)
26 | key_list.append(b)
27 |
28 | event_ids=dict(zip(key_list,marker_list))
29 | return event_ids
30 |
--------------------------------------------------------------------------------
/MNE_workshop/Scripts/list_rearrange.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Created on Thu Nov 12 10:58:33 2020
4 |
5 | @author: Psychology
6 | """
7 |
8 | import os
9 | import pandas as pd
10 | import numpy as np
11 | import settings
12 | import re
13 |
14 |
15 | os.chdir(settings.base_dir_init())
16 | marker_fname=('behavioral_data/data/lists/')
17 |
18 | marker_files=os.listdir(marker_fname)
19 | marker_file_list=[]
20 | for marker_file in marker_files:
21 | if os.path.splitext(marker_file)[1]=='.csv':
22 | marker_file_list.append(marker_file)
23 |
24 | positive_list=[]
25 | control_list=[]
26 | cue_only_list=[]
27 | for positive in marker_file_list:
28 | if positive.find('positive')==7 or positive.find('positive')==6:
29 | positive_list.append(positive)
30 | for control in marker_file_list:
31 | if control.find('control')==7 or control.find('control')==6:
32 | control_list.append(control)
33 | for cue in marker_file_list:
34 | if cue.find('cue')==7 or cue.find('cue')==6:
35 | cue_only_list.append(cue)
36 |
37 | for i in range(0,len(positive_list)):
38 | all_conditions=pd.DataFrame(columns=['Positive','Control','Cue_only'])
39 | all_conditions['Positive']=pd.read_csv(marker_fname + positive_list[i])['cue_trigger']
40 | all_conditions['Control']=pd.read_csv(marker_fname + control_list[i])['cue_trigger']
41 | all_conditions['Cue_only']=pd.read_csv(marker_fname + cue_only_list[i])['trigger_learn']
42 | subject_id=re.findall('(\d+)',positive_list[i])[0]
43 | all_conditions.to_csv('Behavioral/condition_marker/'+ subject_id +'_marker_lists.csv',index=False)
--------------------------------------------------------------------------------
/MNE_workshop/Scripts/mne_bids_test.py:
--------------------------------------------------------------------------------
1 | #%%
2 | #%matplotlib qt
3 | import mne
4 | import os
5 | from mne_bids import write_raw_bids, BIDSPath,make_dataset_description
6 | import re
7 | import settings
8 | import event_test
9 | import pandas as pd
10 | #%%
11 | subjetc_file=settings.subject_path_init()
12 | os.chdir(settings.base_dir_init())
13 | #%%
14 |
15 | raw_files=os.listdir(subjetc_file)
16 | raw_file_list=[]
17 | marker_lists=pd.read_csv('Behavioral/all_raw_marker.csv')['trigger'].to_list()
18 | event_ids=event_test.raw_marker_create(marker_lists)
19 |
20 | for raw_file in raw_files:
21 | if os.path.splitext(raw_file)[1]=='.vhdr':
22 | raw_file_list.append(raw_file)
23 | #%%
24 | for q in range(0,len(raw_file_list)):
25 |
26 | raw=mne.io.read_raw_brainvision(os.path.join(subjetc_file,raw_file_list[q]),preload=False)
27 | # if len(raw.info['ch_names'])>60:
28 | # raw.info['bads']=['BIP1','BIP2','BIP3','BIP4','BIP5','BIP6','BIP7','BIP8','BIP9','BIP10','BIP11','BIP12','BIP13','BIP14',
29 | # 'BIP15','BIP16','BIP17','BIP18','BIP19','BIP20','BIP21','BIP22','BIP23','BIP24']
30 | # raw.drop_channels(ch_names=raw.info['bads'])
31 | raw.info['line_freq'] = 50
32 | raw.set_channel_types(mapping={'EOG':'eog'})
33 | # montage=mne.channels.make_standard_montage('standard_1020')
34 | # raw.set_montage(montage)
35 | subject_id=re.findall('(\d+)',raw_file_list[q])[0]
36 | bids_path = BIDSPath(subject=subject_id, task=settings.task, root=settings.bids_root_path_init(),session=settings.session,datatype='eeg',suffix='eeg')
37 | #events,events_id=mne.events_from_annotations(raw,event_id=event_ids)
38 | write_raw_bids(raw, bids_path,overwrite=True)
39 |
40 | make_dataset_description(path=settings.bids_root_path_init(),name=settings.project_name,authors=settings.authors,
41 | acknowledgements=settings.acknowledgements,funding=settings.funding_support,overwrite=True)
42 |
43 |
--------------------------------------------------------------------------------
/MNE_workshop/Scripts/settings.py:
--------------------------------------------------------------------------------
1 | import os
2 | import numpy as np
3 | import pandas as pd
4 | #%% ###### DIRECTORY STRUCTURE ######
5 | def base_dir_init(): # Base directory for EEG analysis
6 | base_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
7 | return base_dir
8 |
9 | def script_path_init():
10 | script_path = base_dir_init() + '\Scripts'
11 | return script_path
12 |
13 | def bids_root_path_init():
14 | bids_path = base_dir_init() + '\mne_bids'
15 | return bids_path
16 |
17 | def subject_path_init(): # Subjects directory, for storing EEG data
18 | subject_path = base_dir_init() + '\Raw_data'
19 | return subject_path
20 |
21 | def marker_list_path_init():
22 | marker_path = base_dir_init() + "\Behaviorl"
23 | return marker_path
24 |
25 | if __name__ == '__main__':
26 | base_dir = base_dir_init()
27 | print('====== Current directory ======')
28 | print(base_dir)
29 |
30 |
31 | #%% remove the data that did not meet your criteria, you shoudl use the "sub-number" to represent the subjects no matter the filename of your data#
32 |
33 | rm_sub_list=['sub-01','sub-02','sub-04','sub-05','sub-06','sub-12','sub-17','sub-19','sub-21','sub-25','sub-32','sub-37','sub-39']
34 |
35 |
36 | #%% ###################First we need to convert our raw EEG data into a BIDS-compliant folder structure##############
37 | #######################In this section we need define the following parameters for data description##################
38 |
39 |
40 | task='ForcedChioce'
41 |
42 | session='3'
43 |
44 |
45 | project_name='Sleep_learning_Forced_chioce_task'
46 |
47 | authors='Tao Xia, Xiaoqing Hu'
48 |
49 | acknowledgements='The authors would like to thank the subjects for their participantion'
50 |
51 | funding_support='GRF1004'
52 |
53 | #################let's define the dict object of events_ids for MNE analysis############
54 | #marker_lists=pd.read_csv('Behavioral/all_raw_marker.csv')['trigger'].to_list() # to do: events operation
55 |
56 | low_filter=30
57 | high_filter=0.1
58 |
59 | epochs_tmin=-0.2
60 | epochs_tmax=1
61 |
62 |
63 |
64 | # %%
65 |
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/BNA_subregions.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/Machine_learning_in_neuroimaging_using_python_LiChao/BNA_subregions.xlsx
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/README.html:
--------------------------------------------------------------------------------
1 |
READMEPython在神经影像机器学习中的应用
1059 |
1060 | 作者:黎超
1061 | Email: lichao19870617@163.com
1062 | easylearn为一站式机器学习图形界面软件,网址:https://github.com/lichao312214129/easylearn
1063 | easylearn微信交流群:
1064 |
1065 |
1066 | 神经影像机器学习一般流程
1067 | 链接:https://www.processon.com/view/link/5fb4f37a1e085368771b301a
1068 | 微信二维码:
1069 |
1070 | 密码:F5tU
1071 | 文件说明
1072 |
1073 | -
1074 |
fc_triu.npy 为145个人的功能连接矩阵,其中71个精神分裂症患者,74个正常对照。功能连接矩阵为246个节点间的时间序列的Pearson’s相关矩阵,我只纳入了上三角部分,共30135(246*245/2)个特征。 [注:文件名一定要和targets.xlsx中的ID对应]
1075 |
1076 | -
1077 |
若想获取 fc_triu.npy 的原始246*246的数据,请转到百度云盘下载链接:https://pan.baidu.com/s/177aIKoxuZWDUTMVxW5kw8Q
1078 | 提取码:doey
1079 |
1080 | -
1081 |
targets.xlsx 为每个被试对应的ID/唯一识别码/唯一名称和类别,0为正常,1为精神分裂症
1082 |
1083 | -
1084 |
BNA_subregions.xlsx 为脑246分区的信息[http://atlas.brainnetome.org/]
1085 |
1086 | -
1087 |
workshop.ipynb 为演示代码的jupyter-n*otebook版本
1088 |
1089 | -
1090 |
workshop.py 为演示代码的普通版本
1091 |
1092 | -
1093 |
requirements.txt 为项目依赖的Python包
1094 |
1095 | -
1096 |
easylearn操作视频.zip 为使用easylearn图形界面完成精神分裂症诊断的操作视频
1097 |
1098 | -
1099 |
注:Demo数据为COBRE数据集 http://fcon_1000.projects.nitrc.org/indi/retro/cobre.html
1100 |
1101 |
1102 | 版本
1103 | Python3.7
1104 | 依赖包
1105 | os
1106 | scipy
1107 | pandas
1108 | numpy
1109 | matplotlib
1110 | seaborn
1111 | collections
1112 | scikit-learn
1113 | nilearn
1114 | pyecharts
1115 | jupyter
1116 | 安装方法
1117 | 切换到本目录,在终端使用如下命令安装所有依赖
1118 | pip install -r requirements.txt
1119 | easylearn安装方法
1120 | pip install eslearn
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/README.md:
--------------------------------------------------------------------------------
1 | # Python在神经影像机器学习中的应用
2 | > 作者:黎超
3 | > Email: lichao19870617@163.com
4 | > easylearn为一站式机器学习图形界面软件,网址:https://github.com/lichao312214129/easylearn
5 | > easylearn微信交流群:
6 | >
7 |
8 | ### 神经影像机器学习一般流程
9 | 链接:https://www.processon.com/view/link/5fb4f37a1e085368771b301a
10 | 微信二维码:
11 |
12 | **密码:F5tU**
13 |
14 | ### 文件说明
15 | - *fc_triu.npy* 为145个人的功能连接矩阵,其中71个精神分裂症患者,74个正常对照。功能连接矩阵为246个节点间的时间序列的Pearson's相关矩阵,我只纳入了上三角部分,共30135(246*245/2)个特征。 [注:文件名一定要和targets.xlsx中的ID对应]
16 |
17 | - 若想获取 *fc_triu.npy* 的原始246*246的数据,请转到百度云盘下载链接:https://pan.baidu.com/s/177aIKoxuZWDUTMVxW5kw8Q
18 | 提取码:doey
19 |
20 | - *targets.xlsx* 为每个被试对应的ID/唯一识别码/唯一名称和类别,0为正常,1为精神分裂症
21 |
22 | - *BNA_subregions.xlsx* 为脑246分区的信息[http://atlas.brainnetome.org/]
23 |
24 | - *workshop.ipynb* 为演示代码的jupyter-n*otebook版本
25 |
26 | - *workshop.py* 为演示代码的普通版本
27 |
28 | - *requirements.txt* 为项目依赖的Python包
29 |
30 | - *easylearn操作视频.zip* 为使用easylearn图形界面完成精神分裂症诊断的操作视频
31 |
32 | - 注:Demo数据为COBRE数据集
33 |
34 | ### 版本
35 | Python3.7
36 |
37 | ### 依赖包
38 | os
39 | scipy
40 | pandas
41 | numpy
42 | matplotlib
43 | seaborn
44 | collections
45 | scikit-learn
46 | nilearn
47 | pyecharts
48 | jupyter
49 |
50 | #### 安装方法
51 | 切换到本目录,在终端使用如下命令安装所有依赖
52 | `pip install -r requirements.txt`
53 |
54 | #### easylearn安装方法
55 | `pip install eslearn`
56 |
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/classification_performances.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/Machine_learning_in_neuroimaging_using_python_LiChao/classification_performances.pdf
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/easylearn交流群.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/Machine_learning_in_neuroimaging_using_python_LiChao/easylearn交流群.jpg
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/easylearn操作视频.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/Machine_learning_in_neuroimaging_using_python_LiChao/easylearn操作视频.zip
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/fc_triu.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/Machine_learning_in_neuroimaging_using_python_LiChao/fc_triu.npy
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/outputs.pickle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/Machine_learning_in_neuroimaging_using_python_LiChao/outputs.pickle
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/requirements.txt:
--------------------------------------------------------------------------------
1 | os
2 | scipy
3 | pandas
4 | numpy
5 | matplotlib
6 | seaborn
7 | collections
8 | scikit-learn
9 | nilearn
10 | pyecharts
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/szVShc.json:
--------------------------------------------------------------------------------
1 | {
2 | "data_loading": {
3 | "whole": {
4 | "modalities": {
5 | "fc": {
6 | "file": [
7 | "F:/workshop/demo_data/data/sub-40000.mat",
8 | "F:/workshop/demo_data/data/sub-40001.mat",
9 | "F:/workshop/demo_data/data/sub-40002.mat",
10 | "F:/workshop/demo_data/data/sub-40003.mat",
11 | "F:/workshop/demo_data/data/sub-40004.mat",
12 | "F:/workshop/demo_data/data/sub-40005.mat",
13 | "F:/workshop/demo_data/data/sub-40006.mat",
14 | "F:/workshop/demo_data/data/sub-40007.mat",
15 | "F:/workshop/demo_data/data/sub-40008.mat",
16 | "F:/workshop/demo_data/data/sub-40009.mat",
17 | "F:/workshop/demo_data/data/sub-40010.mat",
18 | "F:/workshop/demo_data/data/sub-40011.mat",
19 | "F:/workshop/demo_data/data/sub-40012.mat",
20 | "F:/workshop/demo_data/data/sub-40013.mat",
21 | "F:/workshop/demo_data/data/sub-40014.mat",
22 | "F:/workshop/demo_data/data/sub-40015.mat",
23 | "F:/workshop/demo_data/data/sub-40016.mat",
24 | "F:/workshop/demo_data/data/sub-40017.mat",
25 | "F:/workshop/demo_data/data/sub-40018.mat",
26 | "F:/workshop/demo_data/data/sub-40019.mat",
27 | "F:/workshop/demo_data/data/sub-40020.mat",
28 | "F:/workshop/demo_data/data/sub-40021.mat",
29 | "F:/workshop/demo_data/data/sub-40022.mat",
30 | "F:/workshop/demo_data/data/sub-40023.mat",
31 | "F:/workshop/demo_data/data/sub-40024.mat",
32 | "F:/workshop/demo_data/data/sub-40025.mat",
33 | "F:/workshop/demo_data/data/sub-40026.mat",
34 | "F:/workshop/demo_data/data/sub-40027.mat",
35 | "F:/workshop/demo_data/data/sub-40028.mat",
36 | "F:/workshop/demo_data/data/sub-40029.mat",
37 | "F:/workshop/demo_data/data/sub-40030.mat",
38 | "F:/workshop/demo_data/data/sub-40031.mat",
39 | "F:/workshop/demo_data/data/sub-40032.mat",
40 | "F:/workshop/demo_data/data/sub-40033.mat",
41 | "F:/workshop/demo_data/data/sub-40034.mat",
42 | "F:/workshop/demo_data/data/sub-40035.mat",
43 | "F:/workshop/demo_data/data/sub-40036.mat",
44 | "F:/workshop/demo_data/data/sub-40037.mat",
45 | "F:/workshop/demo_data/data/sub-40038.mat",
46 | "F:/workshop/demo_data/data/sub-40039.mat",
47 | "F:/workshop/demo_data/data/sub-40040.mat",
48 | "F:/workshop/demo_data/data/sub-40041.mat",
49 | "F:/workshop/demo_data/data/sub-40042.mat",
50 | "F:/workshop/demo_data/data/sub-40043.mat",
51 | "F:/workshop/demo_data/data/sub-40044.mat",
52 | "F:/workshop/demo_data/data/sub-40045.mat",
53 | "F:/workshop/demo_data/data/sub-40046.mat",
54 | "F:/workshop/demo_data/data/sub-40047.mat",
55 | "F:/workshop/demo_data/data/sub-40048.mat",
56 | "F:/workshop/demo_data/data/sub-40049.mat",
57 | "F:/workshop/demo_data/data/sub-40050.mat",
58 | "F:/workshop/demo_data/data/sub-40051.mat",
59 | "F:/workshop/demo_data/data/sub-40052.mat",
60 | "F:/workshop/demo_data/data/sub-40053.mat",
61 | "F:/workshop/demo_data/data/sub-40054.mat",
62 | "F:/workshop/demo_data/data/sub-40055.mat",
63 | "F:/workshop/demo_data/data/sub-40056.mat",
64 | "F:/workshop/demo_data/data/sub-40057.mat",
65 | "F:/workshop/demo_data/data/sub-40058.mat",
66 | "F:/workshop/demo_data/data/sub-40059.mat",
67 | "F:/workshop/demo_data/data/sub-40060.mat",
68 | "F:/workshop/demo_data/data/sub-40061.mat",
69 | "F:/workshop/demo_data/data/sub-40062.mat",
70 | "F:/workshop/demo_data/data/sub-40063.mat",
71 | "F:/workshop/demo_data/data/sub-40064.mat",
72 | "F:/workshop/demo_data/data/sub-40065.mat",
73 | "F:/workshop/demo_data/data/sub-40066.mat",
74 | "F:/workshop/demo_data/data/sub-40067.mat",
75 | "F:/workshop/demo_data/data/sub-40068.mat",
76 | "F:/workshop/demo_data/data/sub-40069.mat",
77 | "F:/workshop/demo_data/data/sub-40071.mat",
78 | "F:/workshop/demo_data/data/sub-40072.mat",
79 | "F:/workshop/demo_data/data/sub-40073.mat",
80 | "F:/workshop/demo_data/data/sub-40074.mat",
81 | "F:/workshop/demo_data/data/sub-40076.mat",
82 | "F:/workshop/demo_data/data/sub-40077.mat",
83 | "F:/workshop/demo_data/data/sub-40078.mat",
84 | "F:/workshop/demo_data/data/sub-40079.mat",
85 | "F:/workshop/demo_data/data/sub-40080.mat",
86 | "F:/workshop/demo_data/data/sub-40081.mat",
87 | "F:/workshop/demo_data/data/sub-40082.mat",
88 | "F:/workshop/demo_data/data/sub-40084.mat",
89 | "F:/workshop/demo_data/data/sub-40085.mat",
90 | "F:/workshop/demo_data/data/sub-40086.mat",
91 | "F:/workshop/demo_data/data/sub-40087.mat",
92 | "F:/workshop/demo_data/data/sub-40088.mat",
93 | "F:/workshop/demo_data/data/sub-40089.mat",
94 | "F:/workshop/demo_data/data/sub-40090.mat",
95 | "F:/workshop/demo_data/data/sub-40091.mat",
96 | "F:/workshop/demo_data/data/sub-40092.mat",
97 | "F:/workshop/demo_data/data/sub-40093.mat",
98 | "F:/workshop/demo_data/data/sub-40094.mat",
99 | "F:/workshop/demo_data/data/sub-40095.mat",
100 | "F:/workshop/demo_data/data/sub-40096.mat",
101 | "F:/workshop/demo_data/data/sub-40097.mat",
102 | "F:/workshop/demo_data/data/sub-40098.mat",
103 | "F:/workshop/demo_data/data/sub-40099.mat",
104 | "F:/workshop/demo_data/data/sub-40100.mat",
105 | "F:/workshop/demo_data/data/sub-40101.mat",
106 | "F:/workshop/demo_data/data/sub-40102.mat",
107 | "F:/workshop/demo_data/data/sub-40103.mat",
108 | "F:/workshop/demo_data/data/sub-40104.mat",
109 | "F:/workshop/demo_data/data/sub-40105.mat",
110 | "F:/workshop/demo_data/data/sub-40106.mat",
111 | "F:/workshop/demo_data/data/sub-40107.mat",
112 | "F:/workshop/demo_data/data/sub-40108.mat",
113 | "F:/workshop/demo_data/data/sub-40109.mat",
114 | "F:/workshop/demo_data/data/sub-40110.mat",
115 | "F:/workshop/demo_data/data/sub-40111.mat",
116 | "F:/workshop/demo_data/data/sub-40112.mat",
117 | "F:/workshop/demo_data/data/sub-40113.mat",
118 | "F:/workshop/demo_data/data/sub-40114.mat",
119 | "F:/workshop/demo_data/data/sub-40115.mat",
120 | "F:/workshop/demo_data/data/sub-40116.mat",
121 | "F:/workshop/demo_data/data/sub-40117.mat",
122 | "F:/workshop/demo_data/data/sub-40118.mat",
123 | "F:/workshop/demo_data/data/sub-40119.mat",
124 | "F:/workshop/demo_data/data/sub-40120.mat",
125 | "F:/workshop/demo_data/data/sub-40121.mat",
126 | "F:/workshop/demo_data/data/sub-40122.mat",
127 | "F:/workshop/demo_data/data/sub-40123.mat",
128 | "F:/workshop/demo_data/data/sub-40124.mat",
129 | "F:/workshop/demo_data/data/sub-40125.mat",
130 | "F:/workshop/demo_data/data/sub-40126.mat",
131 | "F:/workshop/demo_data/data/sub-40127.mat",
132 | "F:/workshop/demo_data/data/sub-40128.mat",
133 | "F:/workshop/demo_data/data/sub-40129.mat",
134 | "F:/workshop/demo_data/data/sub-40130.mat",
135 | "F:/workshop/demo_data/data/sub-40131.mat",
136 | "F:/workshop/demo_data/data/sub-40132.mat",
137 | "F:/workshop/demo_data/data/sub-40133.mat",
138 | "F:/workshop/demo_data/data/sub-40134.mat",
139 | "F:/workshop/demo_data/data/sub-40135.mat",
140 | "F:/workshop/demo_data/data/sub-40136.mat",
141 | "F:/workshop/demo_data/data/sub-40137.mat",
142 | "F:/workshop/demo_data/data/sub-40138.mat",
143 | "F:/workshop/demo_data/data/sub-40139.mat",
144 | "F:/workshop/demo_data/data/sub-40140.mat",
145 | "F:/workshop/demo_data/data/sub-40141.mat",
146 | "F:/workshop/demo_data/data/sub-40142.mat",
147 | "F:/workshop/demo_data/data/sub-40143.mat",
148 | "F:/workshop/demo_data/data/sub-40144.mat",
149 | "F:/workshop/demo_data/data/sub-40145.mat",
150 | "F:/workshop/demo_data/data/sub-40146.mat",
151 | "F:/workshop/demo_data/data/sub-40147.mat"
152 | ],
153 | "mask": ""
154 | }
155 | },
156 | "targets": "D:/My_Codes/Python-Workshop-SuZhou/Machine_learning_in_neuroimaging_using_python_LiChao/targets.xlsx",
157 | "covariates": ""
158 | }
159 | },
160 | "feature_engineering": {
161 | "feature_preprocessing": {
162 | "StandardScaler()": {}
163 | },
164 | "dimreduction": {
165 | "PCA()": {
166 | "n_components": {
167 | "value": "0.95"
168 | }
169 | }
170 | },
171 | "feature_selection": {
172 | "RFECV()": {
173 | "step": {
174 | "value": "0.10"
175 | },
176 | "cv": {
177 | "value": "5"
178 | },
179 | "estimator": {
180 | "value": "SVC(kernel='linear')"
181 | },
182 | "n_jobs": {
183 | "value": "-1"
184 | }
185 | }
186 | },
187 | "unbalance_treatment": {
188 | "RandomOverSampler()": {}
189 | }
190 | },
191 | "machine_learning": {
192 | "Classification": {
193 | "RidgeClassifier()": {
194 | "alpha": {
195 | "value": "1"
196 | }
197 | }
198 | }
199 | },
200 | "model_evaluation": {
201 | "StratifiedKFold()": {
202 | "n_splits": {
203 | "value": "5"
204 | },
205 | "shuffle": {
206 | "value": "True"
207 | },
208 | "random_state": {
209 | "value": "0"
210 | }
211 | },
212 | "Statistical_analysis": {
213 | "Binomial test": {}
214 | }
215 | }
216 | }
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/targets.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/Machine_learning_in_neuroimaging_using_python_LiChao/targets.xlsx
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/workshop.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding: utf-8
3 |
4 | # In[59]:
5 |
6 |
7 | import os
8 | import scipy.io as sio
9 | import pandas as pd
10 | import numpy as np
11 | import matplotlib.pyplot as plt
12 | import seaborn as sns
13 | import seaborn as sns
14 | from collections import Counter
15 | from sklearn.model_selection import StratifiedShuffleSplit
16 | from sklearn.preprocessing import StandardScaler
17 | from sklearn.decomposition import PCA
18 | from sklearn.feature_selection import RFECV
19 | from sklearn.svm import LinearSVC
20 | from sklearn.linear_model import LogisticRegression, RidgeClassifier, LassoCV
21 | from sklearn import metrics
22 | from nilearn import plotting
23 | from pyecharts.charts import Graph
24 | from pyecharts import options as opts
25 |
26 |
27 | # ### ===========================输入===========================
28 |
29 | # In[60]:
30 |
31 |
32 | data_file_raw = "F:/workshop/demo_data/data" # 如果下载了原始数据
33 | data_file_triu = "./fc_triu.npy" # 如果只有上三角向量
34 | label_file = "./targets.xlsx"
35 |
36 |
37 | # ### ===========================读取特征和标签===========================
38 |
39 | # In[61]:
40 |
41 |
42 | # 读取保存数据的文件名
43 | files_name = os.listdir(data_file_raw)
44 | files = [os.path.join(data_file_raw, fn) for fn in files_name] # 获取所有功能连接的文件地址
45 | label = pd.read_excel(label_file)
46 | # print(f"files={files}")
47 | print(label)
48 |
49 |
50 | # In[62]:
51 |
52 |
53 | # 加载第一个功能连接, 查看数据形式
54 | onefc = sio.loadmat(files[0])
55 | print(f"数据类型为:{type(onefc)}")
56 | # 查看字典的keys
57 | print(f"功能连接的keys为: {onefc.keys()}")
58 | # 第4个item是数据,我们查看数据的情况
59 | dd = onefc[list(onefc.keys())[3]]
60 | print(f"功能连接特征的原始形状为:{dd.shape}")
61 | plt.imshow(dd, cmap="jet")
62 | plt.colorbar()
63 |
64 |
65 | # In[63]:
66 |
67 |
68 | # 逐个读取每个被试的功能连接, 并将所有数据放入data
69 | # 因为功能连接是一个对称矩阵,即上三角和下三角是对称的,所以后续加载数据的时候,我们只保留上三角即可
70 | mask = np.ones(np.shape(dd))
71 | mask = np.triu(mask, 1)
72 | mask = mask == 1
73 | plt.imshow(mask, cmap="gray")
74 | plt.colorbar()
75 | plt.show()
76 |
77 |
78 | # In[64]:
79 |
80 |
81 | # 如果下载了原始数据,加载并提取每个功能连接数据的上三角部分
82 | data = []
83 | for file in files:
84 | dd = sio.loadmat(file)
85 | dd = dd[list(dd.keys())[3]]
86 | dd = dd[mask] # 用mask筛选上三角矩阵
87 | data.append(dd)
88 | data = np.array(data) # 将data转换为numpy.array
89 | print(f"###特征的形状:{data.shape}###")
90 | pd.DataFrame(data).head(5)
91 |
92 |
93 | # In[65]:
94 |
95 |
96 | # 如果只有fc_triu.npy,即上三角矩阵
97 | data = np.load(data_file_triu)
98 | print(f"###特征的形状:{data.shape}###")
99 | pd.DataFrame(data).head(5)
100 |
101 |
102 | # ### ===========================将每个被试特征与其标签对齐===========================
103 |
104 | # In[66]:
105 |
106 |
107 | # 1.第一步提取文件名中的被试名
108 | files_name = pd.Series(files_name)
109 | files_id = files_name.str.findall(".*sub.?\d*")
110 | files_id = pd.DataFrame([fi[0] for fi in files_id])
111 | # 2.将label按照文件名顺序重新排序
112 | label_sorted = pd.merge(files_id, label, left_on=0, right_on="__ID__")
113 | label_sorted = label_sorted["__Targets__"].values
114 |
115 |
116 | # In[67]:
117 |
118 |
119 | # 为了后续演示,我故意在特征中随机设置5000个缺失值
120 | np.seed = 666
121 | n_sub = len(data)
122 | id_nan = np.random.permutation(data.size)[:5000]
123 | data = data.reshape([-1,1])
124 | data[id_nan,] = np.nan
125 | data = data.reshape(n_sub,-1)
126 |
127 |
128 | # ### =============================划分数据=============================
129 |
130 | # In[68]:
131 |
132 |
133 | np.random.seed(0)
134 | skf = StratifiedShuffleSplit(n_splits=1, test_size=0.4, random_state=666)
135 | skf_index = list(skf.split(data, label_sorted))
136 | feature_train = data[skf_index[0][0],:]
137 | label_train = label_sorted[skf_index[0][0]]
138 | feature_other = data[skf_index[0][1],:]
139 | label_other = label_sorted[skf_index[0][1]]
140 |
141 | skf = StratifiedShuffleSplit(n_splits=1, test_size=0.5, random_state=666)
142 | skf_index = list(skf.split(feature_other, label_other))
143 | feature_validation = feature_other[skf_index[0][0],:]
144 | label_validation = label_other[skf_index[0][0]]
145 | feature_test = feature_other[skf_index[0][1],:]
146 | label_test = label_other[skf_index[0][1]]
147 |
148 | # 检查各个数据中各类的数目, 即各类别是否平衡
149 | ct_tr = sorted(Counter(label_train).items())
150 | ct_val = sorted(Counter(label_validation).items())
151 | ct_te = sorted(Counter(label_test).items())
152 |
153 | print(f"训练集中各个类别的数目为:{ct_tr}")
154 | print(f"验证集中各个类别的数目为:{ct_val}")
155 | print(f"测试集中各个类别的数目为:{ct_te}")
156 |
157 | # 画饼图,看各类比例
158 | plt.subplot(1,3,1)
159 | labels = ["SZ", "HC"]
160 | sizes = [ct[1] for ct in ct_tr]
161 | plt.pie(sizes,labels=labels,autopct='%1.1f%%',shadow=False,startangle=150, )
162 | plt.title("Trainning dataset")
163 |
164 | plt.subplot(1,3,2)
165 | sizes = [ct[1] for ct in ct_val]
166 | plt.pie(sizes,labels=labels,autopct='%1.1f%%',shadow=False,startangle=150, )
167 | plt.title("Validation dataset")
168 |
169 | plt.subplot(1,3,3)
170 | sizes = [ct[1] for ct in ct_te]
171 | plt.pie(sizes,labels=labels,autopct='%1.1f%%',shadow=False,startangle=150, )
172 | plt.title("Test dataset")
173 | plt.show()
174 |
175 |
176 | # ### =============================数据检查与处理=============================
177 |
178 | # In[69]:
179 |
180 |
181 | # 检查训练集中缺失值
182 | nan_value = np.sum(np.isnan(feature_train), axis=0)
183 | print(f"所有特征中,最多的缺失值数量为:{np.max(nan_value)}") # 最大的缺失值
184 |
185 |
186 | # In[70]:
187 |
188 |
189 | # 缺失值不多,选择用均值填充缺失值
190 | feature_train = pd.DataFrame(feature_train)
191 | feature_validation = pd.DataFrame(feature_validation)
192 | feature_test = pd.DataFrame(feature_test)
193 |
194 | fill_value = feature_train.mean() # 只能用训练集的参数,因为实际应用中我们往往不能获取测试集的数据
195 | feature_train = pd.DataFrame(feature_train)
196 | feature_train.fillna(value=fill_value, inplace=True)
197 | feature_validation.fillna(value=fill_value, inplace=True)
198 | feature_test.fillna(value=fill_value, inplace=True)
199 |
200 | nan_value = np.sum(np.isnan(feature_train), axis=0)
201 | print(f"填充后,所有特征中,最多的缺失值数量为:{np.max(nan_value)}") # 最大的缺失值
202 |
203 |
204 | # In[71]:
205 |
206 |
207 | # 检查训练集特征数值为0的样本比例
208 | zero_value = np.sum(feature_train==0, axis=0)
209 | print(f"全为0的特征数量为: {np.max(zero_value)}")
210 |
211 |
212 | # In[72]:
213 |
214 |
215 | # 检查各个数据集的分布和相关性
216 | data_ = np.vstack([feature_train.mean(axis=0), feature_validation.mean(axis=0), feature_test.mean(axis=0)])
217 | fig, axs = plt.subplots(1,2, figsize=(10,5))
218 | sns.heatmap(np.corrcoef(data_), annot=True, ax=axs[0])
219 | axs[0].axis('equal')
220 | axs[0].set_xticklabels(["Trainning dataset","Validation dataset","Test dataset"], rotation=45)
221 | axs[0].set_yticklabels(["Trainning dataset","Validation dataset","Test dataset"], rotation=0)
222 | sns.kdeplot(data_[0,:], ax=axs[1])
223 | sns.kdeplot(data_[1,:], ax=axs[1])
224 | sns.kdeplot(data_[2,:], ax=axs[1])
225 | plt.title("Distribution", fontsize=20)
226 | plt.legend(["Training dataset", "Validation dataset", "Test dataset"])
227 | plt.subplots_adjust(wspace=1)
228 | plt.show()
229 |
230 |
231 | # In[73]:
232 |
233 |
234 | # 规范化数据
235 | scaler = StandardScaler()
236 | feature_train_ = scaler.fit_transform(feature_train)
237 |
238 | feature_validation_ = scaler.transform(feature_validation) # 对验证集和测试集在规范化时,要用训练集的参数
239 | feature_test_ = scaler.transform(feature_test)
240 |
241 | pd.DataFrame(feature_train).head(5)
242 |
243 |
244 | # ### =============================特征工程:降维 + 特征选择=============================
245 |
246 | # In[74]:
247 |
248 |
249 | # 降维
250 | pca = PCA(n_components=0.95, random_state=666)
251 | feature_train_ = pca.fit_transform(feature_train_)
252 |
253 | feature_validation_ = pca.transform(feature_validation_) # 使用训练集的参数给验证集和测试集做降维
254 | feature_test_ = pca.transform(feature_test_)
255 | print(f"###降维后特征维度由{feature_train.shape[1]}变为{feature_train_.shape[1]}###")
256 | pd.DataFrame(feature_train_).head(5)
257 |
258 |
259 | # In[82]:
260 |
261 |
262 | # 递归特征消除筛选特征
263 | selector = RFECV(LinearSVC(random_state=666), step=5, cv=5, n_jobs=3)
264 | selector.fit(feature_train_, label_train)
265 | feature_train_ = selector.transform(feature_train_)
266 |
267 | # 对验证集和测试集做特征选择,要用训练集的参数
268 | feature_validation_ = selector.transform(feature_validation_)
269 | feature_test_ = selector.transform(feature_test_)
270 | print(f"###递归特征消除法选择特征后,特征维度为{feature_train_.shape[1]}###")
271 | print(f"被剔除的特征的编号为:\n{pd.DataFrame(np.where(1-selector.support_)).values}")
272 | pd.DataFrame(feature_train_).head(5)
273 |
274 |
275 | # ### ============================训练模型============================
276 |
277 | # In[87]:
278 |
279 |
280 | # model = LogisticRegression(C=1, random_state=666)
281 | model = RidgeClassifier(random_state=666)
282 | model.fit(feature_train_, label_train)
283 |
284 |
285 | # ### ============================模型验证============================
286 | # > 最好使用外部验证集
287 |
288 | # In[88]:
289 |
290 |
291 | pred_train_label = model.predict(feature_train_)
292 | pred_val_label = model.predict(feature_validation_)
293 |
294 |
295 | # In[89]:
296 |
297 |
298 | # 模型验证,以及根据验证情况调参
299 | acc_train = metrics.accuracy_score(label_train, pred_train_label)
300 | f1score_train = metrics.f1_score(label_train, pred_train_label)
301 | acc_validation = metrics.accuracy_score(label_validation, pred_val_label)
302 | f1score_validation = metrics.f1_score(label_validation, pred_val_label)
303 | print(f"acc_train = {acc_train:.3f}; f1score_train = {f1score_train}\nacc_validation = {acc_validation:.8f}; f1score_validaton = {f1score_validation}")
304 |
305 |
306 | # ### ============================最终的测试============================
307 | # > 最好使用外部测试集
308 |
309 | # In[90]:
310 |
311 |
312 | pred_test_label = model.predict(feature_test_)
313 | pred_test_prob = model.decision_function(feature_test_)
314 | acc_test = metrics.accuracy_score(label_test, pred_test_label)
315 | f1score_test = metrics.f1_score(label_test, pred_test_label)
316 | print(f"acc_test = {acc_test:.8f}; f1score_test = {f1score_test}\n")
317 |
318 |
319 | # ### ============================结果可视化============================
320 |
321 | # In[80]:
322 |
323 |
324 | # 获取权重
325 | wei = model.coef_
326 | wei = (wei - wei.mean()) / wei.std()
327 | wei = selector.inverse_transform(wei)
328 | wei = pca.inverse_transform(wei)
329 | weight = np.zeros(mask.shape)
330 | weight[mask] = wei[0]
331 | weight = weight + weight.T
332 |
333 | # 只显示前0.2%的权重
334 | threshold = 99.8
335 | topperc = np.percentile(np.abs(weight), threshold)
336 | weight[np.abs(weight) < topperc] = 0
337 |
338 | # 获取MNI坐标
339 | coords_file = r"F:\workshop\demo_data\BNA_subregions.xlsx"
340 | coords_info = pd.read_excel(coords_file)
341 |
342 | # 获取MNI坐标
343 | coords = np.hstack([coords_info["lh.MNI(X,Y,Z)"].values, coords_info["rh.MNI(X,Y,Z)"].values])
344 | label_idx = np.hstack([coords_info["Label ID.L"].values, coords_info["Label ID.R"].values])
345 | sort_idx = np.argsort(label_idx)
346 | node_coords = coords[sort_idx]
347 | node_coords = pd.DataFrame([eval(nc) for nc in node_coords]).values
348 |
349 | # 获取node name
350 | name = coords_info["Left and Right Hemisphere"]
351 | name_L = ["L".join(name_.split("L(R)")) for name_ in name]
352 | name_R = ["R".join(name_.split("L(R)")) for name_ in name]
353 | node_name = np.hstack([name_L, name_R])
354 | node_name = node_name[sort_idx]
355 |
356 | # 获取构成连接的节点名称
357 | id_mat = np.where(weight)
358 | node1 = node_name[id_mat[0]]
359 | node2 = node_name[id_mat[1]]
360 | node = np.hstack([node1, node2])
361 | node = np.unique(node)
362 |
363 | # 显示连接网络
364 | weight_filter = weight[id_mat[0], id_mat[1]]
365 | wei_node = np.hstack([node1, node2]).T
366 | wei_node = np.vstack([wei_node, np.hstack([weight_filter, weight_filter])]).T
367 |
368 | nodes = [{"name": nd, "symbolSize": np.sum(np.abs(np.float64(wei_node[:,1][np.in1d(wei_node[:,0], str(nd))])))*20} for nd in node]
369 | links = [{"source": str(nd1), "target": str(nd2)} for (nd1, nd2) in zip(node1, node2)]
370 | graph= (
371 | Graph()
372 | .add("", nodes, links, repulsion=100)
373 | .set_global_opts(title_opts=opts.TitleOpts(title=f"前{100-threshold:.2f}%的权重"))
374 | )
375 | graph.render_notebook()
376 |
377 |
378 | # In[81]:
379 |
380 |
381 | # 矩阵显示
382 | plt.figure(figsize=(10,10))
383 | plt.imshow(weight, cmap="RdBu_r")
384 | plt.colorbar()
385 | plt.show()
386 |
387 | # 脑图显示
388 | plotting.plot_connectome(weight, node_coords, node_size=0, annotate=True)
389 | plt.show()
390 | view = plotting.view_connectome(weight, node_coords)
391 | view
392 |
393 |
394 | # In[ ]:
395 |
396 |
397 |
398 |
399 |
--------------------------------------------------------------------------------
/Machine_learning_in_neuroimaging_using_python_LiChao/一般流程.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/Machine_learning_in_neuroimaging_using_python_LiChao/一般流程.png
--------------------------------------------------------------------------------
/PsychoPy/Python在实验程序编写中的应用——Ryan.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/PsychoPy/Python在实验程序编写中的应用——Ryan.pdf
--------------------------------------------------------------------------------
/PsychoPy/ReadMe.md:
--------------------------------------------------------------------------------
1 | # Python在实验程序编写和设计中的应用,以PsychoPy为例 #
2 | >分享者:Ryan
3 |
4 | >微信公众号:Ryan聊心理
5 | 
6 |
7 | ## 文件说明 ##
8 | Python在实验程序编写中的应用——Ryan.pdf
9 | ———20201122工作坊分享PPT
10 |
11 | gonogo.psyexp
12 | ———使用PsychoPy Builder创建的GoNogo实验(PsychoPy工程文件)
13 |
14 | gonogo.py
15 | ———使用PsychoPy Builder创建的GoNogo实验(PsychoPy生成的Python文件)
16 |
17 | stimuli_list.xlsx
18 | ———运行使用PsychoPy Builder创建的GoNogo实验所需的刺激材料文件
19 |
20 | gonogo_test.py
21 | ———使用PsychoPy Coder创建的GoNogo实验
22 |
23 | stroop.psyexp
24 | ———使用PsychoPy Builder创建的Stroop实验
25 |
26 | ## 版本 ##
27 | Python 3.6
28 |
29 | PsychoPy 2020.2.4
30 |
31 | ## 安装 ##
32 | 如果已经安装好了Python,建议直接通过pip来安装PsychoPy,不另安装Standalone版的PsychoPy
33 | ### Python标准安装(推荐) ###
34 | pip install psychopy
35 | ### Python纯安装(后续手动安装依赖包-不推荐) ###
36 | pip install psychopy --no-deps
37 | 若只考虑使用PsychoPy的Builder模式,可直接安装PsychoPy的exe
38 | ### EXE直接安装(不推荐) ###
39 | Standalone版的PsychoPy
40 | >链接:https://pan.baidu.com/s/169nYLiGB6nfw7-Eh9fDh8Q
41 | >
42 | >提取码:c4bp
43 |
44 | ## 交流群 ##
45 | 
46 |
47 | ## 招聘 ##
48 | >若感兴趣在企业的就业机会,可以打开链接详细了解
49 |
50 | >https://mp.weixin.qq.com/s/oi8pIErmhcox0lVPsi-spA
--------------------------------------------------------------------------------
/PsychoPy/gonogo.psyexp:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/PsychoPy/gonogo.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | This experiment was created using PsychoPy3 Experiment Builder (v2020.2.6),
5 | on 十一月 21, 2020, at 15:37
6 | If you publish work using this script the most relevant publication is:
7 |
8 | Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, Lindeløv JK. (2019)
9 | PsychoPy2: Experiments in behavior made easy Behav Res 51: 195.
10 | https://doi.org/10.3758/s13428-018-01193-y
11 |
12 | """
13 |
14 | from __future__ import absolute_import, division
15 |
16 | from psychopy import locale_setup
17 | from psychopy import prefs
18 | from psychopy import sound, gui, visual, core, data, event, logging, clock
19 | from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
20 | STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
21 |
22 | import numpy as np # whole numpy lib is available, prepend 'np.'
23 | from numpy import (sin, cos, tan, log, log10, pi, average,
24 | sqrt, std, deg2rad, rad2deg, linspace, asarray)
25 | from numpy.random import random, randint, normal, shuffle
26 | import os # handy system and path functions
27 | import sys # to get file system encoding
28 |
29 | from psychopy.hardware import keyboard
30 |
31 |
32 |
33 | # Ensure that relative paths start from the same directory as this script
34 | _thisDir = os.path.dirname(os.path.abspath(__file__))
35 | os.chdir(_thisDir)
36 |
37 | # Store info about the experiment session
38 | psychopyVersion = '2020.2.6'
39 | expName = 'gonogo' # from the Builder filename that created this script
40 | expInfo = {'participant': '', 'session': '001'}
41 | dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
42 | if dlg.OK == False:
43 | core.quit() # user pressed cancel
44 | expInfo['date'] = data.getDateStr() # add a simple timestamp
45 | expInfo['expName'] = expName
46 | expInfo['psychopyVersion'] = psychopyVersion
47 |
48 | # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
49 | filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
50 |
51 | # An ExperimentHandler isn't essential but helps with data saving
52 | thisExp = data.ExperimentHandler(name=expName, version='',
53 | extraInfo=expInfo, runtimeInfo=None,
54 | originPath='F:\\坚果云同步盘\\Ryan的同步文件\\201122Python分享\\Git\\gonogo.py',
55 | savePickle=True, saveWideText=True,
56 | dataFileName=filename)
57 | # save a log file for detail verbose info
58 | logFile = logging.LogFile(filename+'.log', level=logging.EXP)
59 | logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
60 |
61 | endExpNow = False # flag for 'escape' or other condition => quit the exp
62 | frameTolerance = 0.001 # how close to onset before 'same' frame
63 |
64 | # Start Code - component code to be run after the window creation
65 |
66 | # Setup the Window
67 | win = visual.Window(
68 | size=[1024, 768], fullscr=False, screen=0,
69 | winType='pyglet', allowGUI=True, allowStencil=False,
70 | monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
71 | blendMode='avg', useFBO=True,
72 | units='pix')
73 | # store frame rate of monitor if we can measure it
74 | expInfo['frameRate'] = win.getActualFrameRate()
75 | if expInfo['frameRate'] != None:
76 | frameDur = 1.0 / round(expInfo['frameRate'])
77 | else:
78 | frameDur = 1.0 / 60.0 # could not measure, so guess
79 |
80 | # create a default keyboard (e.g. to check for escape)
81 | defaultKeyboard = keyboard.Keyboard()
82 |
83 | # Initialize components for Routine "ins1"
84 | ins1Clock = core.Clock()
85 | ins1_text = visual.TextStim(win=win, name='ins1_text',
86 | text='If you see M, press SPACE, if see W, do nothing\n\nPress ENTER to start practice',
87 | font='Arial',
88 | pos=(0, 0), height=30, wrapWidth=None, ori=0,
89 | color='white', colorSpace='rgb', opacity=1,
90 | languageStyle='LTR',
91 | depth=0.0);
92 | key_resp_ins1 = keyboard.Keyboard()
93 |
94 | # Initialize components for Routine "practice"
95 | practiceClock = core.Clock()
96 | fix_text = visual.TextStim(win=win, name='fix_text',
97 | text='+',
98 | font='Arial',
99 | pos=(0, 0), height=50, wrapWidth=None, ori=0,
100 | color='white', colorSpace='rgb', opacity=1,
101 | languageStyle='LTR',
102 | depth=0.0);
103 | sti_text = visual.TextStim(win=win, name='sti_text',
104 | text='default text',
105 | font='Arial',
106 | pos=(0, 0), height=36, wrapWidth=None, ori=0,
107 | color='white', colorSpace='rgb', opacity=1,
108 | languageStyle='LTR',
109 | depth=-1.0);
110 | key_resp = keyboard.Keyboard()
111 |
112 | # Initialize components for Routine "ins2"
113 | ins2Clock = core.Clock()
114 | ins2_text = visual.TextStim(win=win, name='ins2_text',
115 | text='Press ENTER to start experiment',
116 | font='Arial',
117 | pos=(0, 0), height=30, wrapWidth=None, ori=0,
118 | color='white', colorSpace='rgb', opacity=1,
119 | languageStyle='LTR',
120 | depth=0.0);
121 | key_resp_ins2 = keyboard.Keyboard()
122 |
123 | # Initialize components for Routine "exp1"
124 | exp1Clock = core.Clock()
125 | fix1_text = visual.TextStim(win=win, name='fix1_text',
126 | text='+',
127 | font='Arial',
128 | pos=(0, 0), height=50, wrapWidth=None, ori=0,
129 | color='white', colorSpace='rgb', opacity=1,
130 | languageStyle='LTR',
131 | depth=0.0);
132 | sti1_text = visual.TextStim(win=win, name='sti1_text',
133 | text='default text',
134 | font='Arial',
135 | pos=(0, 0), height=36, wrapWidth=None, ori=0,
136 | color='white', colorSpace='rgb', opacity=1,
137 | languageStyle='LTR',
138 | depth=-1.0);
139 | key_resp_2 = keyboard.Keyboard()
140 |
141 | # Initialize components for Routine "rest"
142 | restClock = core.Clock()
143 | rest_text = visual.TextStim(win=win, name='rest_text',
144 | text='Rest for a while',
145 | font='Arial',
146 | pos=(0, 0), height=30, wrapWidth=None, ori=0,
147 | color='white', colorSpace='rgb', opacity=1,
148 | languageStyle='LTR',
149 | depth=0.0);
150 |
151 | # Initialize components for Routine "exp2"
152 | exp2Clock = core.Clock()
153 | fix2_text = visual.TextStim(win=win, name='fix2_text',
154 | text='+',
155 | font='Arial',
156 | pos=(0, 0), height=50, wrapWidth=None, ori=0,
157 | color='white', colorSpace='rgb', opacity=1,
158 | languageStyle='LTR',
159 | depth=0.0);
160 | si2_text = visual.TextStim(win=win, name='si2_text',
161 | text='default text',
162 | font='Arial',
163 | pos=(0, 0), height=36, wrapWidth=None, ori=0,
164 | color='white', colorSpace='rgb', opacity=1,
165 | languageStyle='LTR',
166 | depth=-1.0);
167 | key_resp_3 = keyboard.Keyboard()
168 |
169 | # Initialize components for Routine "finish"
170 | finishClock = core.Clock()
171 | finish_text = visual.TextStim(win=win, name='finish_text',
172 | text='This is the end of the experiment.\n\nThank you!',
173 | font='Arial',
174 | pos=(0, 0), height=30, wrapWidth=None, ori=0,
175 | color='white', colorSpace='rgb', opacity=1,
176 | languageStyle='LTR',
177 | depth=0.0);
178 | key_resp_finish = keyboard.Keyboard()
179 |
180 | # Create some handy timers
181 | globalClock = core.Clock() # to track the time since experiment started
182 | routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
183 |
184 | # ------Prepare to start Routine "ins1"-------
185 | continueRoutine = True
186 | # update component parameters for each repeat
187 | key_resp_ins1.keys = []
188 | key_resp_ins1.rt = []
189 | _key_resp_ins1_allKeys = []
190 | # keep track of which components have finished
191 | ins1Components = [ins1_text, key_resp_ins1]
192 | for thisComponent in ins1Components:
193 | thisComponent.tStart = None
194 | thisComponent.tStop = None
195 | thisComponent.tStartRefresh = None
196 | thisComponent.tStopRefresh = None
197 | if hasattr(thisComponent, 'status'):
198 | thisComponent.status = NOT_STARTED
199 | # reset timers
200 | t = 0
201 | _timeToFirstFrame = win.getFutureFlipTime(clock="now")
202 | ins1Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
203 | frameN = -1
204 |
205 | # -------Run Routine "ins1"-------
206 | while continueRoutine:
207 | # get current time
208 | t = ins1Clock.getTime()
209 | tThisFlip = win.getFutureFlipTime(clock=ins1Clock)
210 | tThisFlipGlobal = win.getFutureFlipTime(clock=None)
211 | frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
212 | # update/draw components on each frame
213 |
214 | # *ins1_text* updates
215 | if ins1_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
216 | # keep track of start time/frame for later
217 | ins1_text.frameNStart = frameN # exact frame index
218 | ins1_text.tStart = t # local t and not account for scr refresh
219 | ins1_text.tStartRefresh = tThisFlipGlobal # on global time
220 | win.timeOnFlip(ins1_text, 'tStartRefresh') # time at next scr refresh
221 | ins1_text.setAutoDraw(True)
222 |
223 | # *key_resp_ins1* updates
224 | waitOnFlip = False
225 | if key_resp_ins1.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
226 | # keep track of start time/frame for later
227 | key_resp_ins1.frameNStart = frameN # exact frame index
228 | key_resp_ins1.tStart = t # local t and not account for scr refresh
229 | key_resp_ins1.tStartRefresh = tThisFlipGlobal # on global time
230 | win.timeOnFlip(key_resp_ins1, 'tStartRefresh') # time at next scr refresh
231 | key_resp_ins1.status = STARTED
232 | # keyboard checking is just starting
233 | waitOnFlip = True
234 | win.callOnFlip(key_resp_ins1.clock.reset) # t=0 on next screen flip
235 | win.callOnFlip(key_resp_ins1.clearEvents, eventType='keyboard') # clear events on next screen flip
236 | if key_resp_ins1.status == STARTED and not waitOnFlip:
237 | theseKeys = key_resp_ins1.getKeys(keyList=['return'], waitRelease=False)
238 | _key_resp_ins1_allKeys.extend(theseKeys)
239 | if len(_key_resp_ins1_allKeys):
240 | key_resp_ins1.keys = _key_resp_ins1_allKeys[-1].name # just the last key pressed
241 | key_resp_ins1.rt = _key_resp_ins1_allKeys[-1].rt
242 | # a response ends the routine
243 | continueRoutine = False
244 |
245 | # check for quit (typically the Esc key)
246 | if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
247 | core.quit()
248 |
249 | # check if all components have finished
250 | if not continueRoutine: # a component has requested a forced-end of Routine
251 | break
252 | continueRoutine = False # will revert to True if at least one component still running
253 | for thisComponent in ins1Components:
254 | if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
255 | continueRoutine = True
256 | break # at least one component has not yet finished
257 |
258 | # refresh the screen
259 | if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
260 | win.flip()
261 |
262 | # -------Ending Routine "ins1"-------
263 | for thisComponent in ins1Components:
264 | if hasattr(thisComponent, "setAutoDraw"):
265 | thisComponent.setAutoDraw(False)
266 | thisExp.addData('ins1_text.started', ins1_text.tStartRefresh)
267 | thisExp.addData('ins1_text.stopped', ins1_text.tStopRefresh)
268 | # the Routine "ins1" was not non-slip safe, so reset the non-slip timer
269 | routineTimer.reset()
270 |
271 | # set up handler to look after randomisation of conditions etc
272 | prac_trials = data.TrialHandler(nReps=2, method='random',
273 | extraInfo=expInfo, originPath=-1,
274 | trialList=data.importConditions('stimuli_list.xlsx'),
275 | seed=None, name='prac_trials')
276 | thisExp.addLoop(prac_trials) # add the loop to the experiment
277 | thisPrac_trial = prac_trials.trialList[0] # so we can initialise stimuli with some values
278 | # abbreviate parameter names if possible (e.g. rgb = thisPrac_trial.rgb)
279 | if thisPrac_trial != None:
280 | for paramName in thisPrac_trial:
281 | exec('{} = thisPrac_trial[paramName]'.format(paramName))
282 |
283 | for thisPrac_trial in prac_trials:
284 | currentLoop = prac_trials
285 | # abbreviate parameter names if possible (e.g. rgb = thisPrac_trial.rgb)
286 | if thisPrac_trial != None:
287 | for paramName in thisPrac_trial:
288 | exec('{} = thisPrac_trial[paramName]'.format(paramName))
289 |
290 | # ------Prepare to start Routine "practice"-------
291 | continueRoutine = True
292 | routineTimer.add(1.800000)
293 | # update component parameters for each repeat
294 | sti_text.setText(sti)
295 | key_resp.keys = []
296 | key_resp.rt = []
297 | _key_resp_allKeys = []
298 | # keep track of which components have finished
299 | practiceComponents = [fix_text, sti_text, key_resp]
300 | for thisComponent in practiceComponents:
301 | thisComponent.tStart = None
302 | thisComponent.tStop = None
303 | thisComponent.tStartRefresh = None
304 | thisComponent.tStopRefresh = None
305 | if hasattr(thisComponent, 'status'):
306 | thisComponent.status = NOT_STARTED
307 | # reset timers
308 | t = 0
309 | _timeToFirstFrame = win.getFutureFlipTime(clock="now")
310 | practiceClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
311 | frameN = -1
312 |
313 | # -------Run Routine "practice"-------
314 | while continueRoutine and routineTimer.getTime() > 0:
315 | # get current time
316 | t = practiceClock.getTime()
317 | tThisFlip = win.getFutureFlipTime(clock=practiceClock)
318 | tThisFlipGlobal = win.getFutureFlipTime(clock=None)
319 | frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
320 | # update/draw components on each frame
321 |
322 | # *fix_text* updates
323 | if fix_text.status == NOT_STARTED and tThisFlip >= 0.4-frameTolerance:
324 | # keep track of start time/frame for later
325 | fix_text.frameNStart = frameN # exact frame index
326 | fix_text.tStart = t # local t and not account for scr refresh
327 | fix_text.tStartRefresh = tThisFlipGlobal # on global time
328 | win.timeOnFlip(fix_text, 'tStartRefresh') # time at next scr refresh
329 | fix_text.setAutoDraw(True)
330 | if fix_text.status == STARTED:
331 | # is it time to stop? (based on global clock, using actual start)
332 | if tThisFlipGlobal > fix_text.tStartRefresh + 0.5-frameTolerance:
333 | # keep track of stop time/frame for later
334 | fix_text.tStop = t # not accounting for scr refresh
335 | fix_text.frameNStop = frameN # exact frame index
336 | win.timeOnFlip(fix_text, 'tStopRefresh') # time at next scr refresh
337 | fix_text.setAutoDraw(False)
338 |
339 | # *sti_text* updates
340 | if sti_text.status == NOT_STARTED and tThisFlip >= 0.9-frameTolerance:
341 | # keep track of start time/frame for later
342 | sti_text.frameNStart = frameN # exact frame index
343 | sti_text.tStart = t # local t and not account for scr refresh
344 | sti_text.tStartRefresh = tThisFlipGlobal # on global time
345 | win.timeOnFlip(sti_text, 'tStartRefresh') # time at next scr refresh
346 | sti_text.setAutoDraw(True)
347 | if sti_text.status == STARTED:
348 | # is it time to stop? (based on global clock, using actual start)
349 | if tThisFlipGlobal > sti_text.tStartRefresh + 0.1-frameTolerance:
350 | # keep track of stop time/frame for later
351 | sti_text.tStop = t # not accounting for scr refresh
352 | sti_text.frameNStop = frameN # exact frame index
353 | win.timeOnFlip(sti_text, 'tStopRefresh') # time at next scr refresh
354 | sti_text.setAutoDraw(False)
355 |
356 | # *key_resp* updates
357 | waitOnFlip = False
358 | if key_resp.status == NOT_STARTED and tThisFlip >= 1.0-frameTolerance:
359 | # keep track of start time/frame for later
360 | key_resp.frameNStart = frameN # exact frame index
361 | key_resp.tStart = t # local t and not account for scr refresh
362 | key_resp.tStartRefresh = tThisFlipGlobal # on global time
363 | win.timeOnFlip(key_resp, 'tStartRefresh') # time at next scr refresh
364 | key_resp.status = STARTED
365 | # keyboard checking is just starting
366 | waitOnFlip = True
367 | win.callOnFlip(key_resp.clock.reset) # t=0 on next screen flip
368 | win.callOnFlip(key_resp.clearEvents, eventType='keyboard') # clear events on next screen flip
369 | if key_resp.status == STARTED:
370 | # is it time to stop? (based on global clock, using actual start)
371 | if tThisFlipGlobal > key_resp.tStartRefresh + 0.8-frameTolerance:
372 | # keep track of stop time/frame for later
373 | key_resp.tStop = t # not accounting for scr refresh
374 | key_resp.frameNStop = frameN # exact frame index
375 | win.timeOnFlip(key_resp, 'tStopRefresh') # time at next scr refresh
376 | key_resp.status = FINISHED
377 | if key_resp.status == STARTED and not waitOnFlip:
378 | theseKeys = key_resp.getKeys(keyList=['space'], waitRelease=False)
379 | _key_resp_allKeys.extend(theseKeys)
380 | if len(_key_resp_allKeys):
381 | key_resp.keys = _key_resp_allKeys[-1].name # just the last key pressed
382 | key_resp.rt = _key_resp_allKeys[-1].rt
383 | # was this correct?
384 | if (key_resp.keys == str(ans)) or (key_resp.keys == ans):
385 | key_resp.corr = 1
386 | else:
387 | key_resp.corr = 0
388 | # a response ends the routine
389 | continueRoutine = False
390 |
391 | # check for quit (typically the Esc key)
392 | if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
393 | core.quit()
394 |
395 | # check if all components have finished
396 | if not continueRoutine: # a component has requested a forced-end of Routine
397 | break
398 | continueRoutine = False # will revert to True if at least one component still running
399 | for thisComponent in practiceComponents:
400 | if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
401 | continueRoutine = True
402 | break # at least one component has not yet finished
403 |
404 | # refresh the screen
405 | if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
406 | win.flip()
407 |
408 | # -------Ending Routine "practice"-------
409 | for thisComponent in practiceComponents:
410 | if hasattr(thisComponent, "setAutoDraw"):
411 | thisComponent.setAutoDraw(False)
412 | prac_trials.addData('fix_text.started', fix_text.tStartRefresh)
413 | prac_trials.addData('fix_text.stopped', fix_text.tStopRefresh)
414 | prac_trials.addData('sti_text.started', sti_text.tStartRefresh)
415 | prac_trials.addData('sti_text.stopped', sti_text.tStopRefresh)
416 | # check responses
417 | if key_resp.keys in ['', [], None]: # No response was made
418 | key_resp.keys = None
419 | # was no response the correct answer?!
420 | if str(ans).lower() == 'none':
421 | key_resp.corr = 1; # correct non-response
422 | else:
423 | key_resp.corr = 0; # failed to respond (incorrectly)
424 | # store data for prac_trials (TrialHandler)
425 | prac_trials.addData('key_resp.keys',key_resp.keys)
426 | prac_trials.addData('key_resp.corr', key_resp.corr)
427 | if key_resp.keys != None: # we had a response
428 | prac_trials.addData('key_resp.rt', key_resp.rt)
429 | prac_trials.addData('key_resp.started', key_resp.tStartRefresh)
430 | prac_trials.addData('key_resp.stopped', key_resp.tStopRefresh)
431 | thisExp.nextEntry()
432 |
433 | # completed 2 repeats of 'prac_trials'
434 |
435 |
436 | # ------Prepare to start Routine "ins2"-------
437 | continueRoutine = True
438 | # update component parameters for each repeat
439 | key_resp_ins2.keys = []
440 | key_resp_ins2.rt = []
441 | _key_resp_ins2_allKeys = []
442 | # keep track of which components have finished
443 | ins2Components = [ins2_text, key_resp_ins2]
444 | for thisComponent in ins2Components:
445 | thisComponent.tStart = None
446 | thisComponent.tStop = None
447 | thisComponent.tStartRefresh = None
448 | thisComponent.tStopRefresh = None
449 | if hasattr(thisComponent, 'status'):
450 | thisComponent.status = NOT_STARTED
451 | # reset timers
452 | t = 0
453 | _timeToFirstFrame = win.getFutureFlipTime(clock="now")
454 | ins2Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
455 | frameN = -1
456 |
457 | # -------Run Routine "ins2"-------
458 | while continueRoutine:
459 | # get current time
460 | t = ins2Clock.getTime()
461 | tThisFlip = win.getFutureFlipTime(clock=ins2Clock)
462 | tThisFlipGlobal = win.getFutureFlipTime(clock=None)
463 | frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
464 | # update/draw components on each frame
465 |
466 | # *ins2_text* updates
467 | if ins2_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
468 | # keep track of start time/frame for later
469 | ins2_text.frameNStart = frameN # exact frame index
470 | ins2_text.tStart = t # local t and not account for scr refresh
471 | ins2_text.tStartRefresh = tThisFlipGlobal # on global time
472 | win.timeOnFlip(ins2_text, 'tStartRefresh') # time at next scr refresh
473 | ins2_text.setAutoDraw(True)
474 |
475 | # *key_resp_ins2* updates
476 | waitOnFlip = False
477 | if key_resp_ins2.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
478 | # keep track of start time/frame for later
479 | key_resp_ins2.frameNStart = frameN # exact frame index
480 | key_resp_ins2.tStart = t # local t and not account for scr refresh
481 | key_resp_ins2.tStartRefresh = tThisFlipGlobal # on global time
482 | win.timeOnFlip(key_resp_ins2, 'tStartRefresh') # time at next scr refresh
483 | key_resp_ins2.status = STARTED
484 | # keyboard checking is just starting
485 | waitOnFlip = True
486 | win.callOnFlip(key_resp_ins2.clock.reset) # t=0 on next screen flip
487 | win.callOnFlip(key_resp_ins2.clearEvents, eventType='keyboard') # clear events on next screen flip
488 | if key_resp_ins2.status == STARTED and not waitOnFlip:
489 | theseKeys = key_resp_ins2.getKeys(keyList=['return'], waitRelease=False)
490 | _key_resp_ins2_allKeys.extend(theseKeys)
491 | if len(_key_resp_ins2_allKeys):
492 | key_resp_ins2.keys = _key_resp_ins2_allKeys[-1].name # just the last key pressed
493 | key_resp_ins2.rt = _key_resp_ins2_allKeys[-1].rt
494 | # a response ends the routine
495 | continueRoutine = False
496 |
497 | # check for quit (typically the Esc key)
498 | if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
499 | core.quit()
500 |
501 | # check if all components have finished
502 | if not continueRoutine: # a component has requested a forced-end of Routine
503 | break
504 | continueRoutine = False # will revert to True if at least one component still running
505 | for thisComponent in ins2Components:
506 | if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
507 | continueRoutine = True
508 | break # at least one component has not yet finished
509 |
510 | # refresh the screen
511 | if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
512 | win.flip()
513 |
514 | # -------Ending Routine "ins2"-------
515 | for thisComponent in ins2Components:
516 | if hasattr(thisComponent, "setAutoDraw"):
517 | thisComponent.setAutoDraw(False)
518 | thisExp.addData('ins2_text.started', ins2_text.tStartRefresh)
519 | thisExp.addData('ins2_text.stopped', ins2_text.tStopRefresh)
520 | # the Routine "ins2" was not non-slip safe, so reset the non-slip timer
521 | routineTimer.reset()
522 |
523 | # set up handler to look after randomisation of conditions etc
524 | exp1_trials = data.TrialHandler(nReps=3, method='random',
525 | extraInfo=expInfo, originPath=-1,
526 | trialList=data.importConditions('stimuli_list.xlsx'),
527 | seed=None, name='exp1_trials')
528 | thisExp.addLoop(exp1_trials) # add the loop to the experiment
529 | thisExp1_trial = exp1_trials.trialList[0] # so we can initialise stimuli with some values
530 | # abbreviate parameter names if possible (e.g. rgb = thisExp1_trial.rgb)
531 | if thisExp1_trial != None:
532 | for paramName in thisExp1_trial:
533 | exec('{} = thisExp1_trial[paramName]'.format(paramName))
534 |
535 | for thisExp1_trial in exp1_trials:
536 | currentLoop = exp1_trials
537 | # abbreviate parameter names if possible (e.g. rgb = thisExp1_trial.rgb)
538 | if thisExp1_trial != None:
539 | for paramName in thisExp1_trial:
540 | exec('{} = thisExp1_trial[paramName]'.format(paramName))
541 |
542 | # ------Prepare to start Routine "exp1"-------
543 | continueRoutine = True
544 | routineTimer.add(1.800000)
545 | # update component parameters for each repeat
546 | sti1_text.setText(sti)
547 | key_resp_2.keys = []
548 | key_resp_2.rt = []
549 | _key_resp_2_allKeys = []
550 | # keep track of which components have finished
551 | exp1Components = [fix1_text, sti1_text, key_resp_2]
552 | for thisComponent in exp1Components:
553 | thisComponent.tStart = None
554 | thisComponent.tStop = None
555 | thisComponent.tStartRefresh = None
556 | thisComponent.tStopRefresh = None
557 | if hasattr(thisComponent, 'status'):
558 | thisComponent.status = NOT_STARTED
559 | # reset timers
560 | t = 0
561 | _timeToFirstFrame = win.getFutureFlipTime(clock="now")
562 | exp1Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
563 | frameN = -1
564 |
565 | # -------Run Routine "exp1"-------
566 | while continueRoutine and routineTimer.getTime() > 0:
567 | # get current time
568 | t = exp1Clock.getTime()
569 | tThisFlip = win.getFutureFlipTime(clock=exp1Clock)
570 | tThisFlipGlobal = win.getFutureFlipTime(clock=None)
571 | frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
572 | # update/draw components on each frame
573 |
574 | # *fix1_text* updates
575 | if fix1_text.status == NOT_STARTED and tThisFlip >= 0.4-frameTolerance:
576 | # keep track of start time/frame for later
577 | fix1_text.frameNStart = frameN # exact frame index
578 | fix1_text.tStart = t # local t and not account for scr refresh
579 | fix1_text.tStartRefresh = tThisFlipGlobal # on global time
580 | win.timeOnFlip(fix1_text, 'tStartRefresh') # time at next scr refresh
581 | fix1_text.setAutoDraw(True)
582 | if fix1_text.status == STARTED:
583 | # is it time to stop? (based on global clock, using actual start)
584 | if tThisFlipGlobal > fix1_text.tStartRefresh + 0.5-frameTolerance:
585 | # keep track of stop time/frame for later
586 | fix1_text.tStop = t # not accounting for scr refresh
587 | fix1_text.frameNStop = frameN # exact frame index
588 | win.timeOnFlip(fix1_text, 'tStopRefresh') # time at next scr refresh
589 | fix1_text.setAutoDraw(False)
590 |
591 | # *sti1_text* updates
592 | if sti1_text.status == NOT_STARTED and tThisFlip >= 0.9-frameTolerance:
593 | # keep track of start time/frame for later
594 | sti1_text.frameNStart = frameN # exact frame index
595 | sti1_text.tStart = t # local t and not account for scr refresh
596 | sti1_text.tStartRefresh = tThisFlipGlobal # on global time
597 | win.timeOnFlip(sti1_text, 'tStartRefresh') # time at next scr refresh
598 | sti1_text.setAutoDraw(True)
599 | if sti1_text.status == STARTED:
600 | # is it time to stop? (based on global clock, using actual start)
601 | if tThisFlipGlobal > sti1_text.tStartRefresh + 0.1-frameTolerance:
602 | # keep track of stop time/frame for later
603 | sti1_text.tStop = t # not accounting for scr refresh
604 | sti1_text.frameNStop = frameN # exact frame index
605 | win.timeOnFlip(sti1_text, 'tStopRefresh') # time at next scr refresh
606 | sti1_text.setAutoDraw(False)
607 |
608 | # *key_resp_2* updates
609 | waitOnFlip = False
610 | if key_resp_2.status == NOT_STARTED and tThisFlip >= 1.0-frameTolerance:
611 | # keep track of start time/frame for later
612 | key_resp_2.frameNStart = frameN # exact frame index
613 | key_resp_2.tStart = t # local t and not account for scr refresh
614 | key_resp_2.tStartRefresh = tThisFlipGlobal # on global time
615 | win.timeOnFlip(key_resp_2, 'tStartRefresh') # time at next scr refresh
616 | key_resp_2.status = STARTED
617 | # keyboard checking is just starting
618 | waitOnFlip = True
619 | win.callOnFlip(key_resp_2.clock.reset) # t=0 on next screen flip
620 | win.callOnFlip(key_resp_2.clearEvents, eventType='keyboard') # clear events on next screen flip
621 | if key_resp_2.status == STARTED:
622 | # is it time to stop? (based on global clock, using actual start)
623 | if tThisFlipGlobal > key_resp_2.tStartRefresh + 0.8-frameTolerance:
624 | # keep track of stop time/frame for later
625 | key_resp_2.tStop = t # not accounting for scr refresh
626 | key_resp_2.frameNStop = frameN # exact frame index
627 | win.timeOnFlip(key_resp_2, 'tStopRefresh') # time at next scr refresh
628 | key_resp_2.status = FINISHED
629 | if key_resp_2.status == STARTED and not waitOnFlip:
630 | theseKeys = key_resp_2.getKeys(keyList=['space'], waitRelease=False)
631 | _key_resp_2_allKeys.extend(theseKeys)
632 | if len(_key_resp_2_allKeys):
633 | key_resp_2.keys = _key_resp_2_allKeys[-1].name # just the last key pressed
634 | key_resp_2.rt = _key_resp_2_allKeys[-1].rt
635 | # was this correct?
636 | if (key_resp_2.keys == str(ans)) or (key_resp_2.keys == ans):
637 | key_resp_2.corr = 1
638 | else:
639 | key_resp_2.corr = 0
640 | # a response ends the routine
641 | continueRoutine = False
642 |
643 | # check for quit (typically the Esc key)
644 | if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
645 | core.quit()
646 |
647 | # check if all components have finished
648 | if not continueRoutine: # a component has requested a forced-end of Routine
649 | break
650 | continueRoutine = False # will revert to True if at least one component still running
651 | for thisComponent in exp1Components:
652 | if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
653 | continueRoutine = True
654 | break # at least one component has not yet finished
655 |
656 | # refresh the screen
657 | if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
658 | win.flip()
659 |
660 | # -------Ending Routine "exp1"-------
661 | for thisComponent in exp1Components:
662 | if hasattr(thisComponent, "setAutoDraw"):
663 | thisComponent.setAutoDraw(False)
664 | exp1_trials.addData('fix1_text.started', fix1_text.tStartRefresh)
665 | exp1_trials.addData('fix1_text.stopped', fix1_text.tStopRefresh)
666 | exp1_trials.addData('sti1_text.started', sti1_text.tStartRefresh)
667 | exp1_trials.addData('sti1_text.stopped', sti1_text.tStopRefresh)
668 | # check responses
669 | if key_resp_2.keys in ['', [], None]: # No response was made
670 | key_resp_2.keys = None
671 | # was no response the correct answer?!
672 | if str(ans).lower() == 'none':
673 | key_resp_2.corr = 1; # correct non-response
674 | else:
675 | key_resp_2.corr = 0; # failed to respond (incorrectly)
676 | # store data for exp1_trials (TrialHandler)
677 | exp1_trials.addData('key_resp_2.keys',key_resp_2.keys)
678 | exp1_trials.addData('key_resp_2.corr', key_resp_2.corr)
679 | if key_resp_2.keys != None: # we had a response
680 | exp1_trials.addData('key_resp_2.rt', key_resp_2.rt)
681 | exp1_trials.addData('key_resp_2.started', key_resp_2.tStartRefresh)
682 | exp1_trials.addData('key_resp_2.stopped', key_resp_2.tStopRefresh)
683 | thisExp.nextEntry()
684 |
685 | # completed 3 repeats of 'exp1_trials'
686 |
687 |
688 | # ------Prepare to start Routine "rest"-------
689 | continueRoutine = True
690 | routineTimer.add(5.000000)
691 | # update component parameters for each repeat
692 | # keep track of which components have finished
693 | restComponents = [rest_text]
694 | for thisComponent in restComponents:
695 | thisComponent.tStart = None
696 | thisComponent.tStop = None
697 | thisComponent.tStartRefresh = None
698 | thisComponent.tStopRefresh = None
699 | if hasattr(thisComponent, 'status'):
700 | thisComponent.status = NOT_STARTED
701 | # reset timers
702 | t = 0
703 | _timeToFirstFrame = win.getFutureFlipTime(clock="now")
704 | restClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
705 | frameN = -1
706 |
707 | # -------Run Routine "rest"-------
708 | while continueRoutine and routineTimer.getTime() > 0:
709 | # get current time
710 | t = restClock.getTime()
711 | tThisFlip = win.getFutureFlipTime(clock=restClock)
712 | tThisFlipGlobal = win.getFutureFlipTime(clock=None)
713 | frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
714 | # update/draw components on each frame
715 |
716 | # *rest_text* updates
717 | if rest_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
718 | # keep track of start time/frame for later
719 | rest_text.frameNStart = frameN # exact frame index
720 | rest_text.tStart = t # local t and not account for scr refresh
721 | rest_text.tStartRefresh = tThisFlipGlobal # on global time
722 | win.timeOnFlip(rest_text, 'tStartRefresh') # time at next scr refresh
723 | rest_text.setAutoDraw(True)
724 | if rest_text.status == STARTED:
725 | # is it time to stop? (based on global clock, using actual start)
726 | if tThisFlipGlobal > rest_text.tStartRefresh + 5.0-frameTolerance:
727 | # keep track of stop time/frame for later
728 | rest_text.tStop = t # not accounting for scr refresh
729 | rest_text.frameNStop = frameN # exact frame index
730 | win.timeOnFlip(rest_text, 'tStopRefresh') # time at next scr refresh
731 | rest_text.setAutoDraw(False)
732 |
733 | # check for quit (typically the Esc key)
734 | if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
735 | core.quit()
736 |
737 | # check if all components have finished
738 | if not continueRoutine: # a component has requested a forced-end of Routine
739 | break
740 | continueRoutine = False # will revert to True if at least one component still running
741 | for thisComponent in restComponents:
742 | if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
743 | continueRoutine = True
744 | break # at least one component has not yet finished
745 |
746 | # refresh the screen
747 | if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
748 | win.flip()
749 |
750 | # -------Ending Routine "rest"-------
751 | for thisComponent in restComponents:
752 | if hasattr(thisComponent, "setAutoDraw"):
753 | thisComponent.setAutoDraw(False)
754 | thisExp.addData('rest_text.started', rest_text.tStartRefresh)
755 | thisExp.addData('rest_text.stopped', rest_text.tStopRefresh)
756 |
757 | # set up handler to look after randomisation of conditions etc
758 | exp2_trials = data.TrialHandler(nReps=3, method='random',
759 | extraInfo=expInfo, originPath=-1,
760 | trialList=data.importConditions('stimuli_list.xlsx'),
761 | seed=None, name='exp2_trials')
762 | thisExp.addLoop(exp2_trials) # add the loop to the experiment
763 | thisExp2_trial = exp2_trials.trialList[0] # so we can initialise stimuli with some values
764 | # abbreviate parameter names if possible (e.g. rgb = thisExp2_trial.rgb)
765 | if thisExp2_trial != None:
766 | for paramName in thisExp2_trial:
767 | exec('{} = thisExp2_trial[paramName]'.format(paramName))
768 |
769 | for thisExp2_trial in exp2_trials:
770 | currentLoop = exp2_trials
771 | # abbreviate parameter names if possible (e.g. rgb = thisExp2_trial.rgb)
772 | if thisExp2_trial != None:
773 | for paramName in thisExp2_trial:
774 | exec('{} = thisExp2_trial[paramName]'.format(paramName))
775 |
776 | # ------Prepare to start Routine "exp2"-------
777 | continueRoutine = True
778 | routineTimer.add(1.800000)
779 | # update component parameters for each repeat
780 | si2_text.setText(sti)
781 | key_resp_3.keys = []
782 | key_resp_3.rt = []
783 | _key_resp_3_allKeys = []
784 | # keep track of which components have finished
785 | exp2Components = [fix2_text, si2_text, key_resp_3]
786 | for thisComponent in exp2Components:
787 | thisComponent.tStart = None
788 | thisComponent.tStop = None
789 | thisComponent.tStartRefresh = None
790 | thisComponent.tStopRefresh = None
791 | if hasattr(thisComponent, 'status'):
792 | thisComponent.status = NOT_STARTED
793 | # reset timers
794 | t = 0
795 | _timeToFirstFrame = win.getFutureFlipTime(clock="now")
796 | exp2Clock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
797 | frameN = -1
798 |
799 | # -------Run Routine "exp2"-------
800 | while continueRoutine and routineTimer.getTime() > 0:
801 | # get current time
802 | t = exp2Clock.getTime()
803 | tThisFlip = win.getFutureFlipTime(clock=exp2Clock)
804 | tThisFlipGlobal = win.getFutureFlipTime(clock=None)
805 | frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
806 | # update/draw components on each frame
807 |
808 | # *fix2_text* updates
809 | if fix2_text.status == NOT_STARTED and tThisFlip >= 0.4-frameTolerance:
810 | # keep track of start time/frame for later
811 | fix2_text.frameNStart = frameN # exact frame index
812 | fix2_text.tStart = t # local t and not account for scr refresh
813 | fix2_text.tStartRefresh = tThisFlipGlobal # on global time
814 | win.timeOnFlip(fix2_text, 'tStartRefresh') # time at next scr refresh
815 | fix2_text.setAutoDraw(True)
816 | if fix2_text.status == STARTED:
817 | # is it time to stop? (based on global clock, using actual start)
818 | if tThisFlipGlobal > fix2_text.tStartRefresh + 0.5-frameTolerance:
819 | # keep track of stop time/frame for later
820 | fix2_text.tStop = t # not accounting for scr refresh
821 | fix2_text.frameNStop = frameN # exact frame index
822 | win.timeOnFlip(fix2_text, 'tStopRefresh') # time at next scr refresh
823 | fix2_text.setAutoDraw(False)
824 |
825 | # *si2_text* updates
826 | if si2_text.status == NOT_STARTED and tThisFlip >= 0.9-frameTolerance:
827 | # keep track of start time/frame for later
828 | si2_text.frameNStart = frameN # exact frame index
829 | si2_text.tStart = t # local t and not account for scr refresh
830 | si2_text.tStartRefresh = tThisFlipGlobal # on global time
831 | win.timeOnFlip(si2_text, 'tStartRefresh') # time at next scr refresh
832 | si2_text.setAutoDraw(True)
833 | if si2_text.status == STARTED:
834 | # is it time to stop? (based on global clock, using actual start)
835 | if tThisFlipGlobal > si2_text.tStartRefresh + 0.1-frameTolerance:
836 | # keep track of stop time/frame for later
837 | si2_text.tStop = t # not accounting for scr refresh
838 | si2_text.frameNStop = frameN # exact frame index
839 | win.timeOnFlip(si2_text, 'tStopRefresh') # time at next scr refresh
840 | si2_text.setAutoDraw(False)
841 |
842 | # *key_resp_3* updates
843 | waitOnFlip = False
844 | if key_resp_3.status == NOT_STARTED and tThisFlip >= 1.0-frameTolerance:
845 | # keep track of start time/frame for later
846 | key_resp_3.frameNStart = frameN # exact frame index
847 | key_resp_3.tStart = t # local t and not account for scr refresh
848 | key_resp_3.tStartRefresh = tThisFlipGlobal # on global time
849 | win.timeOnFlip(key_resp_3, 'tStartRefresh') # time at next scr refresh
850 | key_resp_3.status = STARTED
851 | # keyboard checking is just starting
852 | waitOnFlip = True
853 | win.callOnFlip(key_resp_3.clock.reset) # t=0 on next screen flip
854 | win.callOnFlip(key_resp_3.clearEvents, eventType='keyboard') # clear events on next screen flip
855 | if key_resp_3.status == STARTED:
856 | # is it time to stop? (based on global clock, using actual start)
857 | if tThisFlipGlobal > key_resp_3.tStartRefresh + 0.8-frameTolerance:
858 | # keep track of stop time/frame for later
859 | key_resp_3.tStop = t # not accounting for scr refresh
860 | key_resp_3.frameNStop = frameN # exact frame index
861 | win.timeOnFlip(key_resp_3, 'tStopRefresh') # time at next scr refresh
862 | key_resp_3.status = FINISHED
863 | if key_resp_3.status == STARTED and not waitOnFlip:
864 | theseKeys = key_resp_3.getKeys(keyList=['space'], waitRelease=False)
865 | _key_resp_3_allKeys.extend(theseKeys)
866 | if len(_key_resp_3_allKeys):
867 | key_resp_3.keys = _key_resp_3_allKeys[-1].name # just the last key pressed
868 | key_resp_3.rt = _key_resp_3_allKeys[-1].rt
869 | # was this correct?
870 | if (key_resp_3.keys == str(ans)) or (key_resp_3.keys == ans):
871 | key_resp_3.corr = 1
872 | else:
873 | key_resp_3.corr = 0
874 | # a response ends the routine
875 | continueRoutine = False
876 |
877 | # check for quit (typically the Esc key)
878 | if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
879 | core.quit()
880 |
881 | # check if all components have finished
882 | if not continueRoutine: # a component has requested a forced-end of Routine
883 | break
884 | continueRoutine = False # will revert to True if at least one component still running
885 | for thisComponent in exp2Components:
886 | if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
887 | continueRoutine = True
888 | break # at least one component has not yet finished
889 |
890 | # refresh the screen
891 | if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
892 | win.flip()
893 |
894 | # -------Ending Routine "exp2"-------
895 | for thisComponent in exp2Components:
896 | if hasattr(thisComponent, "setAutoDraw"):
897 | thisComponent.setAutoDraw(False)
898 | exp2_trials.addData('fix2_text.started', fix2_text.tStartRefresh)
899 | exp2_trials.addData('fix2_text.stopped', fix2_text.tStopRefresh)
900 | exp2_trials.addData('si2_text.started', si2_text.tStartRefresh)
901 | exp2_trials.addData('si2_text.stopped', si2_text.tStopRefresh)
902 | # check responses
903 | if key_resp_3.keys in ['', [], None]: # No response was made
904 | key_resp_3.keys = None
905 | # was no response the correct answer?!
906 | if str(ans).lower() == 'none':
907 | key_resp_3.corr = 1; # correct non-response
908 | else:
909 | key_resp_3.corr = 0; # failed to respond (incorrectly)
910 | # store data for exp2_trials (TrialHandler)
911 | exp2_trials.addData('key_resp_3.keys',key_resp_3.keys)
912 | exp2_trials.addData('key_resp_3.corr', key_resp_3.corr)
913 | if key_resp_3.keys != None: # we had a response
914 | exp2_trials.addData('key_resp_3.rt', key_resp_3.rt)
915 | exp2_trials.addData('key_resp_3.started', key_resp_3.tStartRefresh)
916 | exp2_trials.addData('key_resp_3.stopped', key_resp_3.tStopRefresh)
917 | thisExp.nextEntry()
918 |
919 | # completed 3 repeats of 'exp2_trials'
920 |
921 |
922 | # ------Prepare to start Routine "finish"-------
923 | continueRoutine = True
924 | # update component parameters for each repeat
925 | key_resp_finish.keys = []
926 | key_resp_finish.rt = []
927 | _key_resp_finish_allKeys = []
928 | # keep track of which components have finished
929 | finishComponents = [finish_text, key_resp_finish]
930 | for thisComponent in finishComponents:
931 | thisComponent.tStart = None
932 | thisComponent.tStop = None
933 | thisComponent.tStartRefresh = None
934 | thisComponent.tStopRefresh = None
935 | if hasattr(thisComponent, 'status'):
936 | thisComponent.status = NOT_STARTED
937 | # reset timers
938 | t = 0
939 | _timeToFirstFrame = win.getFutureFlipTime(clock="now")
940 | finishClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip
941 | frameN = -1
942 |
943 | # -------Run Routine "finish"-------
944 | while continueRoutine:
945 | # get current time
946 | t = finishClock.getTime()
947 | tThisFlip = win.getFutureFlipTime(clock=finishClock)
948 | tThisFlipGlobal = win.getFutureFlipTime(clock=None)
949 | frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
950 | # update/draw components on each frame
951 |
952 | # *finish_text* updates
953 | if finish_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
954 | # keep track of start time/frame for later
955 | finish_text.frameNStart = frameN # exact frame index
956 | finish_text.tStart = t # local t and not account for scr refresh
957 | finish_text.tStartRefresh = tThisFlipGlobal # on global time
958 | win.timeOnFlip(finish_text, 'tStartRefresh') # time at next scr refresh
959 | finish_text.setAutoDraw(True)
960 |
961 | # *key_resp_finish* updates
962 | waitOnFlip = False
963 | if key_resp_finish.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
964 | # keep track of start time/frame for later
965 | key_resp_finish.frameNStart = frameN # exact frame index
966 | key_resp_finish.tStart = t # local t and not account for scr refresh
967 | key_resp_finish.tStartRefresh = tThisFlipGlobal # on global time
968 | win.timeOnFlip(key_resp_finish, 'tStartRefresh') # time at next scr refresh
969 | key_resp_finish.status = STARTED
970 | # keyboard checking is just starting
971 | waitOnFlip = True
972 | win.callOnFlip(key_resp_finish.clock.reset) # t=0 on next screen flip
973 | win.callOnFlip(key_resp_finish.clearEvents, eventType='keyboard') # clear events on next screen flip
974 | if key_resp_finish.status == STARTED and not waitOnFlip:
975 | theseKeys = key_resp_finish.getKeys(keyList=['y', 'n', 'left', 'right', 'space', 'return'], waitRelease=False)
976 | _key_resp_finish_allKeys.extend(theseKeys)
977 | if len(_key_resp_finish_allKeys):
978 | key_resp_finish.keys = _key_resp_finish_allKeys[-1].name # just the last key pressed
979 | key_resp_finish.rt = _key_resp_finish_allKeys[-1].rt
980 | # a response ends the routine
981 | continueRoutine = False
982 |
983 | # check for quit (typically the Esc key)
984 | if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
985 | core.quit()
986 |
987 | # check if all components have finished
988 | if not continueRoutine: # a component has requested a forced-end of Routine
989 | break
990 | continueRoutine = False # will revert to True if at least one component still running
991 | for thisComponent in finishComponents:
992 | if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
993 | continueRoutine = True
994 | break # at least one component has not yet finished
995 |
996 | # refresh the screen
997 | if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
998 | win.flip()
999 |
1000 | # -------Ending Routine "finish"-------
1001 | for thisComponent in finishComponents:
1002 | if hasattr(thisComponent, "setAutoDraw"):
1003 | thisComponent.setAutoDraw(False)
1004 | thisExp.addData('finish_text.started', finish_text.tStartRefresh)
1005 | thisExp.addData('finish_text.stopped', finish_text.tStopRefresh)
1006 | # the Routine "finish" was not non-slip safe, so reset the non-slip timer
1007 | routineTimer.reset()
1008 |
1009 | # Flip one final time so any remaining win.callOnFlip()
1010 | # and win.timeOnFlip() tasks get executed before quitting
1011 | win.flip()
1012 |
1013 | # these shouldn't be strictly necessary (should auto-save)
1014 | thisExp.saveAsWideText(filename+'.csv', delim='auto')
1015 | thisExp.saveAsPickle(filename)
1016 | logging.flush()
1017 | # make sure everything is closed down
1018 | thisExp.abort() # or data files will save again on exit
1019 | win.close()
1020 | core.quit()
1021 |
--------------------------------------------------------------------------------
/PsychoPy/gonogo_test.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | Created on Sun Jul 08 10:14:59 2018
4 | Modified on Sat Nov 21 15:15:15 2020
5 |
6 | @author: ryan
7 | """
8 |
9 | from datetime import datetime
10 | from psychopy import core, gui, visual, event
11 | from random import shuffle
12 |
13 | data = {}
14 | data['Expname'] = 'Go/nogo Test'
15 | #Creat a string version of the current year/month/day hour/minute
16 | data['Expdate'] = datetime.now().strftime('%Y%m%d_%H%M')
17 | data['ParticipantID'] = ''
18 | data['Gender'] = ''
19 |
20 | #Set up input dialog
21 | #Use the 'fixed' argument to stop the user changing the 'expname' and 'expdate' parameter
22 | #Use the 'order' argument to set the order in which to display the fields
23 | dlg = gui.DlgFromDict(data, title='Input data', fixed=['Expname','Expdate'],
24 | order=['Expname','Expdate','ParticipantID','Gender'])
25 |
26 | #if participant quit, scripts end here
27 | if not dlg.OK:
28 | print("User cancelled the experiment")
29 | core.quit()
30 |
31 | filename = 'part_%s_%s.csv' % (data['ParticipantID'],data['Expdate'])
32 | f = open(filename, 'a+')
33 |
34 | #Print the title of data form
35 | f.write('trialID,stimuli,rt,acc\n')
36 |
37 | #set experiment window
38 | win = visual.Window([1024,768],fullscr = False, \
39 | allowGUI =True, units = "pix", color = (0,0,0))
40 |
41 | #set instructions of the experiment
42 | instruction1 = visual.TextStim(win, text = 'If you see M, press SPACE, if see W, do nothing', pos=(0, 88), color = (1,1,1))
43 | instruction2 = visual.TextStim(win, text = 'Press ENTER to start practice', pos=(0, -88), color = (1,1,1))
44 | instruction3 = visual.TextStim(win, text = 'Press ENTER to start experiment', pos=(0, -88), color = (1,1,1))
45 | instruction4 = visual.TextStim(win, text = 'Rest for a while', pos=(0, -88), color = (1,1,1))
46 | instruction5 = visual.TextStim(win, text = 'This is the end of the experiment. Thank you!', pos=(0, -88), color = (1,1,1))
47 |
48 | #set fixations and stimuli of the experiment
49 | fix = visual.TextStim(win, text = '+', height=50, pos=(0, 0), color = (1,1,1))
50 |
51 | sti = visual.TextStim(win, text = 'B', height=36, pos=(0, 0), color = (1,1,1))
52 |
53 | #define a empty list for storing stimulis
54 | sti_list = []
55 |
56 | #define a function for trial loop
57 | def trial(n_trial):
58 | #randomize the stimulus list
59 | shuffle(sti_list)
60 | for i in range(n_trial):
61 | core.wait(0.4)
62 | fix.draw()
63 | win.flip()
64 | core.wait(0.5)
65 | sti.setText(sti_list[i])
66 | sti.draw()
67 | displaytime = win.flip()
68 | core.wait(0.1)
69 | win.flip()
70 | core.wait(0.8)
71 | keys = event.getKeys(keyList=['space'],timeStamped=True)
72 |
73 | #calculate rt
74 | if keys:
75 | rt = keys[0][1] - displaytime
76 | else:
77 | rt = "none"
78 |
79 | #calculate accuracy
80 | if sti_list[i] == "M":
81 | if not keys:
82 | acc = "0"
83 | else:
84 | acc = "1"
85 | elif sti_list[i] == "W":
86 | if not keys:
87 | acc = "1"
88 | else:
89 | acc = "0"
90 |
91 | #write into data file
92 | f.write(str(n_trial) + ',')
93 | f.write(sti_list[i] + ',')
94 | f.write(str(rt) + ',')
95 | f.write(acc + ',')
96 | f.write('\n')
97 |
98 | instruction1.draw()
99 | instruction2.draw()
100 | win.flip()
101 | event.waitKeys(keyList=['return'])
102 | core.wait(1.0)
103 |
104 | #set the practice stimulus list (fixed)
105 | sti_list = ["M","W","M","W","M","W","M","W","M","W","M","W","M","W"]
106 |
107 | #practice block
108 | trial(10)
109 |
110 | #mark between practice and experiment
111 | f.write('experiment starts below\n')
112 |
113 | #ready to run the experiment
114 | win.flip()
115 | instruction3.draw()
116 | win.flip()
117 | event.waitKeys(keyList=['return'])
118 | core.wait(1.0)
119 |
120 | #set the first experiment stimulus list (generate)
121 | sti_list = []
122 | temp = ["M","W","W","W","W"]
123 | for i in range(3):
124 | sti_list.extend(temp)
125 |
126 | #first experiment block begin
127 | trial(15)
128 |
129 | #rest
130 | instruction4.draw()
131 | win.flip()
132 | core.wait(5.0)
133 |
134 | #second experiment block begin
135 | trial(15)
136 |
137 | #the end of the experiment, close the window and exit psychopy core
138 | instruction5.draw()
139 | win.flip()
140 | event.waitKeys()
141 | win.close()
142 | core.quit()
--------------------------------------------------------------------------------
/PsychoPy/stimuli_list.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/PsychoPy/stimuli_list.xlsx
--------------------------------------------------------------------------------
/PsychoPy/stroop.psyexp:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/PsychoPy/微信公众号.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/PsychoPy/微信公众号.png
--------------------------------------------------------------------------------
/PsychoPy/扫码_搜索联合传播样式-微信标准绿版.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/PsychoPy/扫码_搜索联合传播样式-微信标准绿版.png
--------------------------------------------------------------------------------
/PsychoPy/群二维码.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/PsychoPy/群二维码.png
--------------------------------------------------------------------------------
/PythonPipeline_DataAnalysis_Psychology_HaiyangGeng/README.md:
--------------------------------------------------------------------------------
1 | Python version is 2.7.
2 | For the dependence, please look into the beginning of the notebook.
3 |
--------------------------------------------------------------------------------
/PythonPipeline_DataAnalysis_Psychology_HaiyangGeng/SE-QPE_40_demo1118.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/PythonPipeline_DataAnalysis_Psychology_HaiyangGeng/SE-QPE_40_demo1118.xlsx
--------------------------------------------------------------------------------
/PythonPipeline_DataAnalysis_Psychology_HaiyangGeng/SE_all_demo1118.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/PythonPipeline_DataAnalysis_Psychology_HaiyangGeng/SE_all_demo1118.xlsx
--------------------------------------------------------------------------------
/PythonPipeline_DataAnalysis_Psychology_HaiyangGeng/SE_basic_infor_demo1118.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/PythonPipeline_DataAnalysis_Psychology_HaiyangGeng/SE_basic_infor_demo1118.xlsx
--------------------------------------------------------------------------------
/PythonPipeline_DataAnalysis_Psychology_HaiyangGeng/SE_scale_demo1118.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/PythonPipeline_DataAnalysis_Psychology_HaiyangGeng/SE_scale_demo1118.xlsx
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Python-Workshop-SuZhou
2 | A place where all demo code and data are stored.
3 |
4 | For the the details of the conference and workshop, please go to [第七届全国脑电与脑成像研究与应用研讨会](http://www.cognscigd.cn/2020/11/16/%e7%ac%ac%e4%b8%83%e5%b1%8a%e5%85%a8%e5%9b%bd%e8%84%91%e7%94%b5%e4%b8%8e%e8%84%91%e6%88%90%e5%83%8f%e7%a0%94%e7%a9%b6%e4%b8%8e%e5%ba%94%e7%94%a8%e7%a0%94%e8%ae%a8%e4%bc%9a%ef%bc%88%e7%ac%ac%e4%b8%89/)
5 |
6 | The workshop will be hold on 1:30 pm 22th Nov, 2020, Fucui Hall, NanLin Hotel.
7 |
8 |
9 | | | | |
10 | |-----|-------------------------------------|-------------|
11 | | 报告人 | 主题 | 时间 |
12 | | 耿海洋 | Python在心理学(行为)数据分析中的应用,一个标准化流程 | 13:30-14:00 |
13 | | 夏涛 | Python在EEG数据分析中的应用,以MNE为例 | 14:00-14:30 |
14 | | 胡传鹏 | Python在计算建模中的应用,以HDDM为例 | 14:30-15:00 |
15 | | | 答疑 | 15:00-15:15 |
16 | | 孔祥祯 | Python在fMRI数据分析中的应用,以fMRIprep为例 | 15:15-15:45 |
17 | | 杨子鹏 | Python在实验程序编写和设计中的应用,以PsychoPy为例 | 15:45-16:15 |
18 | | 黎超 | Python在神经影像机器学习中的应用,以scikit-learn为例 | 16:15-16:45 |
19 | | | 答疑 | 16:45-17:00 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/fMRIPrep/README.md:
--------------------------------------------------------------------------------
1 | # Neuroimaging in Python: fMRIPrep
2 | > Xiangzhen Kong, Zhejiang Univeristy
3 | > https://person.zju.edu.cn/konglab#lab
4 |
5 | ### Installation
6 | Two ways
7 | - [Mannually prepared enviroment](https://fmriprep.org/en/stable/installation.html#manually-prepared-environment-python-3-7) (Python 3.7+)
8 | - Use container technologies (RECOMMENDED), e.g., [Docker](https://fmriprep.org/en/stable/docker.html#run-docker) and [Singularity](https://fmriprep.org/en/stable/singularity.html#run-singularity)
9 |
10 | ### Usage Notes
11 | fMRIPrep can be ran via the command *fmriprep* directly, or via the command *docker run*, or via the *fmriprep-docker* wrapper. The *fmriprep-docker* accepts all of the typical options for fMRIPrep. To simplify the practice, we use *fmriprep-docker* for this course.
12 | - [Command-Line Arguments](https://fmriprep.org/en/stable/usage.html)
13 |
14 | ### Examples
15 | `docker run -rm hello-world`
16 |
17 | `python -m pip install --user --upgrade fmriprep-docker`
18 |
19 | `fmriprep-docker .\ds003030\ .\output\ participant --fs-licence-file .\license.txt`
20 |
21 | `fmriprep-docker .\ds003030\ .\output\ participant --fs-licence-file .\license.txt --fs-no-reconall`
22 |
23 | File *license.txt* is the FreeSurfer license file, which can be applied via this [link](https://surfer.nmr.mgh.harvard.edu/registration.html). When you receive the license file, put a copy to the main folder (i.e., the same folder as *output*, *ds003030_select*, and *README.md*).
24 |
25 | **To be updated ...**
26 |
27 | ### Links
28 | fMRIPrep https://fmriprep.org/en/stable/index.html
29 |
30 | Nipype https://nipype.readthedocs.io/en/latest/
31 |
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/CHANGES:
--------------------------------------------------------------------------------
1 |
2 | 1.0.0 2020-07-27
3 |
4 | - Initial snapshot
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/dataset_description.json:
--------------------------------------------------------------------------------
1 | {
2 | "Name": "Flickering Checkerboard Demo Scans",
3 | "BIDSVersion": "1.1.1",
4 | "License": "CC0",
5 | "Authors": [
6 | "C. Brock Kirwan"
7 | ],
8 | "DatasetDOI": "10.18112/openneuro.ds003030.v1.0.0"
9 | }
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/participants.tsv:
--------------------------------------------------------------------------------
1 | participant_id age sex
2 | sub-01 23 M
3 | sub-02 53 M
4 |
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/sub-01/anat/sub-01_T1w.json:
--------------------------------------------------------------------------------
1 | {
2 | "Modality": "MR",
3 | "MagneticFieldStrength": 3,
4 | "ImagingFrequency": 123.263,
5 | "Manufacturer": "Siemens",
6 | "ManufacturersModelName": "TrioTim",
7 | "InstitutionName": "Brigham_Young_University",
8 | "InstitutionalDepartmentName": "MRI",
9 | "InstitutionAddress": "University_Pkwy_1700_North_685_Provo_FCF749_UT_US_84601",
10 | "DeviceSerialNumber": "35002",
11 | "StationName": "MRC35002",
12 | "PatientPosition": "HFS",
13 | "ProcedureStepDescription": "Research_KIRWAN",
14 | "SoftwareVersions": "syngo_MR_B17",
15 | "MRAcquisitionType": "3D",
16 | "SeriesDescription": "t1_mpr_sag_iso_(mprage)",
17 | "ProtocolName": "t1_mpr_sag_iso_(mprage)",
18 | "ScanningSequence": "GR_IR",
19 | "SequenceVariant": "SP_MP_OSP",
20 | "ScanOptions": "IR_PFP",
21 | "SequenceName": "_tfl3d1_ns",
22 | "ImageType": ["ORIGINAL", "PRIMARY", "M", "ND", "NORM"],
23 | "SeriesNumber": 2,
24 | "AcquisitionTime": "10:23:50.052500",
25 | "AcquisitionNumber": 1,
26 | "SliceThickness": 1,
27 | "SAR": 0.0996595,
28 | "EchoTime": 0.00226,
29 | "RepetitionTime": 1.9,
30 | "InversionTime": 0.9,
31 | "FlipAngle": 9,
32 | "PartialFourier": 0.875,
33 | "BaseResolution": 256,
34 | "ShimSetting": [
35 | -2768,
36 | -22810,
37 | 1838,
38 | -69,
39 | 10,
40 | 173,
41 | -426,
42 | 363 ],
43 | "TxRefAmp": 386.42,
44 | "PhaseResolution": 0.96,
45 | "PhaseOversampling": 0.2,
46 | "ReceiveCoilName": "HeadMatrix",
47 | "CoilString": "C:HEA;HEP",
48 | "PulseSequenceDetails": "%SiemensSeq%_tfl",
49 | "PercentPhaseFOV": 87.5,
50 | "PhaseEncodingSteps": 227,
51 | "AcquisitionMatrixPE": 215,
52 | "ReconMatrixPE": 224,
53 | "PixelBandwidth": 199,
54 | "DwellTime": 9.8e-06,
55 | "ImageOrientationPatientDICOM": [
56 | 0,
57 | 1,
58 | 0,
59 | 0,
60 | 0,
61 | -1 ],
62 | "InPlanePhaseEncodingDirectionDICOM": "ROW",
63 | "ConversionSoftware": "dcm2niix",
64 | "ConversionSoftwareVersion": "v1.0.20190902"
65 | }
66 |
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/sub-01/anat/sub-01_T1w.nii.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/fMRIPrep/ds003030_select/sub-01/anat/sub-01_T1w.nii.gz
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/sub-01/func/sub-01_task-FlickeringCheckerBoard_run-1_bold.json:
--------------------------------------------------------------------------------
1 | {
2 | "Modality": "MR",
3 | "MagneticFieldStrength": 3,
4 | "ImagingFrequency": 123.263,
5 | "Manufacturer": "Siemens",
6 | "ManufacturersModelName": "TrioTim",
7 | "InstitutionName": "Brigham_Young_University",
8 | "InstitutionalDepartmentName": "MRI",
9 | "InstitutionAddress": "University_Pkwy_1700_North_685_Provo_FCF749_UT_US_84601",
10 | "DeviceSerialNumber": "35002",
11 | "StationName": "MRC35002",
12 | "PatientPosition": "HFS",
13 | "ProcedureStepDescription": "Research_KIRWAN",
14 | "SoftwareVersions": "syngo_MR_B17",
15 | "MRAcquisitionType": "2D",
16 | "SeriesDescription": "act_fMRI_Demo",
17 | "ProtocolName": "fMRI_Demo",
18 | "ScanningSequence": "EP",
19 | "SequenceVariant": "SK",
20 | "ScanOptions": "FS",
21 | "SequenceName": "epfid2d1_64",
22 | "ImageType": [
23 | "ORIGINAL",
24 | "PRIMARY",
25 | "FMRI",
26 | "NONE",
27 | "ND",
28 | "MOSAIC"
29 | ],
30 | "SeriesNumber": 4,
31 | "AcquisitionTime": "10:31:57.882500",
32 | "AcquisitionNumber": 1,
33 | "SliceThickness": 3,
34 | "SpacingBetweenSlices": 3,
35 | "SAR": 0.137259,
36 | "EchoTime": 0.028,
37 | "RepetitionTime": 2.5,
38 | "FlipAngle": 90,
39 | "PartialFourier": 1,
40 | "BaseResolution": 64,
41 | "ShimSetting": [
42 | -2778,
43 | -22846,
44 | 2272,
45 | 554,
46 | 2,
47 | 135,
48 | -175,
49 | 424
50 | ],
51 | "TxRefAmp": 386.42,
52 | "PhaseResolution": 1,
53 | "ReceiveCoilName": "HeadMatrix",
54 | "CoilString": "C:HEA;HEP",
55 | "PulseSequenceDetails": "%CustomerSeq%_ep2d_bold_PMU",
56 | "PercentPhaseFOV": 100,
57 | "PhaseEncodingSteps": 64,
58 | "AcquisitionMatrixPE": 64,
59 | "ReconMatrixPE": 64,
60 | "BandwidthPerPixelPhaseEncode": 36.337,
61 | "EffectiveEchoSpacing": 0.000430002,
62 | "DerivedVendorReportedEchoSpacing": 0.000430002,
63 | "TotalReadoutTime": 0.0270902,
64 | "PixelBandwidth": 2894,
65 | "DwellTime": 2.7e-06,
66 | "PhaseEncodingDirection": "j-",
67 | "SliceTiming": [
68 | 1.255,
69 | 0,
70 | 1.3175,
71 | 0.0625,
72 | 1.38,
73 | 0.125,
74 | 1.4425,
75 | 0.1875,
76 | 1.505,
77 | 0.25,
78 | 1.5675,
79 | 0.3125,
80 | 1.63,
81 | 0.375,
82 | 1.6925,
83 | 0.44,
84 | 1.7575,
85 | 0.5025,
86 | 1.82,
87 | 0.565,
88 | 1.8825,
89 | 0.6275,
90 | 1.945,
91 | 0.69,
92 | 2.0075,
93 | 0.7525,
94 | 2.07,
95 | 0.815,
96 | 2.1325,
97 | 0.8775,
98 | 2.195,
99 | 0.94,
100 | 2.2575,
101 | 1.0025,
102 | 2.32,
103 | 1.0675,
104 | 2.385,
105 | 1.13,
106 | 2.4475,
107 | 1.1925
108 | ],
109 | "ImageOrientationPatientDICOM": [
110 | 1,
111 | 0,
112 | 0,
113 | 0,
114 | 1,
115 | 0
116 | ],
117 | "InPlanePhaseEncodingDirectionDICOM": "COL",
118 | "ConversionSoftware": "dcm2niix",
119 | "ConversionSoftwareVersion": "v1.0.20190902",
120 | "TaskName": "FlickeringCheckerBoard"
121 | }
122 |
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/sub-01/func/sub-01_task-FlickeringCheckerBoard_run-1_bold.nii.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/fMRIPrep/ds003030_select/sub-01/func/sub-01_task-FlickeringCheckerBoard_run-1_bold.nii.gz
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/sub-01/func/sub-01_task-FlickeringCheckerBoard_run-1_events.tsv:
--------------------------------------------------------------------------------
1 | onset duration trial_type
2 | 0 20 Checkerboard
3 | 20 20 Music
4 | 40 20 Checkerboard
5 | 60 20 Music
6 | 80 20 Checkerboard
7 | 100 20 Music
8 | 120 20 Checkerboard
9 | 140 20 Music
10 | 160 20 Checkerboard
11 | 180 20 Music
12 | 200 20 Checkerboard
13 | 220 20 Music
14 | 240 20 Checkerboard
15 | 260 20 Music
16 | 280 20 Checkerboard
17 | 300 20 Music
18 | 320 20 Checkerboard
19 | 340 20 Music
20 | 360 20 Checkerboard
21 | 380 20 Music
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/sub-02/anat/sub-02_T1w.json:
--------------------------------------------------------------------------------
1 | {
2 | "Modality": "MR",
3 | "MagneticFieldStrength": 3,
4 | "ImagingFrequency": 123.261,
5 | "Manufacturer": "Siemens",
6 | "ManufacturersModelName": "TrioTim",
7 | "InstitutionName": "Brigham_Young_University",
8 | "InstitutionAddress": "University_Pkwy_1700_North_685_Provo_UT_US_84601",
9 | "DeviceSerialNumber": "35002",
10 | "StationName": "MININT-E41B04",
11 | "PatientPosition": "HFS",
12 | "ProcedureStepDescription": "Research_KIRWAN",
13 | "SoftwareVersions": "syngo_MR_B17",
14 | "MRAcquisitionType": "3D",
15 | "SeriesDescription": "t1_mpr_sag_iso_(mprage)",
16 | "ProtocolName": "t1_mpr_sag_iso_(mprage)",
17 | "ScanningSequence": "GR_IR",
18 | "SequenceVariant": "SP_MP_OSP",
19 | "ScanOptions": "IR_PFP",
20 | "SequenceName": "_tfl3d1_ns",
21 | "ImageType": ["ORIGINAL", "PRIMARY", "M", "ND", "NORM"],
22 | "SeriesNumber": 2,
23 | "AcquisitionTime": "15:17:3.095000",
24 | "AcquisitionNumber": 1,
25 | "SliceThickness": 1,
26 | "SAR": 0.086199,
27 | "EchoTime": 0.00226,
28 | "RepetitionTime": 1.9,
29 | "InversionTime": 0.9,
30 | "FlipAngle": 9,
31 | "PartialFourier": 0.875,
32 | "BaseResolution": 256,
33 | "ShimSetting": [
34 | -2824,
35 | -22910,
36 | 1912,
37 | -115,
38 | -88,
39 | -35,
40 | -292,
41 | 395 ],
42 | "TxRefAmp": 388.099,
43 | "PhaseResolution": 0.96,
44 | "PhaseOversampling": 0.2,
45 | "ReceiveCoilName": "HeadMatrix",
46 | "PulseSequenceDetails": "%SiemensSeq%_tfl",
47 | "PercentPhaseFOV": 87.5,
48 | "PhaseEncodingSteps": 227,
49 | "AcquisitionMatrixPE": 215,
50 | "ReconMatrixPE": 224,
51 | "PixelBandwidth": 199,
52 | "ImageOrientationPatientDICOM": [
53 | 0,
54 | 1,
55 | 0,
56 | -0.0471064,
57 | 0,
58 | -0.99889 ],
59 | "InPlanePhaseEncodingDirectionDICOM": "ROW",
60 | "ConversionSoftware": "dcm2niix",
61 | "ConversionSoftwareVersion": "v1.0.20190902"
62 | }
63 |
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/sub-02/anat/sub-02_T1w.nii.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/fMRIPrep/ds003030_select/sub-02/anat/sub-02_T1w.nii.gz
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/sub-02/func/sub-02_task-FlickeringCheckerBoard_run-1_bold.json:
--------------------------------------------------------------------------------
1 | {
2 | "Modality": "MR",
3 | "MagneticFieldStrength": 3,
4 | "ImagingFrequency": 123.261,
5 | "Manufacturer": "Siemens",
6 | "ManufacturersModelName": "TrioTim",
7 | "InstitutionName": "Brigham_Young_University",
8 | "InstitutionalDepartmentName": "MRI",
9 | "InstitutionAddress": "University_Pkwy_1700_North_685_Provo_UT_US_84601",
10 | "DeviceSerialNumber": "35002",
11 | "StationName": "MININT-E41B04",
12 | "PatientPosition": "HFS",
13 | "ProcedureStepDescription": "Research_KIRWAN",
14 | "SoftwareVersions": "syngo_MR_B17",
15 | "MRAcquisitionType": "2D",
16 | "SeriesDescription": "act_fMRI_Demo",
17 | "ProtocolName": "fMRI_Demo",
18 | "ScanningSequence": "EP",
19 | "SequenceVariant": "SK",
20 | "ScanOptions": "FS",
21 | "SequenceName": "epfid2d1_64",
22 | "ImageType": [
23 | "ORIGINAL",
24 | "PRIMARY",
25 | "FMRI",
26 | "NONE",
27 | "ND",
28 | "MOSAIC"
29 | ],
30 | "SeriesNumber": 4,
31 | "AcquisitionTime": "15:25:39.095000",
32 | "AcquisitionNumber": 1,
33 | "SliceThickness": 3,
34 | "SpacingBetweenSlices": 3,
35 | "SAR": 0.119467,
36 | "EchoTime": 0.028,
37 | "RepetitionTime": 2.5,
38 | "FlipAngle": 90,
39 | "PartialFourier": 1,
40 | "BaseResolution": 64,
41 | "ShimSetting": [
42 | -2828,
43 | -22897,
44 | 2326,
45 | 408,
46 | -36,
47 | 118,
48 | -477,
49 | 244
50 | ],
51 | "TxRefAmp": 388.099,
52 | "PhaseResolution": 1,
53 | "ReceiveCoilName": "HeadMatrix",
54 | "CoilString": "C:HEA;HEP",
55 | "PulseSequenceDetails": "%CustomerSeq%_ep2d_bold_PMU",
56 | "PercentPhaseFOV": 100,
57 | "PhaseEncodingSteps": 64,
58 | "AcquisitionMatrixPE": 64,
59 | "ReconMatrixPE": 64,
60 | "BandwidthPerPixelPhaseEncode": 36.337,
61 | "EffectiveEchoSpacing": 0.000430002,
62 | "DerivedVendorReportedEchoSpacing": 0.000430002,
63 | "TotalReadoutTime": 0.0270902,
64 | "PixelBandwidth": 2894,
65 | "DwellTime": 2.7e-06,
66 | "PhaseEncodingDirection": "j-",
67 | "SliceTiming": [
68 | 1.255,
69 | 0,
70 | 1.3175,
71 | 0.0625,
72 | 1.38,
73 | 0.125,
74 | 1.4425,
75 | 0.1875,
76 | 1.505,
77 | 0.25,
78 | 1.5675,
79 | 0.3125,
80 | 1.63,
81 | 0.3775,
82 | 1.695,
83 | 0.44,
84 | 1.7575,
85 | 0.5025,
86 | 1.82,
87 | 0.565,
88 | 1.8825,
89 | 0.6275,
90 | 1.945,
91 | 0.69,
92 | 2.0075,
93 | 0.7525,
94 | 2.07,
95 | 0.815,
96 | 2.1325,
97 | 0.8775,
98 | 2.195,
99 | 0.94,
100 | 2.2575,
101 | 1.005,
102 | 2.3225,
103 | 1.0675,
104 | 2.385,
105 | 1.13,
106 | 2.4475,
107 | 1.1925
108 | ],
109 | "ImageOrientationPatientDICOM": [
110 | 1,
111 | 2e-16,
112 | 0,
113 | -2e-16,
114 | 0.987414,
115 | -0.158158
116 | ],
117 | "InPlanePhaseEncodingDirectionDICOM": "COL",
118 | "ConversionSoftware": "dcm2niix",
119 | "ConversionSoftwareVersion": "v1.0.20190902",
120 | "TaskName": "FlickeringCheckerBoard"
121 | }
122 |
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/sub-02/func/sub-02_task-FlickeringCheckerBoard_run-1_bold.nii.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/coolspiderghy/Python-Workshop-SuZhou/0b040d4890f576f2519e771080cdb44eb8815be8/fMRIPrep/ds003030_select/sub-02/func/sub-02_task-FlickeringCheckerBoard_run-1_bold.nii.gz
--------------------------------------------------------------------------------
/fMRIPrep/ds003030_select/sub-02/func/sub-02_task-FlickeringCheckerBoard_run-1_events.tsv:
--------------------------------------------------------------------------------
1 | onset duration trial_type
2 | 0 20 Checkerboard
3 | 20 20 Music
4 | 40 20 Checkerboard
5 | 60 20 Music
6 | 80 20 Checkerboard
7 | 100 20 Music
8 | 120 20 Checkerboard
9 | 140 20 Music
10 | 160 20 Checkerboard
11 | 180 20 Music
12 | 200 20 Checkerboard
13 | 220 20 Music
14 | 240 20 Checkerboard
15 | 260 20 Music
16 | 280 20 Checkerboard
17 | 300 20 Music
18 | 320 20 Checkerboard
19 | 340 20 Music
20 | 360 20 Checkerboard
21 | 380 20 Music
--------------------------------------------------------------------------------
/fMRIPrep/output/README.md:
--------------------------------------------------------------------------------
1 | .
--------------------------------------------------------------------------------