-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwb-ppi.py
executable file
·163 lines (122 loc) · 5 KB
/
wb-ppi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import warnings
warnings.filterwarnings("ignore")
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
from bids.layout import parse_file_entities
from load_confounds import Confounds
from nilearn.glm.first_level import make_first_level_design_matrix
from nilearn.input_data import NiftiLabelsMasker
from sklearn.linear_model import LinearRegression
import atlases
from strategies import strategies
def get_args():
parser = argparse.ArgumentParser(description="whole-brain PPI")
parser.add_argument("fmriprep", type=Path, help="path to fmriprep directory")
parser.add_argument("tr", type=float, help="repetition time in seconds")
parser.add_argument("strategy", type=str, help=" - ".join(strategies.keys()))
parser.add_argument("atlas", type=str, help=" - ".join(atlases.atlas_options))
parser.add_argument(
"--smooth_fwhm",
type=float,
default=6,
help="smoothing kernel, default fwhm 6mm",
)
args = parser.parse_args()
assert (
args.strategy in strategies.keys()
), f"{args.strategy} is not a valid strategy"
assert args.atlas in atlases.atlas_options, f"{args.atlas} not an available atlas"
assert args.fmriprep.is_dir(), "fmriprep directory does not exist"
return args
class Data:
def __init__(self, fmriprep, strategy):
print("\nindexing files... ", end="")
self.fmriprep = fmriprep
self.preprocs = self.get_preprocs()
self.events = self.get_events()
self.confounds = self.get_confounds(strategy)
assert len(self.preprocs) == len(self.confounds), "missings fmriprep files"
print(f"found {len(self.preprocs)} images")
def get_preprocs(self):
preprocs = self.fmriprep.glob(
"**/sub-*_task-h*_space-MNI152NLin6Asym_res-2_desc-preproc_bold.nii.gz"
)
return sorted([str(preproc) for preproc in preprocs])
def get_events(self):
events = sorted(
self.fmriprep.parents[1].glob("rawdata/**/sub-*_task-h*events.tsv")
)
return [
pd.read_csv(event, sep="\t", usecols=["onset", "duration", "trial_type"])
for event in events
]
def get_confounds(self, strategy):
return Confounds(**strategy).load(self.preprocs)
def get_linear_model():
return LinearRegression(fit_intercept=False, n_jobs=-2)
def build_path(derivatives, sub, task, strategy, atlas):
path = derivatives / f"wb-ppi/sub-{sub}"
path.mkdir(parents=True, exist_ok=True)
# BIDS pattern: sub-{subject}_task-{task}_atlas-{atlas}_strat-{strategy}_{suffix}.{extension}
return path / f"sub-{sub}_task-{task}_atlas-{atlas}_strat-{strategy}_ppi.npy"
def save_df(path, atlas):
atlas.df.to_csv(f"{path}/atlas-{atlas.title}_labels.csv", index=False)
def save_fig(path, atlas):
atlas.fig.savefig(f"{path}/atlas-{atlas.title}_fig.png", dpi=300)
def save_record(path, args):
file = path / "record.csv"
try:
record = pd.read_csv(file)
except:
record = pd.DataFrame({"atlas": [], "strategy": [], "smooth_fwhm": []})
record.loc[len(record)] = [args.atlas, args.strategy, args.smooth_fwhm]
record.to_csv(file, index=False)
def get_dm(event, frame_times):
return make_first_level_design_matrix(
frame_times=frame_times,
events=event,
hrf_model="glover + derivative",
drift_model=None,
high_pass=None,
)
def fit_ppi(ts_rois, dm, model):
ppi_vect = []
for roi in ts_rois.T:
dm["roi"] = roi # is mean centered
psy = dm.iloc[:, 0]
psy = psy - np.mean([psy.min(), psy.max()]) # zero center
dm["ppi"] = psy * dm["roi"]
model.fit(dm, ts_rois) # y = all rois, X = dm
ppi_vect.append(
model.coef_[:, -1]
) # beta coefficients corresponding to ppi regressor
return np.hstack(ppi_vect)
def main():
args = get_args()
derivatives = args.fmriprep.parent
data = Data(args.fmriprep, strategies[args.strategy])
atlas = atlases.Atlas(args.atlas)
masker = atlas.get_masker(
atlas.maps, atlas.probabilistic, derivatives, args.smooth_fwhm
)
model = get_linear_model()
for preproc, event, confound in zip(data.preprocs, data.events, data.confounds):
file_entities = parse_file_entities(preproc)
sub, task = file_entities["subject"], file_entities["task"]
print(f"> sub-{sub} task-{task}")
path_ppi = build_path(derivatives, sub, task, args.strategy, atlas.title)
ts_rois = masker.fit_transform(imgs=preproc, confounds=confound)
samples = len(ts_rois)
frame_times = np.linspace(0, (samples * args.tr) - args.tr, samples)
dm = get_dm(event, frame_times)
ppi_vect = fit_ppi(ts_rois, dm, model)
np.save(path_ppi, ppi_vect)
path = derivatives / f"wb-ppi/group/atlas-{atlas.title}"
path.mkdir(parents=True, exist_ok=True)
save_df(path, atlas)
save_fig(path, atlas)
save_record(path.parent, args)
if __name__ == "__main__":
main()