OSCR

An international mega-analysis of psychedelic drug effects on brain circuit function.

Code ↔ Paper

2 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 2 matches
  1. [1] § Methods › Brain signal denoising ↔ ana8_uncorrected_data_pipelines_250820_NM.py, lines 138–215 · score 0.76 · noise components, independent components, ICA AROMA, aggressive, CSF, regresses
  2. [2] § Methods › Brain signal denoising ↔ ana8_uncorrected_data_pipelines_250820_NM.py, lines 138–215 · score 0.71 · discrete cosine, component, masks, anatomical, WM, threshold

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 4,756 lines · 195 KB · no license · 2 matches

  1. import os
  2. import numpy as np
  3. import scipy as sc
  4. import json
  5. import glob
  6. import pandas as pd
  7. from sklearn.preprocessing import StandardScaler
  8. from nilearn.input_data import NiftiLabelsMasker
  9. from nilearn.signal import clean
  10. from nilearn.interfaces.fmriprep import load_confounds, load_confounds_components
  11. from nilearn.interfaces.fmriprep.load_confounds_components import _load_high_pass, _load_motion, _load_wm_csf, _load_global_signal, _load_compcor, _load_scrub
  12. from nilearn import datasets as ds
  13. import seaborn as sns
  14. from matplotlib import pylab as plt
  15. import pymc as pm
  16. import arviz
  17. from nilearn.interfaces.fmriprep import load_confounds_strategy
  18. n_rois = 100 #200#, 400
  19. for strategy in [
  20. # ['motion', 'high_pass', 'compcor'],
  21. # ['motion', 'high_pass', 'wm_csf', 'scrub'],
  22. # ['wm_csf', 'high_pass', 'ica_aroma'],
  23. # ['motion', 'high_pass', 'compcor', 'global_signal'],
  24. # ['motion', 'high_pass', 'wm_csf', 'scrub', 'global_signal'],
  25. ['wm_csf', 'high_pass', 'ica_aroma', 'global_signal']
  26. ]:
  27. # ['motion', 'high_pass', 'global_signal'],
  28. # ['motion', 'high_pass', 'wm_csf', 'global_signal'],
  29. # ['wm_csf', 'high_pass', 'ica_aroma', 'global_signal'],
  30. # ['motion', 'high_pass', 'compcor', 'global_signal'],
  31. # ['motion', 'high_pass', 'wm_csf', 'scrub', 'global_signal']]:
  32. # ['motion', 'compcor'],
  33. # ['motion', 'wm_csf', 'scrub'],
  34. # ['aroma', 'wm_csf'],
  35. # ['motion', 'compcor', 'global_signal'],
  36. # ['motion', 'wm_csf', 'scrub', 'global_signal'],
  37. # ['aroma', 'wm_csf', 'global_signal']]:
  38. # ['motion', 'global_signal'], # for the roadout of fMRIPrep outputs
  39. # ['wm_csf', 'global_signal'],
  40. # ['ica_aroma', 'global_signal'],
  41. # ['high_pass', 'global_signal'],
  42. # ['scrub', 'global_signal'],
  43. # ['compcor', 'global_signal'],
  44. # ['motion'], # for the roadout of fMRIPrep outputs
  45. # ['wm_csf'],
  46. # ['ica_aroma'],
  47. # ['high_pass'],
  48. # ['scrub'],
  49. # ['compcor']
  50. CCs_all = []
  51. FDs_all = []
  52. conds_all = []
  53. study_id_all = []
  54. drug_all = [] # 0=psilocy (blue); 1=LSD (orange); 2=Aya (green); 3=mescaline (red), 4=DMT (purple)
  55. drug_labels = np.array(['psilocybin', 'LSD', 'Aya', 'mescaline', 'DMT'])
  56. plt.close('all')
  57. strategy_suffix = '_'.join(strategy)
  58. try:
  59. os.mkdir(strategy_suffix)
  60. except:
  61. pass
  62. # atlas = ds.fetch_atlas_schaefer_2018(n_rois=n_rois, yeo_networks=7)
  63. atlas = ds.fetch_atlas_schaefer_2018(n_rois=n_rois, yeo_networks=17)
  64. cort_labels = [l.decode() for l in atlas.labels]
  65. masker = NiftiLabelsMasker(labels_img=atlas.maps)
  66. masker.fit()
  67. subcort_labels = list(pd.read_csv('_atlas_defs/Tian_subcortical38_labels.txt', header=None).values[:, 0])
  68. claustrum_labels = list(pd.read_csv('_atlas_defs/Claustrum_labels.txt', header=None).values[:, 0])
  69. cerebellum_labels = list(pd.read_csv('_atlas_defs/Cerebellum_labels.txt', header=None).values[:, 0])
  70. # sub_ts = pd.concat([sub_ts, subcort, claustrum, cereb], axis=1)
  71. full_labels = cort_labels + subcort_labels + claustrum_labels + cerebellum_labels
  72. # construct subcort atlas
  73. # sb_nii_paths = []
  74. # for i in range(50):
  75. # cur_nii = glob.glob('_scripts_data/collaboration_psychedelics_ROIs/subcortical/Tian_subcortex_*_%i.nii.gz' % (i + 1))
  76. # if not len(cur_nii):
  77. # pass
  78. # else:
  79. # sb_nii_paths.append(cur_nii)
  80. # construct cerebellum atlas
  81. from nilearn.image import math_img
  82. import nibabel as nib
  83. from nilearn.image import resample_img
  84. cereb_nii_paths = []
  85. cereb_nii_data = np.zeros( (97, 115, 97)).astype(int)
  86. for i in range(17):
  87. cur_nii = glob.glob('_scripts_data/collaboration_psychedelics_ROIs/cerebellum/rBuckner_cerebellum_%i.nii.gz' % (i + 1))
  88. if not len(cur_nii):
  89. pass
  90. else:
  91. print(cur_nii)
  92. cereb_nii_paths.append(cur_nii[0])
  93. cur_nii_bin = nib.load(cur_nii[0]).get_fdata().astype(int)
  94. print(cur_nii_bin.sum())
  95. cereb_nii_data += cur_nii_bin
  96. head = nib.load(cereb_nii_paths[0]).header
  97. aff = nib.load(cereb_nii_paths[0]).affine
  98. cereb_nii = nib.Nifti1Image(cereb_nii_data, affine=aff, header=head)
  99. cereb_nii.to_filename('atlas_cereb_Buckner17.nii.gz')
  100. cereb_nii_r = resample_img(cereb_nii,
  101. target_affine=masker.labels_img_.affine,
  102. target_shape=masker.labels_img_.shape,
  103. interpolation='nearest')
  104. cereb_nii_r.to_filename('atlas_cereb_Buckner17_r.nii.gz')
  105. masker_cereb = NiftiLabelsMasker(labels_img=cereb_nii_r)
  106. masker_cereb.fit()
  107. masker_cereb.labels_img_.to_filename('atlas_cereb_Buckner17_masker_cereb.nii.gz')
  108. study_id = []
  109. # net17_labels = []
  110. # net7_label_names = np.array(['Vis', 'Som', 'DorsAtt', 'SalVent', 'Limbic',
  111. # 'Cont', 'Default', 'TempPar'])
  112. # for l in cort_labels:
  113. # if '_Vis' in l:
  114. # cur_l = 1
  115. # elif '_Som' in l:
  116. # cur_l = 2
  117. # elif 'DorsAtt' in l:
  118. # cur_l = 3
  119. # elif '_SalVent' in l:
  120. # cur_l = 4
  121. # elif '_Limbic' in l:
  122. # cur_l = 5
  123. # elif '_Cont' in l:
  124. # cur_l = 6
  125. # elif 'Default' in l:
  126. # cur_l = 7
  127. # elif 'TempPar' in l:
  128. # cur_l = 8
  129. # else:
  130. # print('error !')
  131. # net17_labels.append(cur_l)
  132. # net17_labels = np.array(net17_labels)
  133. # net7_regcnt = np.bincount(net17_labels - 1)
  134. net17_strs = [s.split('H_')[1].split('_')[0] for s in cort_labels]
  135. net17_label_names = np.unique(net17_strs)
  136. cort_dict = {net17_label_names[i]: (i+1) for i in np.arange(17)}
  137. net17_labels = []
  138. for cur_net_lab in net17_strs:
  139. net17_labels.append(cort_dict[cur_net_lab])
  140. net17_labels = np.array(net17_labels)
  141. # Maastrict data
  142. sub_strs = [p.split('/')[-1] for p in glob.glob('_data_uncorrected_fullcolumns/Maastricht_Psilocybin/sub-*')]
  143. cond = pd.read_csv('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected/Maastricht/ROI_figures/conditions.txt', delimiter='\t')
  144. def get_my_confounds_df(conf_t_path, conf_j_path, strategy):
  145. conf_t = pd.read_csv(conf_t_path, delimiter='\t')
  146. df_out = pd.DataFrame([])
  147. new_cols = None
  148. for cur_stra in strategy:
  149. try:
  150. if cur_stra == 'motion':
  151. # full: translation/rotation + quadratic terms (24 parameters)
  152. new_cols = getattr(load_confounds_components, '_load_motion')(conf_t, 'full')
  153. elif cur_stra == 'wm_csf':
  154. # basic: the averages in each mask (2 parameters)
  155. new_cols = getattr(load_confounds_components, '_load_wm_csf')(conf_t, 'basic')
  156. elif cur_stra == 'global_signal':
  157. # basic: just the global signal (1 parameter)
  158. new_cols = getattr(load_confounds_components, '_load_global_signal')(conf_t, 'basic')
  159. elif cur_stra == 'ica_aroma':
  160. # basic: aggressive/classic AROMA, only regress out the noise independent components
  161. new_cols = getattr(load_confounds_components, '_load_ica_aroma')(conf_t, 'basic')
  162. elif cur_stra == 'high_pass':
  163. # add cosine columns to confound matrix to be regressed out
  164. # adds discrete cosines transformation basis regressors to handle low-frequency signal drifts
  165. new_cols = getattr(load_confounds_components, '_load_high_pass')(conf_t)
  166. elif cur_stra == 'scrub':
  167. # we "tag" rfMRI scans with 0/1 indicators that are then regressed out, instead of removing scans from time series
  168. # fd_threhsold = 0.5 more regular threshold (Lior, various papers !!!)
  169. new_cols = getattr(load_confounds_components, '_load_scrub')(conf_t, scrub=5, fd_threshold=0.5, std_dvars_threshold=3)
  170. elif cur_stra == 'compcor':
  171. # anat_combined: noise components calculated using a white matter and CSF combined anatomical mask
  172. with open(conf_j_path, "rb") as f:
  173. conf_j = json.load(f)
  174. new_cols = getattr(load_confounds_components, '_load_compcor')(conf_t, conf_j, 'anat_combined', 5)
  175. except:
  176. print(f'!!! Exception when grapping {cur_stra} columns for {conf_j_path}')
  177. if new_cols is not None:
  178. df_out = pd.concat([df_out, new_cols], axis=1)
  179. return df_out
  180. # QC: FD + dvars
  181. study_FDs = []
  182. study_dvars = []
  183. for sub_name in sub_strs:
  184. print(sub_name)
  185. conf_t_path = '/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Maastricht_Psilocybin/ROI_confounds/%s/func/%s_task-rest_desc-confounds_timeseries.tsv' % (sub_name, sub_name)
  186. df = pd.read_csv(conf_t_path, delimiter='\t')
  187. cur_fd = (df.framewise_displacement > 0.5).sum()
  188. study_FDs.append(cur_fd)
  189. print(cur_fd)
  190. cur_dvars = df.dvars.mean()
  191. study_dvars.append(cur_dvars)
  192. print(cur_dvars)
  193. plt.figure()
  194. plt.hist(study_FDs, bins=20)
  195. plt.title('FD (#volumes > 0.5mm out of %i total): Maastricht_Psilocybin' % len(df.framewise_displacement))
  196. # plt.title('FD (#volumes > 0.5mm): Maastricht_Psilocybin\nimages > 0.2: %i/%i\nimages > 0.5: %i/%i\nimages > 0.8: %i/%i' % (
  197. # sum(df.framewise_displacement >0.2), len(df.framewise_displacement),
  198. # sum(df.framewise_displacement >0.5), len(df.framewise_displacement),
  199. # sum(df.framewise_displacement >0.8), len(df.framewise_displacement)))
  200. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Maastricht_Psilocybin_FDabove0.5mm.png', dpi=600)
  201. plt.figure()
  202. plt.hist(np.array(study_FDs) / len(df.framewise_displacement), bins=20)
  203. plt.title('FD (fraction of volumes > 0.5mm out of %i total): Maastricht_Psilocybin' % len(df.framewise_displacement))
  204. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Maastricht_Psilocybin_fracFDabove0.5mm.png', dpi=600)
  205. plt.figure()
  206. plt.hist(study_dvars, bins=20)
  207. plt.title('DVARS (mean across TS): Maastricht_Psilocybin')
  208. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Maastricht_Psilocybin_dvars.png')
  209. CCs = []
  210. conds = []
  211. n_skipped = 0
  212. for sub_name in sub_strs:
  213. # print(sub_name)
  214. sub_ts = pd.read_csv('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Maastricht_Psilocybin/%s/func/%s_schaefer100_TS_noDenosing.csv' % (sub_name, sub_name), header=None)
  215. subcort = pd.read_csv('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected/Maastricht/ROI_figures/%s/func/%s_subcortical38_TS_noDenosing.csv' % (sub_name, sub_name), header=None)
  216. claustrum = pd.read_csv('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected/Maastricht/ROI_figures/%s/func/%s_claustrum_TS_noDenosing.csv' % (sub_name, sub_name), header=None)
  217. tmp = clean(
  218. signals=claustrum.iloc[:, [0, 3]].to_numpy(),
  219. confounds=claustrum.iloc[:, [1, 2, 4, 5]].to_numpy(),
  220. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  221. claustrum.iloc[:, [0, 3]] = tmp
  222. cereb = pd.read_csv('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected/Maastricht/ROI_figures/%s/func/%s_cerebellum_TS_noDenosing.csv' % (sub_name, sub_name), header=None)
  223. sub_ts = pd.concat([sub_ts, subcort, claustrum, cereb], axis=1)
  224. sub_ts_z = pd.DataFrame(StandardScaler().fit_transform(sub_ts))
  225. conf_t_path = '/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Maastricht_Psilocybin/ROI_confounds/%s/func/%s_task-rest_desc-confounds_timeseries.tsv' % (sub_name, sub_name)
  226. conf_j_path = '/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Maastricht_Psilocybin/ROI_confounds/%s/func/%s_task-rest_desc-confounds_timeseries.json' % (sub_name, sub_name)
  227. conf = get_my_confounds_df(conf_t_path, conf_j_path, strategy)
  228. conf = pd.DataFrame(np.nan_to_num(conf))
  229. # motion correction
  230. df = pd.read_csv(conf_t_path, delimiter='\t')
  231. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  232. if sub_motion_frac > 0.15:
  233. n_skipped += 1
  234. print('Skipping subject: %s' % sub_name)
  235. continue
  236. # nii_fmri = masker.inverse_transform(sub_ts)
  237. if len(conf) != 0:
  238. sub_ts_z_deconf = clean(
  239. signals=np.nan_to_num(sub_ts_z.values), standardize=False, confounds=np.nan_to_num(conf))
  240. else:
  241. continue
  242. print(f'{sub_name} has {len(conf.columns)} columns to noise clean!')
  243. # sub_ts_z_deconf = pd.DataFrame(
  244. # sub_ts_z_deconf, columns=cort_labels)
  245. # sub_CC = np.corrcoef(sub_ts_z_deconf.T)
  246. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf.T))
  247. cur_cond = cond[cond.Participant.values == int(sub_name[-2:])].Group_1isplacebo
  248. if len(cur_cond) == 0:
  249. continue
  250. cur_cond = int(cur_cond.values == 2) # 1 == drug / 0 == placebo
  251. study_id_all.append(0)
  252. CCs.append(sub_CC)
  253. conds.append(cur_cond)
  254. FDs_all.append(df.framewise_displacement.mean())
  255. CCs_all.append(sub_CC)
  256. conds_all.append(cur_cond)
  257. drug_all.append(0)
  258. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/maastrich_coverage.nii.gz')
  259. CCs = np.array(CCs)
  260. conds = np.array(conds)
  261. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  262. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  263. import matplotlib.pylab as plt
  264. plt.figure(figsize=(16, 10))
  265. sns.set(font_scale=0.4)
  266. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  267. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  268. plt.tight_layout()
  269. plt.savefig('_results_uncorrected_data_pipelines_ana8/maastricht_avg_CC_plcb_%s.pdf' % strategy_suffix)
  270. import matplotlib.pylab as plt
  271. plt.figure(figsize=(16, 10))
  272. sns.set(font_scale=0.4)
  273. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  274. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  275. plt.tight_layout()
  276. plt.savefig('_results_uncorrected_data_pipelines_ana8/maastricht_avg_CC_drug_%s.pdf' % strategy_suffix)
  277. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  278. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  279. # import matplotlib.pylab as plt
  280. # plt.figure(figsize=(16, 10))
  281. # sns.set(font_scale=0.4)
  282. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  283. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  284. # plt.tight_layout()
  285. # plt.savefig('_results_uncorrected/maastricht_avg_CC_plcb_max.pdf')
  286. # import matplotlib.pylab as plt
  287. # plt.figure(figsize=(16, 10))
  288. # sns.set(font_scale=0.4)
  289. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  290. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  291. # plt.tight_layout()
  292. # plt.savefig('_results_uncorrected/maastricht_avg_CC_drug_max.pdf')
  293. import matplotlib.pylab as plt
  294. plt.figure(figsize=(16, 10))
  295. sns.set(font_scale=0.4)
  296. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  297. center=0, xticklabels=full_labels, yticklabels=full_labels)
  298. plt.tight_layout()
  299. plt.savefig('_results_uncorrected_data_pipelines_ana8/maastricht_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  300. from sklearn.linear_model import LinearRegression
  301. CCs = np.nan_to_num(CCs)
  302. out_mat = np.zeros((161, 161))
  303. for i_roi in range(161):
  304. for j_roi in range(161):
  305. if i_roi == j_roi:
  306. continue
  307. lr = LinearRegression(fit_intercept=True)
  308. y = CCs[:, i_roi, j_roi]
  309. X = conds[:, None]
  310. lr.fit(X, y)
  311. out_mat[i_roi, j_roi] = lr.coef_[0]
  312. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  313. import matplotlib.pylab as plt
  314. plt.figure(figsize=(20, 14))
  315. sns.set(font_scale=0.4)
  316. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  317. center=0)
  318. plt.tight_layout()
  319. plt.savefig('_results_uncorrected_data_pipelines_ana8/maastricht_lrcoef_%s.pdf' % strategy_suffix)
  320. # import matplotlib.pylab as plt
  321. # plt.figure(figsize=(20, 14))
  322. # sns.set(font_scale=0.4)
  323. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  324. # center=0)
  325. # plt.tight_layout()
  326. # plt.savefig('_results_uncorrected/maastricht_lrcoef_viridis.pdf')
  327. cum_intra_net = np.zeros((17))
  328. cum_intra_net_cnt = np.zeros((17))
  329. cum_inter_net = np.zeros((17))
  330. cum_inter_net_cnt = np.zeros((17))
  331. for i in range(n_rois): # rows
  332. for j in range(n_rois): # columns
  333. if i==j: # skip connections to self
  334. continue
  335. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  336. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  337. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  338. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  339. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  340. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  341. ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  342. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  343. plt.title('Intra-network drug effects', fontsize=12)
  344. plt.tight_layout()
  345. # plt.savefig('_results_uncorrected/maastricht_cumabs_intra.pdf')
  346. plt.savefig('_results_uncorrected_data_pipelines_ana8/maastricht_avg_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  347. ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  348. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  349. plt.title('Inter-network drug effects', fontsize=12)
  350. plt.tight_layout()
  351. # plt.savefig('_results_uncorrected/maastricht_cumabs_inter.pdf')
  352. plt.savefig('_results_uncorrected_data_pipelines_ana8/maastricht_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  353. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  354. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  355. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  356. # plt.title('Intra-network drug effects', fontsize=12)
  357. # plt.tight_layout()
  358. # plt.savefig('_results_uncorrected/maastricht_cumabs_intra_norm.pdf')
  359. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  360. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  361. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  362. # plt.title('Inter-network drug effects', fontsize=12)
  363. # plt.tight_layout()
  364. # plt.savefig('_results_uncorrected/maastricht_cumabs_inter_norm.pdf')
  365. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  366. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  367. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  368. # plt.title('Intra-network drug effects', fontsize=12)
  369. # plt.tight_layout()
  370. # plt.savefig('_results_uncorrected/maastricht_cumabs_intra_regnorm.pdf')
  371. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  372. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  373. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  374. # plt.title('Inter-network drug effects', fontsize=12)
  375. # plt.tight_layout()
  376. # plt.savefig('_results_uncorrected/maastricht_cumabs_inter_regnorm.pdf')
  377. # # no abs
  378. # cum_intra_net = np.zeros((17))
  379. # cum_intra_net_cnt = np.zeros((17))
  380. # cum_inter_net = np.zeros((17))
  381. # cum_inter_net_cnt = np.zeros((17))
  382. # for i in range(n_rois): # rows
  383. # for j in range(n_rois): # columns
  384. # if i==j: # skip connections to self
  385. # continue
  386. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  387. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  388. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  389. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  390. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  391. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  392. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  393. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  394. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  395. # plt.title('Intra-network drug effects', fontsize=12)
  396. # plt.tight_layout()
  397. # plt.savefig('_results_uncorrected/maastricht_cumabs_intra_regnorm_noabs.pdf')
  398. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  399. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  400. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  401. # plt.title('Inter-network drug effects', fontsize=12)
  402. # plt.tight_layout()
  403. # plt.savefig('_results_uncorrected/maastricht_cumabs_inter_regnorm_noabs.pdf')
  404. # Palhano data: 18 subs, 2 conds; Aya dataset ! (mislabeled)
  405. import os
  406. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Palhano_Psilocybin/*/sub-*/sub-*_schaefer100_TS_noDenosing.csv')
  407. # QC: FD + dvars
  408. study_FDs = []
  409. study_dvars = []
  410. for sub_name in sub_strs:
  411. cur_cond = 'preacute' if 'predosing' in sub_name else 'acute'
  412. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-ayahuasca%s_desc-confounds_timeseries.tsv' % cur_cond
  413. sub_name = sub_strs[0].split('/')[-2]
  414. print(sub_name)
  415. df = pd.read_csv(conf_t_path, delimiter='\t')
  416. cur_fd = (df.framewise_displacement > 0.5).sum()
  417. study_FDs.append(cur_fd)
  418. print(cur_fd)
  419. cur_dvars = df.dvars.mean()
  420. study_dvars.append(cur_dvars)
  421. print(cur_dvars)
  422. plt.figure()
  423. plt.hist(study_FDs, bins=20)
  424. # plt.title('FD (#volumes > 0.5mm): palhano')
  425. plt.title('FD (#volumes > 0.5mm out of %i total): palhano' % len(df.framewise_displacement))
  426. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_palhano_FDabove0.5mm.png', dpi=600)
  427. plt.figure()
  428. plt.hist(np.array(study_FDs) / len(df.framewise_displacement), bins=20)
  429. plt.title('FD (fraction of volumes > 0.5mm out of %i total): palhano' % len(df.framewise_displacement))
  430. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_palhano_fracFDabove0.5mm.png', dpi=600)
  431. plt.figure()
  432. plt.hist(study_dvars, bins=20)
  433. plt.title('DVARS (mean across TS): palhano')
  434. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_palhano_dvars.png')
  435. CCs = []
  436. conds = []
  437. n_skipped = 0
  438. for sub_name in sub_strs:
  439. # print(sub_name)
  440. sub_ts = pd.read_csv(sub_name, header=None)
  441. subcort_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_subcortical38_TS_noDenosing.csv'
  442. subcort = pd.read_csv(subcort_path, header=None)
  443. claustrum_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_claustrum_TS_noDenosing.csv'
  444. claustrum = pd.read_csv(claustrum_path, header=None)
  445. tmp = clean(
  446. signals=claustrum.iloc[:, [0, 3]].to_numpy(),
  447. confounds=claustrum.iloc[:, [1, 2, 4, 5]].to_numpy(),
  448. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  449. claustrum.iloc[:, [0, 3]] = tmp
  450. cereb_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_cerebellum_TS_noDenosing.csv'
  451. cereb = pd.read_csv(cereb_path, header=None)
  452. sub_ts = pd.concat([sub_ts, subcort, claustrum, cereb], axis=1)
  453. assert n_rois + 61 == sub_ts.shape[1]
  454. sub_ts_z = pd.DataFrame(StandardScaler().fit_transform(sub_ts))
  455. cur_cond = 'preacute' if 'predosing' in sub_name else 'acute'
  456. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-ayahuasca%s_desc-confounds_timeseries.tsv' % cur_cond
  457. conf_j_path = conf_t_path.replace('.tsv', '.json')
  458. conf = get_my_confounds_df(conf_t_path, conf_j_path, strategy)
  459. # motion correction
  460. df = pd.read_csv(conf_t_path, delimiter='\t')
  461. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  462. if sub_motion_frac > 0.15:
  463. n_skipped += 1
  464. print('Skipping subject: %s' % sub_name)
  465. continue
  466. if len(conf) != 0:
  467. sub_ts_z_deconf = clean(
  468. signals=np.nan_to_num(sub_ts_z.values), standardize=False, confounds=np.nan_to_num(conf))
  469. # signals=np.nan_to_num(sub_ts_z.values), standardize=False, np.nan_to_num(confounds=conf.iloc[:len(sub_ts_z)]))
  470. else:
  471. continue
  472. # print(f'{sub_name} has {len(conf.columns)} columns to noise clean!')
  473. # sub_ts_z_deconf = pd.DataFrame(
  474. # sub_ts_z_deconf, columns=cort_labels)
  475. # sub_CC = np.corrcoef(sub_ts_z_deconf.T)
  476. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf.T))
  477. study_id_all.append(1)
  478. CCs.append(sub_CC)
  479. conds.append(int(cur_cond == 'acute'))
  480. FDs_all.append(df.framewise_displacement.mean())
  481. CCs_all.append(sub_CC)
  482. conds_all.append(int(cur_cond == 'acute'))
  483. drug_all.append(2)
  484. CCs = np.array(CCs)
  485. conds = np.array(conds)
  486. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/palhano_coverage.nii.gz')
  487. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  488. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  489. import matplotlib.pylab as plt
  490. plt.figure(figsize=(16, 10))
  491. sns.set(font_scale=0.4)
  492. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  493. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  494. plt.tight_layout()
  495. plt.savefig('_results_uncorrected_data_pipelines_ana8/Palhano_avg_CC_plcb_%s.pdf' % strategy_suffix)
  496. import matplotlib.pylab as plt
  497. plt.figure(figsize=(16, 10))
  498. sns.set(font_scale=0.4)
  499. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  500. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  501. plt.tight_layout()
  502. plt.savefig('_results_uncorrected_data_pipelines_ana8/Palhano_avg_CC_drug_%s.pdf' % strategy_suffix)
  503. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  504. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  505. # import matplotlib.pylab as plt
  506. # plt.figure(figsize=(16, 10))
  507. # sns.set(font_scale=0.4)
  508. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  509. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  510. # plt.tight_layout()
  511. # plt.savefig('_results_uncorrected/Palhano_avg_CC_plcb_max.pdf')
  512. # import matplotlib.pylab as plt
  513. # plt.figure(figsize=(16, 10))
  514. # sns.set(font_scale=0.4)
  515. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  516. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  517. # plt.tight_layout()
  518. # plt.savefig('_results_uncorrected/Palhano_avg_CC_drug_max.pdf')
  519. import matplotlib.pylab as plt
  520. plt.figure(figsize=(16, 10))
  521. sns.set(font_scale=0.4)
  522. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  523. center=0, xticklabels=full_labels, yticklabels=full_labels)
  524. plt.tight_layout()
  525. plt.savefig('_results_uncorrected_data_pipelines_ana8/Palhano_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  526. from sklearn.linear_model import LinearRegression
  527. out_mat = np.zeros((161, 161))
  528. CCs = np.nan_to_num(CCs)
  529. for i_roi in range(161):
  530. for j_roi in range(161):
  531. if i_roi == j_roi:
  532. continue
  533. lr = LinearRegression(fit_intercept=True)
  534. y = CCs[:, i_roi, j_roi]
  535. X = conds[:, None]
  536. lr.fit(X, y)
  537. out_mat[i_roi, j_roi] = lr.coef_[0]
  538. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  539. import matplotlib.pylab as plt
  540. plt.figure(figsize=(20, 14))
  541. sns.set(font_scale=0.4)
  542. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  543. center=0)
  544. plt.tight_layout()
  545. # plt.savefig('_results_uncorrected/palhano_lrcoef.pdf')
  546. plt.savefig('_results_uncorrected_data_pipelines_ana8/Palhano_avg_lrcoef_%s.pdf' % strategy_suffix)
  547. # import matplotlib.pylab as plt
  548. # plt.figure(figsize=(20, 14))
  549. # sns.set(font_scale=0.4)
  550. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  551. # center=0, vmax=.35)
  552. # plt.tight_layout()
  553. # plt.savefig('_results_uncorrected/palhano_lrcoef_viridis.pdf')
  554. cum_intra_net = np.zeros((17))
  555. cum_intra_net_cnt = np.zeros((17))
  556. cum_inter_net = np.zeros((17))
  557. cum_inter_net_cnt = np.zeros((17))
  558. for i in range(n_rois): # rows
  559. for j in range(n_rois): # columns
  560. if i==j: # skip connections to self
  561. continue
  562. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  563. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  564. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  565. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  566. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  567. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  568. # ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  569. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  570. # plt.title('Intra-network drug effects', fontsize=12)
  571. # plt.tight_layout()
  572. # plt.savefig('_results_uncorrected/palhano_cumabs_intra.pdf')
  573. # ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  574. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  575. # plt.title('Inter-network drug effects', fontsize=12)
  576. # plt.tight_layout()
  577. # plt.savefig('_results_uncorrected/palhano_cumabs_inter.pdf')
  578. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  579. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  580. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  581. # plt.title('Intra-network drug effects', fontsize=12)
  582. # plt.tight_layout()
  583. # plt.savefig('_results_uncorrected/palhano_cumabs_intra_norm.pdf')
  584. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  585. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  586. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  587. # plt.title('Inter-network drug effects', fontsize=12)
  588. # plt.tight_layout()
  589. # plt.savefig('_results_uncorrected/palhano_cumabs_inter_norm.pdf')
  590. ax = pd.DataFrame(cum_intra_net,
  591. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  592. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  593. plt.title('Intra-network drug effects', fontsize=12)
  594. plt.tight_layout()
  595. plt.savefig('_results_uncorrected_data_pipelines_ana8/Palhano_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  596. ax = pd.DataFrame(cum_inter_net,
  597. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  598. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  599. plt.title('Inter-network drug effects', fontsize=12)
  600. plt.tight_layout()
  601. plt.savefig('_results_uncorrected_data_pipelines_ana8/Palhano_cumabs_inter_regnorm_%s.pdf' % strategy_suffix)
  602. # # no abs
  603. # cum_intra_net = np.zeros((17))
  604. # cum_intra_net_cnt = np.zeros((17))
  605. # cum_inter_net = np.zeros((17))
  606. # cum_inter_net_cnt = np.zeros((17))
  607. # for i in range(n_rois): # rows
  608. # for j in range(n_rois): # columns
  609. # if i==j: # skip connections to self
  610. # continue
  611. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  612. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  613. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  614. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  615. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  616. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  617. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  618. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  619. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  620. # plt.title('Intra-network drug effects', fontsize=12)
  621. # plt.tight_layout()
  622. # plt.savefig('_results_uncorrected/palhano_cumabs_intra_regnorm_noabs.pdf')
  623. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  624. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  625. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  626. # plt.title('Inter-network drug effects', fontsize=12)
  627. # plt.tight_layout()
  628. # plt.savefig('_results_uncorrected/palhano_cumabs_inter_regnorm_noabs.pdf')
  629. # Zurich data / LSD: 25 subs, 2 conds (Flora, Katrin)
  630. del out_df
  631. import os
  632. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Zurich_LSD_Psilocybin/output_LSD/sub-*/ses-*/func/sub-*_schaefer100_TS_noDenosing.csv')
  633. # QC: FD + dvars
  634. study_FDs = []
  635. study_dvars = []
  636. for sub_name in sub_strs:
  637. cur_cond = 'lsd' if 'ses-lsd' in sub_name else 'plcb'
  638. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_desc-confounds_timeseries.tsv'
  639. sub_name = sub_strs[0].split('/')[-4]
  640. print(sub_name)
  641. df = pd.read_csv(conf_t_path, delimiter='\t')
  642. cur_fd = (df.framewise_displacement > 0.5).sum()
  643. study_FDs.append(cur_fd)
  644. print(cur_fd)
  645. cur_dvars = df.dvars.mean()
  646. study_dvars.append(cur_dvars)
  647. print(cur_dvars)
  648. plt.figure()
  649. plt.hist(study_FDs, bins=20)
  650. # plt.title('FD (#volumes > 0.5mm): zurichlsd')
  651. plt.title('FD (#volumes > 0.5mm out of %i total): zurichlsd' % len(df.framewise_displacement))
  652. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_zurichlsd_FDabove0.5mm.png', dpi=600)
  653. plt.figure()
  654. plt.hist(np.array(study_FDs) / len(df.framewise_displacement), bins=20)
  655. plt.title('FD (fraction of volumes > 0.5mm out of %i total): zurichlsd' % len(df.framewise_displacement))
  656. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Zurichlsd_fracFDabove0.5mm.png', dpi=600)
  657. plt.figure()
  658. plt.hist(study_dvars, bins=20)
  659. plt.title('DVARS (mean across TS): zurichlsd')
  660. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_zurichlsd_dvars.png')
  661. CCs = []
  662. n_skipped = 0
  663. conds = []
  664. for sub_name in sub_strs:
  665. # print(sub_name)
  666. sub_ts = pd.read_csv(sub_name, header=None)
  667. subcort_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_subcortical38_TS_noDenosing.csv'
  668. subcort = pd.read_csv(subcort_path, header=None)
  669. claustrum_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_claustrum_TS_noDenosing.csv'
  670. claustrum = pd.read_csv(claustrum_path, header=None)
  671. tmp = clean(
  672. signals=claustrum.iloc[:, [0, 3]].to_numpy(),
  673. confounds=claustrum.iloc[:, [1, 2, 4, 5]].to_numpy(),
  674. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  675. claustrum.iloc[:, [0, 3]] = tmp
  676. cereb_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_cerebellum_TS_noDenosing.csv'
  677. cereb = pd.read_csv(cereb_path, header=None)
  678. sub_ts = pd.concat([sub_ts, subcort, claustrum, cereb], axis=1)
  679. assert n_rois + 61 == sub_ts.shape[1]
  680. sub_ts_z = pd.DataFrame(StandardScaler().fit_transform(sub_ts))
  681. cur_cond = 'lsd' if 'ses-lsd' in sub_name else 'plcb'
  682. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_desc-confounds_timeseries.tsv'
  683. conf_j_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_desc-confounds_timeseries.json'
  684. if not os.path.exists(conf_t_path):
  685. print('Skipping this subject: confound file not found!')
  686. continue
  687. conf = get_my_confounds_df(conf_t_path, conf_j_path, strategy)
  688. # motion correction
  689. df = pd.read_csv(conf_t_path, delimiter='\t')
  690. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  691. if sub_motion_frac > 0.15:
  692. n_skipped += 1
  693. print('Skipping subject: %s' % sub_name)
  694. continue
  695. if len(conf) != 0:
  696. sub_ts_z_deconf = clean(
  697. signals=np.nan_to_num(sub_ts_z.values), standardize=False, confounds=np.nan_to_num(conf))
  698. else:
  699. continue
  700. print(f'{sub_name} has {len(conf.columns)} columns to noise clean!')
  701. # sub_ts_z_deconf = pd.DataFrame(
  702. # sub_ts_z_deconf, columns=cort_labels)
  703. # sub_CC = np.corrcoef(sub_ts_z_deconf.T)
  704. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf.T))
  705. study_id_all.append(2)
  706. CCs.append(sub_CC)
  707. conds.append(int(cur_cond == 'lsd'))
  708. FDs_all.append(df.framewise_displacement.mean())
  709. CCs_all.append(sub_CC)
  710. conds_all.append(int(cur_cond == 'lsd'))
  711. drug_all.append(1)
  712. CCs = np.array(CCs)
  713. conds = np.array(conds)
  714. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/zurichlsd_coverage.nii.gz')
  715. from sklearn.linear_model import LinearRegression
  716. out_mat = np.zeros((161, 161))
  717. CCs = np.nan_to_num(CCs)
  718. for i_roi in range(161):
  719. for j_roi in range(161):
  720. if i_roi == j_roi:
  721. continue
  722. lr = LinearRegression(fit_intercept=True)
  723. y = CCs[:, i_roi, j_roi]
  724. X = conds[:, None]
  725. lr.fit(X, y)
  726. out_mat[i_roi, j_roi] = lr.coef_[0]
  727. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  728. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  729. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  730. import matplotlib.pylab as plt
  731. plt.figure(figsize=(16, 10))
  732. sns.set(font_scale=0.4)
  733. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  734. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  735. plt.tight_layout()
  736. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichLSD_avg_CC_plcb_%s.pdf' % strategy_suffix)
  737. import matplotlib.pylab as plt
  738. plt.figure(figsize=(16, 10))
  739. sns.set(font_scale=0.4)
  740. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  741. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  742. plt.tight_layout()
  743. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichLSD_avg_CC_drug_%s.pdf' % strategy_suffix)
  744. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  745. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  746. # import matplotlib.pylab as plt
  747. # plt.figure(figsize=(16, 10))
  748. # sns.set(font_scale=0.4)
  749. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  750. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  751. # plt.tight_layout()
  752. # plt.savefig('_results_uncorrected/Zurich_avg_CC_plcb_max.pdf')
  753. # import matplotlib.pylab as plt
  754. # plt.figure(figsize=(16, 10))
  755. # sns.set(font_scale=0.4)
  756. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  757. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  758. # plt.tight_layout()
  759. # plt.savefig('_results_uncorrected/Zurich_avg_CC_drug_max.pdf')
  760. import matplotlib.pylab as plt
  761. plt.figure(figsize=(16, 10))
  762. sns.set(font_scale=0.4)
  763. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  764. center=0, xticklabels=full_labels, yticklabels=full_labels)
  765. plt.tight_layout()
  766. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichLSD_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  767. from sklearn.linear_model import LinearRegression
  768. out_mat = np.zeros((161, 161))
  769. CCs = np.nan_to_num(CCs)
  770. for i_roi in range(161):
  771. for j_roi in range(161):
  772. if i_roi == j_roi:
  773. continue
  774. lr = LinearRegression(fit_intercept=True)
  775. y = CCs[:, i_roi, j_roi]
  776. X = conds[:, None]
  777. lr.fit(X, y)
  778. out_mat[i_roi, j_roi] = lr.coef_[0]
  779. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  780. import matplotlib.pylab as plt
  781. plt.figure(figsize=(20, 14))
  782. sns.set(font_scale=0.4)
  783. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  784. center=0)
  785. plt.tight_layout()
  786. # plt.savefig('_results_uncorrected/zurich_lrcoef.pdf')
  787. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichLSD_avg_lrcoef_%s.pdf' % strategy_suffix)
  788. # import matplotlib.pylab as plt
  789. # plt.figure(figsize=(20, 14))
  790. # sns.set(font_scale=0.4)
  791. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  792. # center=0, vmax=.5)
  793. # plt.tight_layout()
  794. # plt.savefig('_results_uncorrected/zurich_lrcoef_viridis.pdf')
  795. cum_intra_net = np.zeros((17))
  796. cum_intra_net_cnt = np.zeros((17))
  797. cum_inter_net = np.zeros((17))
  798. cum_inter_net_cnt = np.zeros((17))
  799. for i in range(n_rois): # rows
  800. for j in range(n_rois): # columns
  801. if i==j: # skip connections to self
  802. continue
  803. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  804. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  805. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  806. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  807. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  808. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  809. # ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  810. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  811. # plt.title('Intra-network drug effects', fontsize=12)
  812. # plt.tight_layout()
  813. # plt.savefig('_results_uncorrected/zurich_cumabs_intra.pdf')
  814. # ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  815. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  816. # plt.title('Inter-network drug effects', fontsize=12)
  817. # plt.tight_layout()
  818. # plt.savefig('_results_uncorrected/zurich_cumabs_inter.pdf')
  819. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  820. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  821. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  822. # plt.title('Intra-network drug effects', fontsize=12)
  823. # plt.tight_layout()
  824. # plt.savefig('_results_uncorrected/zurich_cumabs_intra_norm.pdf')
  825. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  826. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  827. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  828. # plt.title('Inter-network drug effects', fontsize=12)
  829. # plt.tight_layout()
  830. # plt.savefig('_results_uncorrected/zurich_cumabs_inter_norm.pdf')
  831. ax = pd.DataFrame(cum_intra_net,
  832. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  833. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  834. plt.title('Intra-network drug effects', fontsize=12)
  835. plt.tight_layout()
  836. # plt.savefig('_results_uncorrected/zurich_cumabs_intra_regnorm.pdf')
  837. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichLSD_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  838. ax = pd.DataFrame(cum_inter_net,
  839. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  840. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  841. plt.title('Inter-network drug effects', fontsize=12)
  842. plt.tight_layout()
  843. # plt.savefig('_results_uncorrected/zurich_cumabs_inter_regnorm.pdf')
  844. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichLSD_cumabs_inter_regnorm_%s.pdf' % strategy_suffix)
  845. # # no abs
  846. # cum_intra_net = np.zeros((17))
  847. # cum_intra_net_cnt = np.zeros((17))
  848. # cum_inter_net = np.zeros((17))
  849. # cum_inter_net_cnt = np.zeros((17))
  850. # for i in range(n_rois): # rows
  851. # for j in range(n_rois): # columns
  852. # if i==j: # skip connections to self
  853. # continue
  854. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  855. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  856. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  857. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  858. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  859. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  860. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  861. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  862. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  863. # plt.title('Intra-network drug effects', fontsize=12)
  864. # plt.tight_layout()
  865. # plt.savefig('_results_uncorrected/zurich_cumabs_intra_regnorm_noabs.pdf')
  866. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  867. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  868. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  869. # plt.title('Inter-network drug effects', fontsize=12)
  870. # plt.tight_layout()
  871. # plt.savefig('_results_uncorrected/zurich_cumabs_inter_regnorm_noabs.pdf')
  872. # Zurich data / Psilo: 25 subs, 2 conds (Flora, Katrin)
  873. del out_df
  874. import os
  875. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Zurich_LSD_Psilocybin/output_Psilo/sub-*/ses-*/func/sub-*_schaefer100_TS_noDenosing.csv')
  876. # QC: FD + dvars
  877. study_FDs = []
  878. study_dvars = []
  879. for sub_name in sub_strs:
  880. cur_cond = 'lsd' if 'ses-lsd' in sub_name else 'plcb'
  881. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_desc-confounds_timeseries.tsv'
  882. sub_name = sub_strs[0].split('/')[-4]
  883. print(sub_name)
  884. try:
  885. df = pd.read_csv(conf_t_path, delimiter='\t')
  886. except:
  887. continue
  888. cur_fd = (df.framewise_displacement > 0.5).sum()
  889. study_FDs.append(cur_fd)
  890. print(cur_fd)
  891. cur_dvars = df.dvars.mean()
  892. study_dvars.append(cur_dvars)
  893. print(cur_dvars)
  894. plt.figure()
  895. plt.hist(study_FDs, bins=20)
  896. # plt.title('FD (#volumes > 0.5mm): zurichpsilo')
  897. plt.title('FD (#volumes > 0.5mm out of %i total): zurichpsilo' % len(df.framewise_displacement))
  898. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_zurichpsilo_FDabove0.5mm.png', dpi=600)
  899. plt.figure()
  900. plt.hist(np.array(study_FDs) / len(df.framewise_displacement), bins=20)
  901. plt.title('FD (fraction of volumes > 0.5mm out of %i total): zurichpsilo' % len(df.framewise_displacement))
  902. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_zurichpsilo_fracFDabove0.5mm.png', dpi=600)
  903. plt.figure()
  904. plt.hist(study_dvars, bins=20)
  905. plt.title('DVARS (mean across TS): zurichpsilo')
  906. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_zurichpsilo_dvars.png')
  907. CCs = []
  908. conds = []
  909. n_skipped = 0
  910. for sub_name in sub_strs:
  911. # print(sub_name)
  912. try:
  913. sub_ts = pd.read_csv(sub_name, header=None)
  914. subcort_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_subcortical38_TS_noDenosing.csv'
  915. subcort = pd.read_csv(subcort_path, header=None)
  916. claustrum_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_claustrum_TS_noDenosing.csv'
  917. claustrum = pd.read_csv(claustrum_path, header=None)
  918. tmp = clean(
  919. signals=claustrum.iloc[:, [0, 3]].to_numpy(),
  920. confounds=claustrum.iloc[:, [1, 2, 4, 5]].to_numpy(),
  921. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  922. claustrum.iloc[:, [0, 3]] = tmp
  923. cereb_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_cerebellum_TS_noDenosing.csv'
  924. cereb = pd.read_csv(cereb_path, header=None)
  925. sub_ts = pd.concat([sub_ts, subcort, claustrum, cereb], axis=1)
  926. assert n_rois + 61 == sub_ts.shape[1]
  927. except:
  928. print(f'CSV probably corrupted: {sub_name}')
  929. sub_ts_z = pd.DataFrame(StandardScaler().fit_transform(sub_ts), columns=full_labels)
  930. cur_cond = 'psi' if '-psi' in sub_name else 'plcb'
  931. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_desc-confounds_timeseries.tsv'
  932. conf_j_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_desc-confounds_timeseries.json'
  933. if not os.path.exists(conf_t_path):
  934. print('Skipping this subject: confound file not found!')
  935. continue
  936. conf = get_my_confounds_df(conf_t_path, conf_j_path, strategy)
  937. # motion correction
  938. df = pd.read_csv(conf_t_path, delimiter='\t')
  939. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  940. if sub_motion_frac > 0.15:
  941. n_skipped += 1
  942. print('Skipping subject: %s' % sub_name)
  943. continue
  944. if len(conf) != 0:
  945. sub_ts_z_deconf = clean(
  946. signals=np.nan_to_num(sub_ts_z.values), standardize=False, confounds=np.nan_to_num(conf))
  947. else:
  948. continue
  949. print(f'{sub_name} has {len(conf.columns)} columns to noise clean!')
  950. # sub_ts_z_deconf = pd.DataFrame(
  951. # sub_ts_z_deconf, columns=cort_labels)
  952. # sub_CC = np.corrcoef(sub_ts_z_deconf.T)
  953. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf.T))
  954. study_id_all.append(3)
  955. CCs.append(sub_CC)
  956. conds.append(int(cur_cond == 'psi'))
  957. FDs_all.append(df.framewise_displacement.mean())
  958. CCs_all.append(sub_CC)
  959. conds_all.append(int(cur_cond == 'psi'))
  960. drug_all.append(0)
  961. CCs = np.array(CCs)
  962. conds = np.array(conds)
  963. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/zurichpsilo_coverage.nii.gz')
  964. from sklearn.linear_model import LinearRegression
  965. out_mat = np.zeros((161, 161))
  966. CCs = np.nan_to_num(CCs)
  967. for i_roi in range(161):
  968. for j_roi in range(161):
  969. if i_roi == j_roi:
  970. continue
  971. lr = LinearRegression(fit_intercept=True)
  972. y = CCs[:, i_roi, j_roi]
  973. X = conds[:, None]
  974. lr.fit(X, y)
  975. out_mat[i_roi, j_roi] = lr.coef_[0]
  976. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  977. if len(CCs) > 0:
  978. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  979. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  980. import matplotlib.pylab as plt
  981. plt.figure(figsize=(16, 10))
  982. sns.set(font_scale=0.4)
  983. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  984. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  985. plt.tight_layout()
  986. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichPsilo_avg_CC_plcb_%s.pdf' % strategy_suffix)
  987. import matplotlib.pylab as plt
  988. plt.figure(figsize=(16, 10))
  989. sns.set(font_scale=0.4)
  990. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  991. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  992. plt.tight_layout()
  993. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichPsilo_avg_CC_drug_%s.pdf' % strategy_suffix)
  994. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  995. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  996. # import matplotlib.pylab as plt
  997. # plt.figure(figsize=(16, 10))
  998. # sns.set(font_scale=0.4)
  999. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1000. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  1001. # plt.tight_layout()
  1002. # plt.savefig('_results_uncorrected/Zurich_avg_CC_plcb_max.pdf')
  1003. # import matplotlib.pylab as plt
  1004. # plt.figure(figsize=(16, 10))
  1005. # sns.set(font_scale=0.4)
  1006. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1007. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  1008. # plt.tight_layout()
  1009. # plt.savefig('_results_uncorrected/Zurich_avg_CC_drug_max.pdf')
  1010. import matplotlib.pylab as plt
  1011. plt.figure(figsize=(16, 10))
  1012. sns.set(font_scale=0.4)
  1013. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1014. center=0, xticklabels=full_labels, yticklabels=full_labels)
  1015. plt.tight_layout()
  1016. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichPsilo_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  1017. import matplotlib.pylab as plt
  1018. plt.figure(figsize=(20, 14))
  1019. sns.set(font_scale=0.4)
  1020. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1021. center=0)
  1022. plt.tight_layout()
  1023. # plt.savefig('_results_uncorrected/zurich_lrcoef.pdf')
  1024. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichPsilo_avg_lrcoef_%s.pdf' % strategy_suffix)
  1025. # import matplotlib.pylab as plt
  1026. # plt.figure(figsize=(20, 14))
  1027. # sns.set(font_scale=0.4)
  1028. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  1029. # center=0, vmax=.5)
  1030. # plt.tight_layout()
  1031. # plt.savefig('_results_uncorrected/zurich_lrcoef_viridis.pdf')
  1032. cum_intra_net = np.zeros((17))
  1033. cum_intra_net_cnt = np.zeros((17))
  1034. cum_inter_net = np.zeros((17))
  1035. cum_inter_net_cnt = np.zeros((17))
  1036. for i in range(n_rois): # rows
  1037. for j in range(n_rois): # columns
  1038. if i==j: # skip connections to self
  1039. continue
  1040. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  1041. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  1042. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  1043. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  1044. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  1045. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  1046. ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1047. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  1048. plt.title('Intra-network drug effects', fontsize=12)
  1049. plt.tight_layout()
  1050. # plt.savefig('_results_uncorrected/zurich_cumabs_intra.pdf')
  1051. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichPsilo_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  1052. ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1053. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  1054. plt.title('Inter-network drug effects', fontsize=12)
  1055. plt.tight_layout()
  1056. # plt.savefig('_results_uncorrected/zurich_cumabs_inter.pdf')
  1057. plt.savefig('_results_uncorrected_data_pipelines_ana8/ZurichPsilo_cumabs_inter_regnorm_%s.pdf' % strategy_suffix)
  1058. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  1059. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1060. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1061. # plt.title('Intra-network drug effects', fontsize=12)
  1062. # plt.tight_layout()
  1063. # plt.savefig('_results_uncorrected/zurich_cumabs_intra_norm.pdf')
  1064. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  1065. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1066. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1067. # plt.title('Inter-network drug effects', fontsize=12)
  1068. # plt.tight_layout()
  1069. # plt.savefig('_results_uncorrected/zurich_cumabs_inter_norm.pdf')
  1070. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  1071. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1072. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1073. # plt.title('Intra-network drug effects', fontsize=12)
  1074. # plt.tight_layout()
  1075. # plt.savefig('_results_uncorrected/zurich_cumabs_intra_regnorm.pdf')
  1076. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  1077. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1078. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1079. # plt.title('Inter-network drug effects', fontsize=12)
  1080. # plt.tight_layout()
  1081. # plt.savefig('_results_uncorrected/zurich_cumabs_inter_regnorm.pdf')
  1082. # # no abs
  1083. # cum_intra_net = np.zeros((17))
  1084. # cum_intra_net_cnt = np.zeros((17))
  1085. # cum_inter_net = np.zeros((17))
  1086. # cum_inter_net_cnt = np.zeros((17))
  1087. # for i in range(n_rois): # rows
  1088. # for j in range(n_rois): # columns
  1089. # if i==j: # skip connections to self
  1090. # continue
  1091. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  1092. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  1093. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  1094. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  1095. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  1096. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  1097. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  1098. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1099. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  1100. # plt.title('Intra-network drug effects', fontsize=12)
  1101. # plt.tight_layout()
  1102. # plt.savefig('_results_uncorrected/zurich_cumabs_intra_regnorm_noabs.pdf')
  1103. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  1104. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1105. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  1106. # plt.title('Inter-network drug effects', fontsize=12)
  1107. # plt.tight_layout()
  1108. # plt.savefig('_results_uncorrected/zurich_cumabs_inter_regnorm_noabs.pdf')
  1109. # continue # HACK !!! skipping Barrett for now
  1110. # Barrett data: 38 subs, 2 conds (Barrett, Manoj Doss)
  1111. del out_df
  1112. # import os
  1113. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Barrett_Psilocybin/*/*/*_schaefer100_TS_noDenosing.csv')
  1114. # QC: FD + dvars
  1115. study_FDs = []
  1116. study_dvars = []
  1117. for sub_name in sub_strs:
  1118. cur_cond = 'psilocybin' if 'Session5' in sub_name else 'plcb'
  1119. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_desc-confounds_timeseries.tsv'
  1120. sub_name = sub_strs[0].split('/')[-3]
  1121. print(sub_name)
  1122. try:
  1123. df = pd.read_csv(conf_t_path, delimiter='\t')
  1124. except:
  1125. continue
  1126. cur_fd = (df.framewise_displacement > 0.5).sum()
  1127. study_FDs.append(cur_fd)
  1128. print(cur_fd)
  1129. cur_dvars = df.dvars.mean()
  1130. study_dvars.append(cur_dvars)
  1131. print(cur_dvars)
  1132. plt.figure()
  1133. plt.hist(study_FDs, bins=20)
  1134. # plt.title('FD (#volumes > 0.5mm): barrett')
  1135. plt.title('FD (#volumes > 0.5mm out of %i total): barrett' % len(df.framewise_displacement))
  1136. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_barrett_FDabove0.5mm.png', dpi=600)
  1137. plt.figure()
  1138. plt.hist(np.array(study_FDs) / len(df.framewise_displacement), bins=20)
  1139. plt.title('FD (fraction of volumes > 0.5mm out of %i total): barrett' % len(df.framewise_displacement))
  1140. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_barrett_fracFDabove0.5mm.png', dpi=600)
  1141. plt.figure()
  1142. plt.hist(study_dvars, bins=20)
  1143. plt.title('DVARS (mean across TS): barrett')
  1144. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_barrett_dvars.png')
  1145. CCs = []
  1146. n_skipped = 0
  1147. conds = []
  1148. for sub_name in sub_strs:
  1149. # print(sub_name)
  1150. sub_ts = pd.read_csv(sub_name, header=None)
  1151. subcort_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_subcortical38_TS_noDenosing.csv'
  1152. subcort = pd.read_csv(subcort_path, header=None)
  1153. claustrum_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_claustrum_TS_noDenosing.csv'
  1154. claustrum = pd.read_csv(claustrum_path, header=None)
  1155. tmp = clean(
  1156. signals=claustrum.iloc[:, [0, 3]].to_numpy(),
  1157. confounds=claustrum.iloc[:, [1, 2, 4, 5]].to_numpy(),
  1158. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  1159. claustrum.iloc[:, [0, 3]] = tmp
  1160. cereb_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_cerebellum_TS_noDenosing.csv'
  1161. cereb = pd.read_csv(cereb_path, header=None)
  1162. sub_ts = pd.concat([sub_ts, subcort, claustrum, cereb], axis=1)
  1163. assert n_rois + 61 == sub_ts.shape[1]
  1164. sub_ts_z = pd.DataFrame(StandardScaler().fit_transform(sub_ts), columns=full_labels)
  1165. cur_cond = 'psilocybin' if 'Session5' in sub_name else 'plcb'
  1166. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_desc-confounds_timeseries.tsv'
  1167. conf_j_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_desc-confounds_timeseries.json'
  1168. if not os.path.exists(conf_t_path):
  1169. print('Skipping this subject: confound file not found!')
  1170. continue
  1171. conf = get_my_confounds_df(conf_t_path, conf_j_path, strategy)
  1172. # motion correction
  1173. df = pd.read_csv(conf_t_path, delimiter='\t')
  1174. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  1175. if sub_motion_frac > 0.15:
  1176. print('Skipping subject: %s' % sub_name)
  1177. n_skipped += 1
  1178. continue
  1179. if len(conf) != 0:
  1180. sub_ts_z_deconf = clean(
  1181. signals=np.nan_to_num(sub_ts_z.values), standardize=False, confounds=np.nan_to_num(conf))
  1182. else:
  1183. continue
  1184. print(f'{sub_name} has {len(conf.columns)} columns to noise clean!')
  1185. # sub_ts_z_deconf = pd.DataFrame(
  1186. # sub_ts_z_deconf, columns=cort_labels)
  1187. # sub_CC = np.corrcoef(sub_ts_z_deconf.T)
  1188. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf.T))
  1189. # reg_avg_activity_bar.append(sub_ts.median(0).values)
  1190. # reg_avg_activity_bar_std.append(sub_ts.median(0).values)
  1191. #reg_avg_activity.append(sub_ts.mean(0).values)
  1192. study_id_all.append(4)
  1193. CCs.append(sub_CC)
  1194. conds.append(int(cur_cond == 'psilocybin'))
  1195. FDs_all.append(df.framewise_displacement.mean())
  1196. CCs_all.append(sub_CC)
  1197. conds_all.append(int(cur_cond == 'psilocybin'))
  1198. drug_all.append(0)
  1199. # study_id.append(3)
  1200. CCs = np.array(CCs)
  1201. conds = np.array(conds)
  1202. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/barrett_coverage.nii.gz')
  1203. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  1204. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  1205. import matplotlib.pylab as plt
  1206. plt.figure(figsize=(16, 10))
  1207. sns.set(font_scale=0.4)
  1208. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1209. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1210. plt.tight_layout()
  1211. plt.savefig('_results_uncorrected_data_pipelines_ana8/Barrett_avg_CC_plcb_%s.pdf' % strategy_suffix)
  1212. import matplotlib.pylab as plt
  1213. plt.figure(figsize=(16, 10))
  1214. sns.set(font_scale=0.4)
  1215. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1216. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1217. plt.tight_layout()
  1218. plt.savefig('_results_uncorrected_data_pipelines_ana8/Barrett_avg_CC_drug_%s.pdf' % strategy_suffix)
  1219. import matplotlib.pylab as plt
  1220. plt.figure(figsize=(16, 10))
  1221. sns.set(font_scale=0.4)
  1222. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1223. center=0, xticklabels=full_labels, yticklabels=full_labels)
  1224. plt.tight_layout()
  1225. plt.savefig('_results_uncorrected_data_pipelines_ana8/Barrett_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  1226. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  1227. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  1228. # import matplotlib.pylab as plt
  1229. # plt.figure(figsize=(16, 10))
  1230. # sns.set(font_scale=0.4)
  1231. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1232. # center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1233. # plt.tight_layout()
  1234. # plt.savefig('_results_uncorrected/Barrett_avg_CC_plcb_max.pdf')
  1235. # import matplotlib.pylab as plt
  1236. # plt.figure(figsize=(16, 10))
  1237. # sns.set(font_scale=0.4)
  1238. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1239. # center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1240. # plt.tight_layout()
  1241. # plt.savefig('_results_uncorrected/Barrett_avg_CC_drug_max.pdf')
  1242. import matplotlib.pylab as plt
  1243. plt.figure(figsize=(16, 10))
  1244. sns.set(font_scale=0.4)
  1245. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1246. center=0, xticklabels=full_labels, yticklabels=full_labels)
  1247. plt.tight_layout()
  1248. plt.savefig('_results_uncorrected_data_pipelines_ana8/Barrett_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  1249. from sklearn.linear_model import LinearRegression
  1250. out_df = np.zeros((161, 161))
  1251. CCs = np.nan_to_num(CCs)
  1252. for i_roi in range(161):
  1253. for j_roi in range(161):
  1254. if i_roi == j_roi:
  1255. continue
  1256. lr = LinearRegression(fit_intercept=True)
  1257. y = CCs[:, i_roi, j_roi]
  1258. X = conds[:, None]
  1259. lr.fit(X, y)
  1260. out_mat[i_roi, j_roi] = lr.coef_[0]
  1261. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  1262. import matplotlib.pylab as plt
  1263. plt.figure(figsize=(20, 14))
  1264. sns.set(font_scale=0.4)
  1265. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1266. center=0)
  1267. plt.tight_layout()
  1268. # plt.savefig('_results_uncorrected/barret_lrcoef.pdf')
  1269. plt.savefig('_results_uncorrected_data_pipelines_ana8/Barrett_avg_lrcoef_%s.pdf' % strategy_suffix)
  1270. # import matplotlib.pylab as plt
  1271. # plt.figure(figsize=(20, 14))
  1272. # sns.set(font_scale=0.4)
  1273. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  1274. # center=0, vmax=.35)
  1275. # plt.tight_layout()
  1276. # plt.savefig('_results_uncorrected/barret_lrcoef_viridis.pdf')
  1277. cum_intra_net = np.zeros((17))
  1278. cum_intra_net_cnt = np.zeros((17))
  1279. cum_inter_net = np.zeros((17))
  1280. cum_inter_net_cnt = np.zeros((17))
  1281. for i in range(n_rois): # rows
  1282. for j in range(n_rois): # columns
  1283. if i==j: # skip connections to self
  1284. continue
  1285. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  1286. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  1287. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  1288. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  1289. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  1290. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  1291. ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1292. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  1293. plt.title('Intra-network drug effects', fontsize=12)
  1294. plt.tight_layout()
  1295. # plt.savefig('_results_uncorrected/barrett_cumabs_intra.pdf')
  1296. plt.savefig('_results_uncorrected_data_pipelines_ana8/Barrett_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  1297. ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1298. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  1299. plt.title('Inter-network drug effects', fontsize=12)
  1300. plt.tight_layout()
  1301. # plt.savefig('_results_uncorrected/barrett_cumabs_inter.pdf')
  1302. plt.savefig('_results_uncorrected_data_pipelines_ana8/Barrett_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  1303. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  1304. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1305. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1306. # plt.title('Intra-network drug effects', fontsize=12)
  1307. # plt.tight_layout()
  1308. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_norm.pdf')
  1309. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  1310. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1311. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1312. # plt.title('Inter-network drug effects', fontsize=12)
  1313. # plt.tight_layout()
  1314. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_norm.pdf')
  1315. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  1316. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1317. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1318. # plt.title('Intra-network drug effects', fontsize=12)
  1319. # plt.tight_layout()
  1320. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_regnorm.pdf')
  1321. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  1322. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1323. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1324. # plt.title('Inter-network drug effects', fontsize=12)
  1325. # plt.tight_layout()
  1326. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_regnorm.pdf')
  1327. # # no abs
  1328. # cum_intra_net = np.zeros((17))
  1329. # cum_intra_net_cnt = np.zeros((17))
  1330. # cum_inter_net = np.zeros((17))
  1331. # cum_inter_net_cnt = np.zeros((17))
  1332. # for i in range(n_rois): # rows
  1333. # for j in range(n_rois): # columns
  1334. # if i==j: # skip connections to self
  1335. # continue
  1336. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  1337. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  1338. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  1339. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  1340. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  1341. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  1342. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  1343. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1344. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  1345. # plt.title('Intra-network drug effects', fontsize=12)
  1346. # plt.tight_layout()
  1347. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_regnorm_noabs.pdf')
  1348. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  1349. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1350. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  1351. # plt.title('Inter-network drug effects', fontsize=12)
  1352. # plt.tight_layout()
  1353. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_regnorm_noabs.pdf')
  1354. # Roseman data: Psilocybin, 15 subjects
  1355. del out_df
  1356. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Roseman_Psilocybin/sub-*/ses-*/func/sub-*_ses-*_run*_schaefer100_TS_noDenosing.csv')
  1357. # QC: FD + dvars
  1358. study_FDs = []
  1359. study_dvars = []
  1360. for sub_name in sub_strs:
  1361. cur_cond = 'PSILO' if 'PSILO' in sub_name else 'plcb'
  1362. conf_t_path = sub_name.split('_ses-')[0] + '_ses-%s_task-rest_run-1_desc-confounds_timeseries.tsv' % cur_cond
  1363. sub_name = sub_strs[0].split('/')[-4]
  1364. print(sub_name)
  1365. try:
  1366. df = pd.read_csv(conf_t_path, delimiter='\t')
  1367. except:
  1368. continue
  1369. cur_fd = (df.framewise_displacement > 0.5).sum()
  1370. study_FDs.append(cur_fd)
  1371. print(cur_fd)
  1372. cur_dvars = df.dvars.mean()
  1373. study_dvars.append(cur_dvars)
  1374. print(cur_dvars)
  1375. plt.figure()
  1376. plt.hist(study_FDs, bins=20)
  1377. # plt.title('FD (#volumes > 0.5mm): Roseman_Psilocybin')
  1378. plt.title('FD (#volumes > 0.5mm out of %i total): Roseman_Psilocybin' % len(df.framewise_displacement))
  1379. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Roseman_Psilocybin_FDabove0.5mm.png', dpi=600)
  1380. plt.figure()
  1381. plt.hist(np.array(study_FDs) / len(df.framewise_displacement), bins=20)
  1382. plt.title('FD (fraction of volumes > 0.5mm out of %i total): Roseman_Psilocybin' % len(df.framewise_displacement))
  1383. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Roseman_Psilocybin_fracFDabove0.5mm.png', dpi=600)
  1384. plt.figure()
  1385. plt.hist(study_dvars, bins=20)
  1386. plt.title('DVARS (mean across TS): Roseman_Psilocybin')
  1387. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Roseman_Psilocybin_dvars.png')
  1388. CCs = []
  1389. n_skipped = 0
  1390. conds = []
  1391. for sub_name in sub_strs:
  1392. # print(sub_name)
  1393. sub_ts = pd.read_csv(sub_name, header=None)
  1394. subcort_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_subcortical38_TS_noDenosing.csv'
  1395. subcort = pd.read_csv(subcort_path, header=None)
  1396. claustrum_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_claustrum_TS_noDenosing.csv'
  1397. claustrum = pd.read_csv(claustrum_path, header=None)
  1398. tmp = clean(
  1399. signals=claustrum.iloc[:, [0, 3]].to_numpy(),
  1400. confounds=claustrum.iloc[:, [1, 2, 4, 5]].to_numpy(),
  1401. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  1402. claustrum.iloc[:, [0, 3]] = tmp
  1403. cereb_path = conf_path = sub_name.split('_schaefer100_TS')[0] + '_cerebellum_TS_noDenosing.csv'
  1404. cereb = pd.read_csv(cereb_path, header=None)
  1405. sub_ts = pd.concat([sub_ts, subcort, claustrum, cereb], axis=1)
  1406. sub_ts_z = pd.DataFrame(StandardScaler().fit_transform(sub_ts), columns=full_labels)
  1407. cur_cond = 'PSILO' if 'PSILO' in sub_name else 'plcb'
  1408. conf_t_path = sub_name.split('_ses-')[0] + '_ses-%s_task-rest_run-1_desc-confounds_timeseries.tsv' % cur_cond
  1409. conf_j_path = conf_t_path.replace('.tsv', '.json')
  1410. if not os.path.exists(conf_t_path):
  1411. print('Skipping this subject: confound file not found!')
  1412. continue
  1413. conf = get_my_confounds_df(conf_t_path, conf_j_path, strategy)
  1414. # motion correction
  1415. df = pd.read_csv(conf_t_path, delimiter='\t')
  1416. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  1417. if sub_motion_frac > 0.15:
  1418. print('Skipping subject: %s' % sub_name)
  1419. n_skipped += 1
  1420. continue
  1421. if len(conf) != 0:
  1422. sub_ts_z_deconf = clean(
  1423. signals=np.nan_to_num(sub_ts_z.values), standardize=False, confounds=np.nan_to_num(conf))
  1424. else:
  1425. continue
  1426. print(f'{sub_name} has {len(conf.columns)} columns to noise clean!')
  1427. # sub_ts_z_deconf = pd.DataFrame(
  1428. # sub_ts_z_deconf, columns=cort_labels)
  1429. # sub_CC = np.corrcoef(sub_ts_z_deconf.T)
  1430. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf.T))
  1431. # reg_avg_activity_bar.append(sub_ts.median(0).values)
  1432. # reg_avg_activity_bar_std.append(sub_ts.median(0).values)
  1433. #reg_avg_activity.append(sub_ts.mean(0).values)
  1434. study_id_all.append(5)
  1435. CCs.append(sub_CC)
  1436. conds.append(int(cur_cond == 'PSILO'))
  1437. FDs_all.append(df.framewise_displacement.mean())
  1438. CCs_all.append(sub_CC)
  1439. conds_all.append(int(cur_cond == 'PSILO'))
  1440. drug_all.append(0)
  1441. # study_id.append(3)
  1442. CCs = np.array(CCs)
  1443. conds = np.array(conds)
  1444. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/rosemanpsilo_coverage.nii.gz')
  1445. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  1446. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  1447. import matplotlib.pylab as plt
  1448. plt.figure(figsize=(16, 10))
  1449. sns.set(font_scale=0.4)
  1450. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1451. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1452. plt.tight_layout()
  1453. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanPsilocybin_avg_CC_plcb_%s.pdf' % strategy_suffix)
  1454. import matplotlib.pylab as plt
  1455. plt.figure(figsize=(16, 10))
  1456. sns.set(font_scale=0.4)
  1457. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1458. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1459. plt.tight_layout()
  1460. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanPsilocybin_avg_CC_drug_%s.pdf' % strategy_suffix)
  1461. import matplotlib.pylab as plt
  1462. plt.figure(figsize=(16, 10))
  1463. sns.set(font_scale=0.4)
  1464. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1465. center=0, xticklabels=full_labels, yticklabels=full_labels)
  1466. plt.tight_layout()
  1467. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanPsilocybin_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  1468. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  1469. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  1470. # import matplotlib.pylab as plt
  1471. # plt.figure(figsize=(16, 10))
  1472. # sns.set(font_scale=0.4)
  1473. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1474. # center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1475. # plt.tight_layout()
  1476. # plt.savefig('_results_uncorrected/Barrett_avg_CC_plcb_max.pdf')
  1477. # import matplotlib.pylab as plt
  1478. # plt.figure(figsize=(16, 10))
  1479. # sns.set(font_scale=0.4)
  1480. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1481. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  1482. # plt.tight_layout()
  1483. # plt.savefig('_results_uncorrected/Barrett_avg_CC_drug_max.pdf')
  1484. # import matplotlib.pylab as plt
  1485. # plt.figure(figsize=(16, 10))
  1486. # sns.set(font_scale=0.4)
  1487. # sns.heatmap(CC_avg_plcb - CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1488. # center=0, xticklabels=cort_labels, yticklabels=cort_labels)
  1489. # plt.tight_layout()
  1490. # plt.savefig('_results_uncorrected/Barrett_avg_CC_plcb-drug.pdf')
  1491. from sklearn.linear_model import LinearRegression
  1492. out_df = np.zeros((161, 161))
  1493. CCs = np.nan_to_num(CCs)
  1494. for i_roi in range(161):
  1495. for j_roi in range(161):
  1496. if i_roi == j_roi:
  1497. continue
  1498. lr = LinearRegression(fit_intercept=True)
  1499. y = CCs[:, i_roi, j_roi]
  1500. X = conds[:, None]
  1501. lr.fit(X, y)
  1502. out_df[i_roi, j_roi] = lr.coef_[0]
  1503. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  1504. import matplotlib.pylab as plt
  1505. plt.figure(figsize=(20, 14))
  1506. sns.set(font_scale=0.4)
  1507. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1508. center=0)
  1509. plt.tight_layout()
  1510. # plt.savefig('_results_uncorrected/barret_lrcoef.pdf')
  1511. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanPsilocybin_avg_lrcoef_%s.pdf' % strategy_suffix)
  1512. # import matplotlib.pylab as plt
  1513. # plt.figure(figsize=(20, 14))
  1514. # sns.set(font_scale=0.4)
  1515. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  1516. # center=0, vmax=.35)
  1517. # plt.tight_layout()
  1518. # plt.savefig('_results_uncorrected/barret_lrcoef_viridis.pdf')
  1519. cum_intra_net = np.zeros((17))
  1520. cum_intra_net_cnt = np.zeros((17))
  1521. cum_inter_net = np.zeros((17))
  1522. cum_inter_net_cnt = np.zeros((17))
  1523. for i in range(n_rois): # rows
  1524. for j in range(n_rois): # columns
  1525. if i==j: # skip connections to self
  1526. continue
  1527. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  1528. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  1529. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  1530. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  1531. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  1532. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  1533. ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1534. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  1535. plt.title('Intra-network drug effects', fontsize=12)
  1536. plt.tight_layout()
  1537. # plt.savefig('_results_uncorrected/barrett_cumabs_intra.pdf')
  1538. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanPsilocybin_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  1539. ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1540. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  1541. plt.title('Inter-network drug effects', fontsize=12)
  1542. plt.tight_layout()
  1543. # plt.savefig('_results_uncorrected/barrett_cumabs_inter.pdf')
  1544. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanPsilocybin_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  1545. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  1546. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1547. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1548. # plt.title('Intra-network drug effects', fontsize=12)
  1549. # plt.tight_layout()
  1550. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_norm.pdf')
  1551. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  1552. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1553. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1554. # plt.title('Inter-network drug effects', fontsize=12)
  1555. # plt.tight_layout()
  1556. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_norm.pdf')
  1557. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  1558. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1559. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1560. # plt.title('Intra-network drug effects', fontsize=12)
  1561. # plt.tight_layout()
  1562. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_regnorm.pdf')
  1563. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  1564. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1565. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1566. # plt.title('Inter-network drug effects', fontsize=12)
  1567. # plt.tight_layout()
  1568. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_regnorm.pdf')
  1569. # # no abs
  1570. # cum_intra_net = np.zeros((17))
  1571. # cum_intra_net_cnt = np.zeros((17))
  1572. # cum_inter_net = np.zeros((17))
  1573. # cum_inter_net_cnt = np.zeros((17))
  1574. # for i in range(n_rois): # rows
  1575. # for j in range(n_rois): # columns
  1576. # if i==j: # skip connections to self
  1577. # continue
  1578. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  1579. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  1580. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  1581. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  1582. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  1583. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  1584. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  1585. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1586. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  1587. # plt.title('Intra-network drug effects', fontsize=12)
  1588. # plt.tight_layout()
  1589. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_regnorm_noabs.pdf')
  1590. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  1591. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1592. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  1593. # plt.title('Inter-network drug effects', fontsize=12)
  1594. # plt.tight_layout()
  1595. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_regnorm_noabs.pdf')
  1596. # Roseman data: LSD, 38 subjects
  1597. del out_df
  1598. # TODO: do the cross-corr in run1 and in run3 for a given subject first, then average the two
  1599. # to obtain a single cross-corr matrix for a given subject
  1600. # goal being to have one set of obsevation per subject (for lat statistical inference)
  1601. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Roseman_LSD/sub-*/ses-*/func/sub-*_ses-*_run-1_schaefer100_TS_noDenosing.csv')
  1602. # QC: FD + dvars
  1603. study_FDs = []
  1604. study_dvars = []
  1605. for sub_name in sub_strs:
  1606. cur_cond = 'plcb' if '-plcb' in sub_name else 'LSD'
  1607. conf_t_path = sub_name.split('_ses-')[0] + '_ses-%s_task-rest_run-1_desc-confounds_timeseries.tsv' % cur_cond
  1608. sub_name = sub_strs[0].split('/')[-4]
  1609. print(sub_name)
  1610. try:
  1611. df = pd.read_csv(conf_t_path, delimiter='\t')
  1612. except:
  1613. continue
  1614. cur_fd = (df.framewise_displacement > 0.5).sum()
  1615. study_FDs.append(cur_fd)
  1616. print(cur_fd)
  1617. cur_dvars = df.dvars.mean()
  1618. study_dvars.append(cur_dvars)
  1619. print(cur_dvars)
  1620. plt.figure()
  1621. plt.hist(study_FDs, bins=20)
  1622. # plt.title('FD (#volumes > 0.5mm): Roseman_LSD')
  1623. plt.title('FD (#volumes > 0.5mm out of %i total): Roseman_LSD' % len(df.framewise_displacement))
  1624. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Roseman_LSD_FDabove0.5mm.png', dpi=600)
  1625. plt.figure()
  1626. plt.hist(np.array(study_FDs) / len(df.framewise_displacement), bins=20)
  1627. plt.title('FD (fraction of volumes > 0.5mm out of %i total): Roseman_LSD' % len(df.framewise_displacement))
  1628. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Roseman_LSD_fracFDabove0.5mm.png', dpi=600)
  1629. plt.figure()
  1630. plt.hist(study_dvars, bins=20)
  1631. plt.title('DVARS (mean across TS): Roseman_LSD')
  1632. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Roseman_LSD_dvars.png')
  1633. CCs = []
  1634. n_skipped = 0
  1635. conds = []
  1636. for sub_name in sub_strs:
  1637. # print(sub_name)
  1638. sub_ts1 = pd.read_csv(sub_name, header=None)
  1639. subcort1_path = sub_name.replace('schaefer%s' % n_rois, 'subcortical38')
  1640. subcort1 = pd.read_csv(subcort1_path, header=None)
  1641. claustrum1_path = sub_name.replace('schaefer%s' % n_rois, 'claustrum')
  1642. claustrum1 = pd.read_csv(claustrum1_path, header=None)
  1643. tmp = clean(
  1644. signals=claustrum1.iloc[:, [0, 3]].to_numpy(),
  1645. confounds=claustrum1.iloc[:, [1, 2, 4, 5]].to_numpy(),
  1646. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  1647. claustrum1.iloc[:, [0, 3]] = tmp
  1648. cerebellum1_path = sub_name.replace('schaefer%s' % n_rois, 'cerebellum')
  1649. cerebellum1 = pd.read_csv(cerebellum1_path, header=None)
  1650. sub_ts1 = pd.concat([sub_ts1, subcort1, claustrum1, cerebellum1], axis=1)
  1651. assert sub_ts1.shape[1] == 161
  1652. sub_ts_z1 = pd.DataFrame(StandardScaler().fit_transform(sub_ts1), columns=full_labels)
  1653. cur_cond = 'plcb' if '-plcb' in sub_name else 'LSD'
  1654. conf_t_path1 = sub_name.split('_ses-')[0] + '_ses-%s_task-rest_run-1_desc-confounds_timeseries.tsv' % cur_cond
  1655. conf_j_path1 = conf_t_path.replace('.tsv', '.json')
  1656. if not os.path.exists(conf_t_path1):
  1657. print('Skipping this subject: confound file not found!')
  1658. continue
  1659. conf1 = get_my_confounds_df(conf_t_path1, conf_j_path1, strategy)
  1660. # motion correction
  1661. df = pd.read_csv(conf_t_path1, delimiter='\t')
  1662. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  1663. if sub_motion_frac > 0.15:
  1664. print('Skipping subject: %s' % sub_name)
  1665. n_skipped += 1
  1666. continue
  1667. if len(conf1) != 0:
  1668. conf1 = np.nan_to_num(conf1)
  1669. sub_ts_z_deconf1 = clean(
  1670. signals=sub_ts_z1.values, standardize=False, confounds=np.nan_to_num(conf1))
  1671. else:
  1672. continue
  1673. sub_CC1 = np.arctanh(np.corrcoef(sub_ts_z_deconf1.T))
  1674. sub_name2 = sub_name.replace('run-1', 'run-3')
  1675. sub_ts2 = pd.read_csv(sub_name2, header=None)
  1676. subcort2_path = subcort1_path.replace('run-1', 'run-3')
  1677. subcort2 = pd.read_csv(subcort2_path, header=None)
  1678. claustrum2_path = claustrum1_path.replace('run-1', 'run-3')
  1679. claustrum2 = pd.read_csv(claustrum2_path, header=None)
  1680. tmp = clean(
  1681. signals=claustrum2.iloc[:, [0, 3]].to_numpy(),
  1682. confounds=claustrum2.iloc[:, [1, 2, 4, 5]].to_numpy(),
  1683. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  1684. claustrum2.iloc[:, [0, 3]] = tmp
  1685. cerebellum2_path = cerebellum1_path.replace('run-1', 'run-3')
  1686. cerebellum2 = pd.read_csv(cerebellum2_path, header=None)
  1687. sub_ts2 = pd.concat([sub_ts2, subcort2, claustrum2, cerebellum2], axis=1)
  1688. assert sub_ts2.shape[1] == 161
  1689. sub_ts_z2 = pd.DataFrame(StandardScaler().fit_transform(sub_ts2), columns=full_labels)
  1690. conf_t_path2 = sub_name.split('_ses-')[0] + '_ses-%s_task-rest_run-3_desc-confounds_timeseries.tsv' % cur_cond
  1691. conf_j_path2 = conf_t_path.replace('.tsv', '.json')
  1692. if not os.path.exists(conf_t_path2):
  1693. print('Skipping this subject: confound file not found!')
  1694. continue
  1695. conf2 = get_my_confounds_df(conf_t_path2, conf_j_path2, strategy)
  1696. # motion correction
  1697. df = pd.read_csv(conf_t_path2, delimiter='\t')
  1698. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  1699. if sub_motion_frac > 0.15:
  1700. print('Skipping subject: %s' % sub_name)
  1701. n_skipped += 1
  1702. continue
  1703. if len(conf2) != 0:
  1704. conf2 = np.nan_to_num(conf2)
  1705. sub_ts_z_deconf2 = clean(
  1706. signals=sub_ts_z2.values, standardize=False, confounds=np.nan_to_num(conf2))
  1707. else:
  1708. continue
  1709. sub_CC2 = np.arctanh(np.corrcoef(sub_ts_z_deconf2.T))
  1710. # reg_avg_activity_bar.append(sub_ts.median(0).values)
  1711. # reg_avg_activity_bar_std.append(sub_ts.median(0).values)
  1712. #reg_avg_activity.append(sub_ts.mean(0).values)
  1713. CCs.append(np.mean([sub_CC1, sub_CC2], axis=0)) # concatenating across run1 and run3 cross-corr matrices
  1714. conds.append(int(cur_cond == 'LSD'))
  1715. FDs_all.append(df.framewise_displacement.mean())
  1716. CCs_all.append(np.mean([sub_CC1, sub_CC2], axis=0)) # concatenating across run1 and run3 cross-corr matrices
  1717. conds_all.append(int(cur_cond == 'LSD'))
  1718. study_id_all.append(6)
  1719. drug_all.append(1)
  1720. CCs = np.array(CCs)
  1721. conds = np.array(conds)
  1722. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/rosemanlsd_coverage.nii.gz')
  1723. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  1724. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  1725. import matplotlib.pylab as plt
  1726. plt.figure(figsize=(16, 10))
  1727. sns.set(font_scale=0.4)
  1728. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1729. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1730. plt.tight_layout()
  1731. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanLSD_avg_CC_plcb_%s.pdf' % strategy_suffix)
  1732. import matplotlib.pylab as plt
  1733. plt.figure(figsize=(16, 10))
  1734. sns.set(font_scale=0.4)
  1735. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1736. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1737. plt.tight_layout()
  1738. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanLSD_avg_CC_drug_%s.pdf' % strategy_suffix)
  1739. import matplotlib.pylab as plt
  1740. plt.figure(figsize=(16, 10))
  1741. sns.set(font_scale=0.4)
  1742. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1743. center=0, xticklabels=full_labels, yticklabels=full_labels)
  1744. plt.tight_layout()
  1745. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanLSD_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  1746. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  1747. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  1748. # import matplotlib.pylab as plt
  1749. # plt.figure(figsize=(16, 10))
  1750. # sns.set(font_scale=0.4)
  1751. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1752. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  1753. # plt.tight_layout()
  1754. # plt.savefig('_results_uncorrected/Barrett_avg_CC_plcb_max.pdf')
  1755. # import matplotlib.pylab as plt
  1756. # plt.figure(figsize=(16, 10))
  1757. # sns.set(font_scale=0.4)
  1758. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1759. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  1760. # plt.tight_layout()
  1761. # plt.savefig('_results_uncorrected/Barrett_avg_CC_drug_max.pdf')
  1762. # import matplotlib.pylab as plt
  1763. # plt.figure(figsize=(16, 10))
  1764. # sns.set(font_scale=0.4)
  1765. # sns.heatmap(CC_avg_plcb - CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1766. # center=0, xticklabels=cort_labels, yticklabels=cort_labels)
  1767. # plt.tight_layout()
  1768. # plt.savefig('_results_uncorrected/Barrett_avg_CC_plcb-drug.pdf')
  1769. from sklearn.linear_model import LinearRegression
  1770. out_mat = np.zeros((161, 161))
  1771. CCs = np.nan_to_num(CCs)
  1772. for i_roi in range(161):
  1773. for j_roi in range(161):
  1774. if i_roi == j_roi:
  1775. continue
  1776. lr = LinearRegression(fit_intercept=True)
  1777. y = CCs[:, i_roi, j_roi]
  1778. X = conds[:, None]
  1779. lr.fit(X, y)
  1780. out_mat[i_roi, j_roi] = lr.coef_[0]
  1781. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  1782. import matplotlib.pylab as plt
  1783. plt.figure(figsize=(20, 14))
  1784. sns.set(font_scale=0.4)
  1785. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1786. center=0)
  1787. plt.tight_layout()
  1788. # plt.savefig('_results_uncorrected/barret_lrcoef.pdf')
  1789. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanLSD_avg_lrcoef_%s.pdf' % strategy_suffix)
  1790. # import matplotlib.pylab as plt
  1791. # plt.figure(figsize=(20, 14))
  1792. # sns.set(font_scale=0.4)
  1793. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  1794. # center=0, vmax=.35)
  1795. # plt.tight_layout()
  1796. # plt.savefig('_results_uncorrected/barret_lrcoef_viridis.pdf')
  1797. cum_intra_net = np.zeros((17))
  1798. cum_intra_net_cnt = np.zeros((17))
  1799. cum_inter_net = np.zeros((17))
  1800. cum_inter_net_cnt = np.zeros((17))
  1801. for i in range(n_rois): # rows
  1802. for j in range(n_rois): # columns
  1803. if i==j: # skip connections to self
  1804. continue
  1805. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  1806. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  1807. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  1808. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  1809. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  1810. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  1811. ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1812. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  1813. plt.title('Intra-network drug effects', fontsize=12)
  1814. plt.tight_layout()
  1815. # plt.savefig('_results_uncorrected/barrett_cumabs_intra.pdf')
  1816. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanLSD_avg_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  1817. ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1818. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  1819. plt.title('Inter-network drug effects', fontsize=12)
  1820. plt.tight_layout()
  1821. # plt.savefig('_results_uncorrected/barrett_cumabs_inter.pdf')
  1822. plt.savefig('_results_uncorrected_data_pipelines_ana8/RosemanLSD_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  1823. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  1824. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1825. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1826. # plt.title('Intra-network drug effects', fontsize=12)
  1827. # plt.tight_layout()
  1828. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_norm.pdf')
  1829. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  1830. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1831. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1832. # plt.title('Inter-network drug effects', fontsize=12)
  1833. # plt.tight_layout()
  1834. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_norm.pdf')
  1835. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  1836. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1837. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1838. # plt.title('Intra-network drug effects', fontsize=12)
  1839. # plt.tight_layout()
  1840. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_regnorm.pdf')
  1841. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  1842. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1843. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  1844. # plt.title('Inter-network drug effects', fontsize=12)
  1845. # plt.tight_layout()
  1846. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_regnorm.pdf')
  1847. # # no abs
  1848. # cum_intra_net = np.zeros((17))
  1849. # cum_intra_net_cnt = np.zeros((17))
  1850. # cum_inter_net = np.zeros((17))
  1851. # cum_inter_net_cnt = np.zeros((17))
  1852. # for i in range(n_rois): # rows
  1853. # for j in range(n_rois): # columns
  1854. # if i==j: # skip connections to self
  1855. # continue
  1856. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  1857. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  1858. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  1859. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  1860. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  1861. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  1862. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  1863. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1864. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  1865. # plt.title('Intra-network drug effects', fontsize=12)
  1866. # plt.tight_layout()
  1867. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_regnorm_noabs.pdf')
  1868. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  1869. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  1870. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  1871. # plt.title('Inter-network drug effects', fontsize=12)
  1872. # plt.tight_layout()
  1873. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_regnorm_noabs.pdf')
  1874. # Basel LSD data: 50 subs, 2 conds
  1875. import os
  1876. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Basel_LSD_TS/sub*/*/func/sub-*_schaefer100_TS_noDenosing.csv')
  1877. # QC: FD + dvars
  1878. study_FDs = []
  1879. study_dvars = []
  1880. for sub_name in sub_strs:
  1881. cur_cond = 'plcb' if 'ses-plcb' in sub_name else 'LSD'
  1882. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_run-01_desc-confounds_timeseries.tsv'
  1883. sub_name = sub_strs[0].split('/')[-4]
  1884. print(sub_name)
  1885. df = pd.read_csv(conf_t_path, delimiter='\t')
  1886. cur_fd = (df.framewise_displacement > 0.5).sum()
  1887. study_FDs.append(cur_fd)
  1888. print(cur_fd)
  1889. cur_dvars = df.dvars.mean()
  1890. study_dvars.append(cur_dvars)
  1891. print(cur_dvars)
  1892. plt.figure()
  1893. plt.hist(study_FDs, bins=20)
  1894. # plt.title('FD (#volumes > 0.5mm): BaselLSD')
  1895. plt.title('FD (#volumes > 0.5mm out of %i total): Basel_LSD' % len(df.framewise_displacement))
  1896. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_BaselLSD_FDabove0.5mm.png', dpi=600)
  1897. plt.figure()
  1898. plt.hist(np.array(study_FDs) / len(df.framewise_displacement), bins=20)
  1899. plt.title('FD (fraction of volumes > 0.5mm out of %i total): BaselLSD' % len(df.framewise_displacement))
  1900. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_BaselLSD_fracFDabove0.5mm.png', dpi=600)
  1901. plt.figure()
  1902. plt.hist(study_dvars, bins=20)
  1903. plt.title('DVARS (mean across TS): BaselLSD')
  1904. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_BaselLSD_dvars.png')
  1905. CCs = []
  1906. n_skipped = 0
  1907. conds = []
  1908. for sub_name in sub_strs:
  1909. # print(sub_name)
  1910. sub_ts = pd.read_csv(sub_name, header=None)
  1911. subcort_path = sub_name.replace('_schaefer%s' % n_rois, 'subcortical38')
  1912. subcort = pd.read_csv(subcort_path, header=None)
  1913. claustrum_path = sub_name.replace('_schaefer%s' % n_rois, 'claustrum')
  1914. claustrum = pd.read_csv(claustrum_path, header=None)
  1915. tmp = clean(
  1916. signals=claustrum.iloc[:, [0, 3]].to_numpy(),
  1917. confounds=claustrum.iloc[:, [1, 2, 4, 5]].to_numpy(),
  1918. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  1919. claustrum.iloc[:, [0, 3]] = tmp
  1920. cerebellum_path = sub_name.replace('_schaefer%s' % n_rois, 'cerebellum')
  1921. cerebellum = pd.read_csv(cerebellum_path, header=None)
  1922. sub_ts = pd.concat([sub_ts, subcort, claustrum, cerebellum], axis=1)
  1923. assert sub_ts.shape[1] == 161
  1924. sub_ts_z = pd.DataFrame(StandardScaler().fit_transform(sub_ts), columns=full_labels)
  1925. cur_cond = 'plcb' if 'ses-plcb' in sub_name else 'LSD'
  1926. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_run-01_desc-confounds_timeseries.tsv'
  1927. conf_j_path = conf_t_path.replace('.tsv', '.json')
  1928. conf = get_my_confounds_df(conf_t_path, conf_j_path, strategy)
  1929. # motion correction
  1930. df = pd.read_csv(conf_t_path, delimiter='\t')
  1931. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  1932. if sub_motion_frac > 0.15:
  1933. print('Skipping subject: %s' % sub_name)
  1934. n_skipped += 1
  1935. continue
  1936. # subcort_path = conf_path = sub_name.split('_schaefer100_TS')[0] + 'subcortical38_TS_noDenosing.csv'
  1937. # subcort = pd.read_csv(subcort_path)
  1938. if len(conf) != 0:
  1939. sub_ts_z_deconf = clean(
  1940. signals=np.nan_to_num(sub_ts_z.values), standardize=False, confounds=np.nan_to_num(conf))
  1941. # signals=np.nan_to_num(sub_ts_z.values), standardize=False, np.nan_to_num(confounds=conf.iloc[:len(sub_ts_z)]))
  1942. else:
  1943. continue
  1944. # print(f'{sub_name} has {len(conf.columns)} columns to noise clean!')
  1945. # sub_ts_z_deconf = pd.DataFrame(
  1946. # sub_ts_z_deconf, columns=cort_labels)
  1947. # sub_CC = np.corrcoef(sub_ts_z_deconf.T)
  1948. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf.T))
  1949. study_id_all.append(7)
  1950. CCs.append(sub_CC)
  1951. conds.append(int(cur_cond == 'LSD'))
  1952. FDs_all.append(df.framewise_displacement.mean())
  1953. CCs_all.append(sub_CC)
  1954. conds_all.append(int(cur_cond == 'LSD'))
  1955. drug_all.append(1)
  1956. CCs = np.array(CCs)
  1957. conds = np.array(conds)
  1958. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/BaselLSD_coverage.nii.gz')
  1959. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  1960. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  1961. import matplotlib.pylab as plt
  1962. plt.figure(figsize=(16, 10))
  1963. sns.set(font_scale=0.4)
  1964. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1965. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1966. plt.tight_layout()
  1967. plt.savefig('_results_uncorrected_data_pipelines_ana8/BaselLSD_avg_CC_plcb_%s.pdf' % strategy_suffix)
  1968. import matplotlib.pylab as plt
  1969. plt.figure(figsize=(16, 10))
  1970. sns.set(font_scale=0.4)
  1971. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1972. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1973. plt.tight_layout()
  1974. plt.savefig('_results_uncorrected_data_pipelines_ana8/BaselLSD_avg_CC_drug_%s.pdf' % strategy_suffix)
  1975. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  1976. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  1977. # import matplotlib.pylab as plt
  1978. # plt.figure(figsize=(16, 10))
  1979. # sns.set(font_scale=0.4)
  1980. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1981. # center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1982. # plt.tight_layout()
  1983. # plt.savefig('_results_uncorrected/BaselLSD_avg_CC_plcb_max.pdf')
  1984. # import matplotlib.pylab as plt
  1985. # plt.figure(figsize=(16, 10))
  1986. # sns.set(font_scale=0.4)
  1987. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1988. # center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  1989. # plt.tight_layout()
  1990. # plt.savefig('_results_uncorrected/BaselLSD_avg_CC_drug_max.pdf')
  1991. import matplotlib.pylab as plt
  1992. plt.figure(figsize=(16, 10))
  1993. sns.set(font_scale=0.4)
  1994. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  1995. center=0, xticklabels=full_labels, yticklabels=full_labels)
  1996. plt.tight_layout()
  1997. plt.savefig('_results_uncorrected_data_pipelines_ana8/BaselLSD_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  1998. from sklearn.linear_model import LinearRegression
  1999. out_mat = np.zeros((161, 161))
  2000. CCs = np.nan_to_num(CCs)
  2001. for i_roi in range(161):
  2002. for j_roi in range(161):
  2003. if i_roi == j_roi:
  2004. continue
  2005. lr = LinearRegression(fit_intercept=True)
  2006. y = CCs[:, i_roi, j_roi]
  2007. X = conds[:, None]
  2008. lr.fit(X, y)
  2009. out_mat[i_roi, j_roi] = lr.coef_[0]
  2010. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  2011. import matplotlib.pylab as plt
  2012. plt.figure(figsize=(20, 14))
  2013. sns.set(font_scale=0.4)
  2014. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2015. center=0)
  2016. plt.tight_layout()
  2017. # plt.savefig('_results_uncorrected/BaselLSD_lrcoef.pdf')
  2018. plt.savefig('_results_uncorrected_data_pipelines_ana8/BaselLSD_avg_lrcoef_%s.pdf' % strategy_suffix)
  2019. # import matplotlib.pylab as plt
  2020. # plt.figure(figsize=(20, 14))
  2021. # sns.set(font_scale=0.4)
  2022. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  2023. # center=0, vmax=.35)
  2024. # plt.tight_layout()
  2025. # plt.savefig('_results_uncorrected/BaselLSD_lrcoef_viridis.pdf')
  2026. cum_intra_net = np.zeros((17))
  2027. cum_intra_net_cnt = np.zeros((17))
  2028. cum_inter_net = np.zeros((17))
  2029. cum_inter_net_cnt = np.zeros((17))
  2030. for i in range(n_rois): # rows
  2031. for j in range(n_rois): # columns
  2032. if i==j: # skip connections to self
  2033. continue
  2034. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  2035. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  2036. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  2037. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  2038. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  2039. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  2040. # ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2041. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  2042. # plt.title('Intra-network drug effects', fontsize=12)
  2043. # plt.tight_layout()
  2044. # plt.savefig('_results_uncorrected/BaselLSD_cumabs_intra.pdf')
  2045. # ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2046. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  2047. # plt.title('Inter-network drug effects', fontsize=12)
  2048. # plt.tight_layout()
  2049. # plt.savefig('_results_uncorrected/BaselLSD_cumabs_inter.pdf')
  2050. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  2051. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2052. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2053. # plt.title('Intra-network drug effects', fontsize=12)
  2054. # plt.tight_layout()
  2055. # plt.savefig('_results_uncorrected/BaselLSD_cumabs_intra_norm.pdf')
  2056. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  2057. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2058. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2059. # plt.title('Inter-network drug effects', fontsize=12)
  2060. # plt.tight_layout()
  2061. # plt.savefig('_results_uncorrected/BaselLSD_cumabs_inter_norm.pdf')
  2062. ax = pd.DataFrame(cum_intra_net,
  2063. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2064. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2065. plt.title('Intra-network drug effects', fontsize=12)
  2066. plt.tight_layout()
  2067. plt.savefig('_results_uncorrected_data_pipelines_ana8/BaselLSD_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  2068. ax = pd.DataFrame(cum_inter_net,
  2069. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2070. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2071. plt.title('Inter-network drug effects', fontsize=12)
  2072. plt.tight_layout()
  2073. plt.savefig('_results_uncorrected_data_pipelines_ana8/BaselLSD_cumabs_inter_regnorm_%s.pdf' % strategy_suffix)
  2074. # # no abs
  2075. # cum_intra_net = np.zeros((17))
  2076. # cum_intra_net_cnt = np.zeros((17))
  2077. # cum_inter_net = np.zeros((17))
  2078. # cum_inter_net_cnt = np.zeros((17))
  2079. # for i in range(n_rois): # rows
  2080. # for j in range(n_rois): # columns
  2081. # if i==j: # skip connections to self
  2082. # continue
  2083. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  2084. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  2085. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  2086. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  2087. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  2088. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  2089. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  2090. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2091. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  2092. # plt.title('Intra-network drug effects', fontsize=12)
  2093. # plt.tight_layout()
  2094. # plt.savefig('_results_uncorrected/BaselLSD_cumabs_intra_regnorm_noabs.pdf')
  2095. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  2096. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2097. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  2098. # plt.title('Inter-network drug effects', fontsize=12)
  2099. # plt.tight_layout()
  2100. # plt.savefig('_results_uncorrected/BaselLSD_cumabs_inter_regnorm_noabs.pdf')
  2101. # Basel LSD/Mesc/Psi data: 34 subs, 4 conds - LSD arm !!!
  2102. import os
  2103. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Basel_LSD_Mescaline_Psilocybin/*/sub-*/*/func/sub-*_schaefer100_TS_noDenosing.csv')
  2104. # QC: FD + dvars
  2105. study_FDs = []
  2106. study_dvars = []
  2107. for sub_name in sub_strs:
  2108. cur_cond = 'plcb'
  2109. if 'ses-LSD' in sub_name:
  2110. cur_cond = 'lsd'
  2111. elif 'ses-mesc' in sub_name:
  2112. cur_cond = 'mesc'
  2113. elif 'ses-psil' in sub_name:
  2114. cur_cond = 'psil'
  2115. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_run-01_desc-confounds_timeseries.tsv'
  2116. print(sub_name.split('/')[-4])
  2117. df = pd.read_csv(conf_t_path, delimiter='\t')
  2118. cur_fd = (df.framewise_displacement > 0.5).sum()
  2119. study_FDs.append(cur_fd)
  2120. print(cur_fd)
  2121. cur_dvars = df.dvars.mean()
  2122. study_dvars.append(cur_dvars)
  2123. print(cur_dvars)
  2124. plt.figure()
  2125. plt.hist(study_FDs, bins=20)
  2126. # plt.title('FD (#volumes > 0.5mm): Basel4cond')
  2127. plt.title('FD (#volumes > 0.5mm out of %i total): Basel4cond' % len(df.framewise_displacement))
  2128. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Basel4cond_FDabove0.5mm.png', dpi=300)
  2129. plt.figure()
  2130. plt.hist(np.array(study_FDs) / len(df.framewise_displacement), bins=20)
  2131. plt.title('FD (fraction of volumes > 0.5mm out of %i total): Basel4cond' % len(df.framewise_displacement))
  2132. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Basel4cond_fracFDabove0.5mm.png', dpi=600)
  2133. plt.figure()
  2134. plt.hist(study_dvars, bins=20)
  2135. plt.title('DVARS (mean across TS): Basel4cond')
  2136. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Basel4cond_dvars.png', dpi=300)
  2137. CCs = []
  2138. n_skipped = 0
  2139. conds = []
  2140. for sub_name in sub_strs:
  2141. # print(sub_name)
  2142. sub_ts = pd.read_csv(sub_name, header=None)
  2143. subcort_path = sub_name.replace('_schaefer%s' % n_rois, 'subcortical38')
  2144. subcort = pd.read_csv(subcort_path, header=None)
  2145. claustrum_path = sub_name.replace('_schaefer%s' % n_rois, 'claustrum')
  2146. claustrum = pd.read_csv(claustrum_path, header=None)
  2147. tmp = clean(
  2148. signals=claustrum.iloc[:, [0, 3]].to_numpy(),
  2149. confounds=claustrum.iloc[:, [1, 2, 4, 5]].to_numpy(),
  2150. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  2151. claustrum.iloc[:, [0, 3]] = tmp
  2152. cerebellum_path = sub_name.replace('_schaefer%s' % n_rois, 'cerebellum')
  2153. cerebellum = pd.read_csv(cerebellum_path, header=None)
  2154. sub_ts = pd.concat([sub_ts, subcort, claustrum, cerebellum], axis=1)
  2155. assert sub_ts.shape[1] == 161
  2156. sub_ts_z = pd.DataFrame(StandardScaler().fit_transform(sub_ts), columns=full_labels)
  2157. cur_cond = 0
  2158. if 'ses-LSD' in sub_name:
  2159. cur_cond = 1
  2160. elif 'ses-mesc' in sub_name:
  2161. continue # see below
  2162. elif 'ses-psil' in sub_name:
  2163. continue # see below
  2164. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_run-01_desc-confounds_timeseries.tsv'
  2165. conf_j_path = conf_t_path.replace('.tsv', '.json')
  2166. conf = get_my_confounds_df(conf_t_path, conf_j_path, strategy)
  2167. # motion correction
  2168. df = pd.read_csv(conf_t_path, delimiter='\t')
  2169. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  2170. if sub_motion_frac > 0.15:
  2171. print('Skipping subject: %s' % sub_name)
  2172. n_skipped += 1
  2173. continue
  2174. # subcort_path = conf_path = sub_name.split('_schaefer100_TS')[0] + 'subcortical38_TS_noDenosing.csv'
  2175. # subcort = pd.read_csv(subcort_path)
  2176. if len(conf) != 0:
  2177. sub_ts_z_deconf = clean(
  2178. signals=np.nan_to_num(sub_ts_z.values), standardize=False, confounds=np.nan_to_num(conf))
  2179. # signals=np.nan_to_num(sub_ts_z.values), standardize=False, np.nan_to_num(confounds=conf.iloc[:len(sub_ts_z)]))
  2180. else:
  2181. continue
  2182. # print(f'{sub_name} has {len(conf.columns)} columns to noise clean!')
  2183. # sub_ts_z_deconf = pd.DataFrame(
  2184. # sub_ts_z_deconf, columns=cort_labels)
  2185. # sub_CC = np.corrcoef(sub_ts_z_deconf.T)
  2186. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf.T))
  2187. study_id_all.append(8)
  2188. CCs.append(sub_CC)
  2189. conds.append(int(cur_cond))
  2190. FDs_all.append(df.framewise_displacement.mean())
  2191. CCs_all.append(sub_CC)
  2192. conds_all.append(int(cur_cond))
  2193. drug_all.append(1) # 0=psyloc (blue); 1=LSD (orange); 2=Aya (green)
  2194. CCs = np.array(CCs)
  2195. conds = np.array(conds)
  2196. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/Basel4condLSD_coverage.nii.gz')
  2197. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  2198. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  2199. import matplotlib.pylab as plt
  2200. plt.figure(figsize=(16, 10))
  2201. sns.set(font_scale=0.4)
  2202. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2203. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2204. plt.tight_layout()
  2205. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condLSD_avg_CC_plcb_%s.pdf' % strategy_suffix)
  2206. import matplotlib.pylab as plt
  2207. plt.figure(figsize=(16, 10))
  2208. sns.set(font_scale=0.4)
  2209. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2210. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2211. plt.tight_layout()
  2212. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condLSD_avg_CC_drug_%s.pdf' % strategy_suffix)
  2213. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  2214. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  2215. # import matplotlib.pylab as plt
  2216. # plt.figure(figsize=(16, 10))
  2217. # sns.set(font_scale=0.4)
  2218. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2219. # center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2220. # plt.tight_layout()
  2221. # plt.savefig('_results_uncorrected/Basel4condLSD_avg_CC_plcb_max.pdf')
  2222. # import matplotlib.pylab as plt
  2223. # plt.figure(figsize=(16, 10))
  2224. # sns.set(font_scale=0.4)
  2225. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2226. # center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2227. # plt.tight_layout()
  2228. # plt.savefig('_results_uncorrected/Basel4condLSD_avg_CC_drug_max.pdf')
  2229. import matplotlib.pylab as plt
  2230. plt.figure(figsize=(16, 10))
  2231. sns.set(font_scale=0.4)
  2232. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2233. center=0, xticklabels=full_labels, yticklabels=full_labels)
  2234. plt.tight_layout()
  2235. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condLSD_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  2236. from sklearn.linear_model import LinearRegression
  2237. out_mat = np.zeros((161, 161))
  2238. CCs = np.nan_to_num(CCs)
  2239. for i_roi in range(161):
  2240. for j_roi in range(161):
  2241. if i_roi == j_roi:
  2242. continue
  2243. lr = LinearRegression(fit_intercept=True)
  2244. y = CCs[:, i_roi, j_roi]
  2245. X = conds[:, None]
  2246. lr.fit(X, y)
  2247. out_mat[i_roi, j_roi] = lr.coef_[0]
  2248. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  2249. import matplotlib.pylab as plt
  2250. plt.figure(figsize=(20, 14))
  2251. sns.set(font_scale=0.4)
  2252. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2253. center=0)
  2254. plt.tight_layout()
  2255. # plt.savefig('_results_uncorrected/Basel4condLSD_lrcoef.pdf')
  2256. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condLSD_avg_lrcoef_%s.pdf' % strategy_suffix)
  2257. # import matplotlib.pylab as plt
  2258. # plt.figure(figsize=(20, 14))
  2259. # sns.set(font_scale=0.4)
  2260. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  2261. # center=0, vmax=.35)
  2262. # plt.tight_layout()
  2263. # plt.savefig('_results_uncorrected/Basel4condLSD_lrcoef_viridis.pdf')
  2264. cum_intra_net = np.zeros((17))
  2265. cum_intra_net_cnt = np.zeros((17))
  2266. cum_inter_net = np.zeros((17))
  2267. cum_inter_net_cnt = np.zeros((17))
  2268. for i in range(n_rois): # rows
  2269. for j in range(n_rois): # columns
  2270. if i==j: # skip connections to self
  2271. continue
  2272. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  2273. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  2274. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  2275. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  2276. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  2277. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  2278. # ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2279. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  2280. # plt.title('Intra-network drug effects', fontsize=12)
  2281. # plt.tight_layout()
  2282. # plt.savefig('_results_uncorrected/Basel4condLSD_cumabs_intra.pdf')
  2283. # ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2284. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  2285. # plt.title('Inter-network drug effects', fontsize=12)
  2286. # plt.tight_layout()
  2287. # plt.savefig('_results_uncorrected/Basel4condLSD_cumabs_inter.pdf')
  2288. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  2289. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2290. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2291. # plt.title('Intra-network drug effects', fontsize=12)
  2292. # plt.tight_layout()
  2293. # plt.savefig('_results_uncorrected/Basel4condLSD_cumabs_intra_norm.pdf')
  2294. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  2295. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2296. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2297. # plt.title('Inter-network drug effects', fontsize=12)
  2298. # plt.tight_layout()
  2299. # plt.savefig('_results_uncorrected/Basel4condLSD_cumabs_inter_norm.pdf')
  2300. ax = pd.DataFrame(cum_intra_net,
  2301. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2302. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2303. plt.title('Intra-network drug effects', fontsize=12)
  2304. plt.tight_layout()
  2305. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condLSD_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  2306. ax = pd.DataFrame(cum_inter_net,
  2307. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2308. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2309. plt.title('Inter-network drug effects', fontsize=12)
  2310. plt.tight_layout()
  2311. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condLSD_cumabs_inter_regnorm_%s.pdf' % strategy_suffix)
  2312. # # no abs
  2313. # cum_intra_net = np.zeros((17))
  2314. # cum_intra_net_cnt = np.zeros((17))
  2315. # cum_inter_net = np.zeros((17))
  2316. # cum_inter_net_cnt = np.zeros((17))
  2317. # for i in range(n_rois): # rows
  2318. # for j in range(n_rois): # columns
  2319. # if i==j: # skip connections to self
  2320. # continue
  2321. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  2322. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  2323. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  2324. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  2325. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  2326. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  2327. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  2328. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2329. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  2330. # plt.title('Intra-network drug effects', fontsize=12)
  2331. # plt.tight_layout()
  2332. # plt.savefig('_results_uncorrected/Basel4condLSD_cumabs_intra_regnorm_noabs.pdf')
  2333. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  2334. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2335. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  2336. # plt.title('Inter-network drug effects', fontsize=12)
  2337. # plt.tight_layout()
  2338. # plt.savefig('_results_uncorrected/Basel4condLSD_cumabs_inter_regnorm_noabs.pdf')
  2339. # Basel LSD/Mesc/Psi data: 34 subs, 4 conds - Mesc arm !!!
  2340. import os
  2341. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Basel_LSD_Mescaline_Psilocybin/*/sub-*/*/func/sub-*_schaefer100_TS_noDenosing.csv')
  2342. CCs = []
  2343. n_skipped = 0
  2344. conds = []
  2345. for sub_name in sub_strs:
  2346. # print(sub_name)
  2347. sub_ts = pd.read_csv(sub_name, header=None)
  2348. subcort_path = sub_name.replace('_schaefer%s' % n_rois, 'subcortical38')
  2349. subcort = pd.read_csv(subcort_path, header=None)
  2350. claustrum_path = sub_name.replace('_schaefer%s' % n_rois, 'claustrum')
  2351. claustrum = pd.read_csv(claustrum_path, header=None)
  2352. tmp = clean(
  2353. signals=claustrum.iloc[:, [0, 3]].to_numpy(),
  2354. confounds=claustrum.iloc[:, [1, 2, 4, 5]].to_numpy(),
  2355. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  2356. claustrum.iloc[:, [0, 3]] = tmp
  2357. cerebellum_path = sub_name.replace('_schaefer%s' % n_rois, 'cerebellum')
  2358. cerebellum = pd.read_csv(cerebellum_path, header=None)
  2359. sub_ts = pd.concat([sub_ts, subcort, claustrum, cerebellum], axis=1)
  2360. assert sub_ts.shape[1] == 161
  2361. sub_ts_z = pd.DataFrame(StandardScaler().fit_transform(sub_ts), columns=full_labels)
  2362. cur_cond = 0
  2363. if 'ses-LSD' in sub_name:
  2364. continue
  2365. elif 'ses-mesc' in sub_name:
  2366. cur_cond = 1
  2367. elif 'ses-psil' in sub_name:
  2368. continue
  2369. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_run-01_desc-confounds_timeseries.tsv'
  2370. conf_j_path = conf_t_path.replace('.tsv', '.json')
  2371. conf = get_my_confounds_df(conf_t_path, conf_j_path, strategy)
  2372. # motion correction
  2373. df = pd.read_csv(conf_t_path, delimiter='\t')
  2374. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  2375. if sub_motion_frac > 0.15:
  2376. print('Skipping subject: %s' % sub_name)
  2377. n_skipped += 1
  2378. continue
  2379. # subcort_path = conf_path = sub_name.split('_schaefer100_TS')[0] + 'subcortical38_TS_noDenosing.csv'
  2380. # subcort = pd.read_csv(subcort_path)
  2381. if len(conf) != 0:
  2382. sub_ts_z_deconf = clean(
  2383. signals=np.nan_to_num(sub_ts_z.values), standardize=False, confounds=np.nan_to_num(conf))
  2384. # signals=np.nan_to_num(sub_ts_z.values), standardize=False, np.nan_to_num(confounds=conf.iloc[:len(sub_ts_z)]))
  2385. else:
  2386. continue
  2387. # print(f'{sub_name} has {len(conf.columns)} columns to noise clean!')
  2388. # sub_ts_z_deconf = pd.DataFrame(
  2389. # sub_ts_z_deconf, columns=cort_labels)
  2390. # # stop
  2391. # sub_CC = np.corrcoef(sub_ts_z_deconf.T)
  2392. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf.T))
  2393. study_id_all.append(9)
  2394. CCs.append(sub_CC)
  2395. conds.append(int(cur_cond))
  2396. FDs_all.append(df.framewise_displacement.mean())
  2397. CCs_all.append(sub_CC)
  2398. conds_all.append(int(cur_cond))
  2399. drug_all.append(3) # 0=psyloc (blue); 1=LSD (orange); 2=Aya (green); 3=Mesc
  2400. CCs = np.array(CCs)
  2401. conds = np.array(conds)
  2402. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/Basel4condmesc_coverage.nii.gz')
  2403. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  2404. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  2405. import matplotlib.pylab as plt
  2406. plt.figure(figsize=(16, 10))
  2407. sns.set(font_scale=0.4)
  2408. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2409. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2410. plt.tight_layout()
  2411. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condmesc_avg_CC_plcb_%s.pdf' % strategy_suffix)
  2412. import matplotlib.pylab as plt
  2413. plt.figure(figsize=(16, 10))
  2414. sns.set(font_scale=0.4)
  2415. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2416. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2417. plt.tight_layout()
  2418. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condmesc_avg_CC_drug_%s.pdf' % strategy_suffix)
  2419. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  2420. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  2421. # import matplotlib.pylab as plt
  2422. # plt.figure(figsize=(16, 10))
  2423. # sns.set(font_scale=0.4)
  2424. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2425. # center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2426. # plt.tight_layout()
  2427. # plt.savefig('_results_uncorrected/Basel4condmesc_avg_CC_plcb_max.pdf')
  2428. # import matplotlib.pylab as plt
  2429. # plt.figure(figsize=(16, 10))
  2430. # sns.set(font_scale=0.4)
  2431. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2432. # center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2433. # plt.tight_layout()
  2434. # plt.savefig('_results_uncorrected/Basel4condmesc_avg_CC_drug_max.pdf')
  2435. import matplotlib.pylab as plt
  2436. plt.figure(figsize=(16, 10))
  2437. sns.set(font_scale=0.4)
  2438. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2439. center=0, xticklabels=cort_labels, yticklabels=cort_labels)
  2440. plt.tight_layout()
  2441. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condmesc_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  2442. from sklearn.linear_model import LinearRegression
  2443. out_mat = np.zeros((161, 161))
  2444. CCs = np.nan_to_num(CCs)
  2445. for i_roi in range(161):
  2446. for j_roi in range(161):
  2447. if i_roi == j_roi:
  2448. continue
  2449. lr = LinearRegression(fit_intercept=True)
  2450. y = CCs[:, i_roi, j_roi]
  2451. X = conds[:, None]
  2452. lr.fit(X, y)
  2453. out_mat[i_roi, j_roi] = lr.coef_[0]
  2454. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  2455. import matplotlib.pylab as plt
  2456. plt.figure(figsize=(20, 14))
  2457. sns.set(font_scale=0.4)
  2458. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2459. center=0)
  2460. plt.tight_layout()
  2461. # plt.savefig('_results_uncorrected/Basel4condmesc_lrcoef.pdf')
  2462. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condmesc_avg_lrcoef_%s.pdf' % strategy_suffix)
  2463. # import matplotlib.pylab as plt
  2464. # plt.figure(figsize=(20, 14))
  2465. # sns.set(font_scale=0.4)
  2466. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  2467. # center=0, vmax=.35)
  2468. # plt.tight_layout()
  2469. # plt.savefig('_results_uncorrected/Basel4condmesc_lrcoef_viridis.pdf')
  2470. cum_intra_net = np.zeros((17))
  2471. cum_intra_net_cnt = np.zeros((17))
  2472. cum_inter_net = np.zeros((17))
  2473. cum_inter_net_cnt = np.zeros((17))
  2474. for i in range(n_rois): # rows
  2475. for j in range(n_rois): # columns
  2476. if i==j: # skip connections to self
  2477. continue
  2478. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  2479. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  2480. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  2481. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  2482. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  2483. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  2484. # ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2485. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  2486. # plt.title('Intra-network drug effects', fontsize=12)
  2487. # plt.tight_layout()
  2488. # plt.savefig('_results_uncorrected/Basel4condmesc_cumabs_intra.pdf')
  2489. # ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2490. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  2491. # plt.title('Inter-network drug effects', fontsize=12)
  2492. # plt.tight_layout()
  2493. # plt.savefig('_results_uncorrected/Basel4condmesc_cumabs_inter.pdf')
  2494. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  2495. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2496. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2497. # plt.title('Intra-network drug effects', fontsize=12)
  2498. # plt.tight_layout()
  2499. # plt.savefig('_results_uncorrected/Basel4condmesc_cumabs_intra_norm.pdf')
  2500. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  2501. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2502. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2503. # plt.title('Inter-network drug effects', fontsize=12)
  2504. # plt.tight_layout()
  2505. # plt.savefig('_results_uncorrected/Basel4condmesc_cumabs_inter_norm.pdf')
  2506. ax = pd.DataFrame(cum_intra_net,
  2507. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2508. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2509. plt.title('Intra-network drug effects', fontsize=12)
  2510. plt.tight_layout()
  2511. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condmesc_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  2512. ax = pd.DataFrame(cum_inter_net,
  2513. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2514. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2515. plt.title('Inter-network drug effects', fontsize=12)
  2516. plt.tight_layout()
  2517. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condmesc_cumabs_inter_regnorm_%s.pdf' % strategy_suffix)
  2518. # # no abs
  2519. # cum_intra_net = np.zeros((17))
  2520. # cum_intra_net_cnt = np.zeros((17))
  2521. # cum_inter_net = np.zeros((17))
  2522. # cum_inter_net_cnt = np.zeros((17))
  2523. # for i in range(n_rois): # rows
  2524. # for j in range(n_rois): # columns
  2525. # if i==j: # skip connections to self
  2526. # continue
  2527. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  2528. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  2529. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  2530. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  2531. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  2532. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  2533. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  2534. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2535. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  2536. # plt.title('Intra-network drug effects', fontsize=12)
  2537. # plt.tight_layout()
  2538. # plt.savefig('_results_uncorrected/Basel4condmesc_cumabs_intra_regnorm_noabs.pdf')
  2539. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  2540. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2541. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  2542. # plt.title('Inter-network drug effects', fontsize=12)
  2543. # plt.tight_layout()
  2544. # plt.savefig('_results_uncorrected/Basel4condmesc_cumabs_inter_regnorm_noabs.pdf')
  2545. # Basel LSD/Mesc/Psi data: 34 subs, 4 conds - psilocybin arm !!!
  2546. import os
  2547. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Basel_LSD_Mescaline_Psilocybin/*/sub-*/*/func/sub-*_schaefer100_TS_noDenosing.csv')
  2548. CCs = []
  2549. n_skipped = 0
  2550. conds = []
  2551. for sub_name in sub_strs:
  2552. # print(sub_name)
  2553. sub_ts = pd.read_csv(sub_name, header=None)
  2554. subcort_path = sub_name.replace('_schaefer%s' % n_rois, 'subcortical38')
  2555. subcort = pd.read_csv(subcort_path, header=None)
  2556. claustrum_path = sub_name.replace('_schaefer%s' % n_rois, 'claustrum')
  2557. claustrum = pd.read_csv(claustrum_path, header=None)
  2558. tmp = clean(
  2559. signals=claustrum.iloc[:, [0, 3]].to_numpy(),
  2560. confounds=claustrum.iloc[:, [1, 2, 4, 5]].to_numpy(),
  2561. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  2562. claustrum.iloc[:, [0, 3]] = tmp
  2563. cerebellum_path = sub_name.replace('_schaefer%s' % n_rois, 'cerebellum')
  2564. cerebellum = pd.read_csv(cerebellum_path, header=None)
  2565. sub_ts = pd.concat([sub_ts, subcort, claustrum, cerebellum], axis=1)
  2566. assert sub_ts.shape[1] == 161
  2567. sub_ts_z = pd.DataFrame(StandardScaler().fit_transform(sub_ts), columns=full_labels)
  2568. cur_cond = 0
  2569. if 'ses-LSD' in sub_name:
  2570. continue
  2571. elif 'ses-mesc' in sub_name:
  2572. continue
  2573. elif 'ses-psil' in sub_name:
  2574. cur_cond = 1
  2575. conf_t_path = sub_name.split('_schaefer100_TS')[0] + '_task-rest_run-01_desc-confounds_timeseries.tsv'
  2576. conf_j_path = conf_t_path.replace('.tsv', '.json')
  2577. conf = get_my_confounds_df(conf_t_path, conf_j_path, strategy)
  2578. # motion correction
  2579. df = pd.read_csv(conf_t_path, delimiter='\t')
  2580. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  2581. if sub_motion_frac > 0.15:
  2582. print('Skipping subject: %s' % sub_name)
  2583. n_skipped += 1
  2584. continue
  2585. # subcort_path = conf_path = sub_name.split('_schaefer100_TS')[0] + 'subcortical38_TS_noDenosing.csv'
  2586. # subcort = pd.read_csv(subcort_path)
  2587. if len(conf) != 0:
  2588. sub_ts_z_deconf = clean(
  2589. signals=np.nan_to_num(sub_ts_z.values), standardize=False, confounds=np.nan_to_num(conf))
  2590. # signals=np.nan_to_num(sub_ts_z.values), standardize=False, np.nan_to_num(confounds=conf.iloc[:len(sub_ts_z)]))
  2591. else:
  2592. continue
  2593. # print(f'{sub_name} has {len(conf.columns)} columns to noise clean!')
  2594. # sub_ts_z_deconf = pd.DataFrame(
  2595. # sub_ts_z_deconf, columns=cort_labels)
  2596. # # stop
  2597. # sub_CC = np.corrcoef(sub_ts_z_deconf.T)
  2598. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf.T))
  2599. study_id_all.append(10)
  2600. CCs.append(sub_CC)
  2601. conds.append(int(cur_cond))
  2602. FDs_all.append(df.framewise_displacement.mean())
  2603. CCs_all.append(sub_CC)
  2604. conds_all.append(int(cur_cond))
  2605. drug_all.append(0) # 0=psyloc (blue); 1=LSD (orange); 2=Aya (green); 3=Mesc
  2606. CCs = np.array(CCs)
  2607. conds = np.array(conds)
  2608. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/Basel4condpsil_coverage.nii.gz')
  2609. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  2610. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  2611. import matplotlib.pylab as plt
  2612. plt.figure(figsize=(16, 10))
  2613. sns.set(font_scale=0.4)
  2614. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2615. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2616. plt.tight_layout()
  2617. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condpsil_avg_CC_plcb_%s.pdf' % strategy_suffix)
  2618. import matplotlib.pylab as plt
  2619. plt.figure(figsize=(16, 10))
  2620. sns.set(font_scale=0.4)
  2621. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2622. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2623. plt.tight_layout()
  2624. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condpsil_avg_CC_drug_%s.pdf' % strategy_suffix)
  2625. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  2626. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  2627. # import matplotlib.pylab as plt
  2628. # plt.figure(figsize=(16, 10))
  2629. # sns.set(font_scale=0.4)
  2630. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2631. # center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2632. # plt.tight_layout()
  2633. # plt.savefig('_results_uncorrected/Basel4condpsil_avg_CC_plcb_max.pdf')
  2634. # import matplotlib.pylab as plt
  2635. # plt.figure(figsize=(16, 10))
  2636. # sns.set(font_scale=0.4)
  2637. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2638. # center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2639. # plt.tight_layout()
  2640. # plt.savefig('_results_uncorrected/Basel4condpsil_avg_CC_drug_max.pdf')
  2641. import matplotlib.pylab as plt
  2642. plt.figure(figsize=(16, 10))
  2643. sns.set(font_scale=0.4)
  2644. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2645. center=0, xticklabels=full_labels, yticklabels=full_labels)
  2646. plt.tight_layout()
  2647. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condpsil_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  2648. from sklearn.linear_model import LinearRegression
  2649. out_mat = np.zeros((161, 161))
  2650. CCs = np.nan_to_num(CCs)
  2651. for i_roi in range(161):
  2652. for j_roi in range(161):
  2653. if i_roi == j_roi:
  2654. continue
  2655. lr = LinearRegression(fit_intercept=True)
  2656. y = CCs[:, i_roi, j_roi]
  2657. X = conds[:, None]
  2658. lr.fit(X, y)
  2659. out_mat[i_roi, j_roi] = lr.coef_[0]
  2660. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  2661. import matplotlib.pylab as plt
  2662. plt.figure(figsize=(20, 14))
  2663. sns.set(font_scale=0.4)
  2664. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2665. center=0)
  2666. plt.tight_layout()
  2667. # plt.savefig('_results_uncorrected/Basel4condpsil_lrcoef.pdf')
  2668. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condpsil_avg_lrcoef_%s.pdf' % strategy_suffix)
  2669. # import matplotlib.pylab as plt
  2670. # plt.figure(figsize=(20, 14))
  2671. # sns.set(font_scale=0.4)
  2672. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  2673. # center=0, vmax=.35)
  2674. # plt.tight_layout()
  2675. # plt.savefig('_results_uncorrected/Basel4condpsil_lrcoef_viridis.pdf')
  2676. cum_intra_net = np.zeros((17))
  2677. cum_intra_net_cnt = np.zeros((17))
  2678. cum_inter_net = np.zeros((17))
  2679. cum_inter_net_cnt = np.zeros((17))
  2680. for i in range(n_rois): # rows
  2681. for j in range(n_rois): # columns
  2682. if i==j: # skip connections to self
  2683. continue
  2684. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  2685. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  2686. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  2687. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  2688. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  2689. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  2690. # ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2691. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  2692. # plt.title('Intra-network drug effects', fontsize=12)
  2693. # plt.tight_layout()
  2694. # plt.savefig('_results_uncorrected/Basel4condpsil_cumabs_intra.pdf')
  2695. # ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2696. # plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  2697. # plt.title('Inter-network drug effects', fontsize=12)
  2698. # plt.tight_layout()
  2699. # plt.savefig('_results_uncorrected/Basel4condpsil_cumabs_inter.pdf')
  2700. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  2701. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2702. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2703. # plt.title('Intra-network drug effects', fontsize=12)
  2704. # plt.tight_layout()
  2705. # plt.savefig('_results_uncorrected/Basel4condpsil_cumabs_intra_norm.pdf')
  2706. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  2707. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2708. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2709. # plt.title('Inter-network drug effects', fontsize=12)
  2710. # plt.tight_layout()
  2711. # plt.savefig('_results_uncorrected/Basel4condpsil_cumabs_inter_norm.pdf')
  2712. ax = pd.DataFrame(cum_intra_net,
  2713. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2714. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2715. plt.title('Intra-network drug effects', fontsize=12)
  2716. plt.tight_layout()
  2717. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condpsil_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  2718. ax = pd.DataFrame(cum_inter_net,
  2719. index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2720. plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2721. plt.title('Inter-network drug effects', fontsize=12)
  2722. plt.tight_layout()
  2723. plt.savefig('_results_uncorrected_data_pipelines_ana8/Basel4condpsil_cumabs_inter_regnorm_%s.pdf' % strategy_suffix)
  2724. # # no abs
  2725. # cum_intra_net = np.zeros((17))
  2726. # cum_intra_net_cnt = np.zeros((17))
  2727. # cum_inter_net = np.zeros((17))
  2728. # cum_inter_net_cnt = np.zeros((17))
  2729. # for i in range(n_rois): # rows
  2730. # for j in range(n_rois): # columns
  2731. # if i==j: # skip connections to self
  2732. # continue
  2733. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  2734. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  2735. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  2736. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  2737. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  2738. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  2739. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  2740. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2741. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  2742. # plt.title('Intra-network drug effects', fontsize=12)
  2743. # plt.tight_layout()
  2744. # plt.savefig('_results_uncorrected/Basel4condpsil_cumabs_intra_regnorm_noabs.pdf')
  2745. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  2746. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2747. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  2748. # plt.title('Inter-network drug effects', fontsize=12)
  2749. # plt.tight_layout()
  2750. # plt.savefig('_results_uncorrected/Basel4condpsil_cumabs_inter_regnorm_noabs.pdf')
  2751. # Timmerman data: DMT, 20-ish subjects
  2752. del out_df
  2753. # TODO: do the cross-corr in run1 and in run3 for a given subject first, then average the two
  2754. # to obtain a single cross-corr matrix for a given subject
  2755. # goal being to have one set of obsevation per subject (for lat statistical inference)
  2756. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Timmermann_DMT/sub-*/ses-*/func/sub-*_ses-*schaefer100_TS_noDenosing.csv')
  2757. # QC: FD + dvars
  2758. study_FDs = []
  2759. study_dvars = []
  2760. for sub_name in sub_strs:
  2761. cur_cond = 'PCB' if 'PCB' in sub_name else 'DMT'
  2762. conf_t_path = sub_name.split('_ses-')[0] + '_ses-%s_task-rest_run-1_desc-confounds_timeseries.tsv' % cur_cond
  2763. sub_name = sub_strs[0].split('/')[-4]
  2764. print(sub_name)
  2765. try:
  2766. df = pd.read_csv(conf_t_path, delimiter='\t')
  2767. except:
  2768. continue
  2769. cur_fd = (df.framewise_displacement > 0.5).sum()
  2770. study_FDs.append(cur_fd)
  2771. print(cur_fd)
  2772. cur_dvars = df.dvars.mean()
  2773. study_dvars.append(cur_dvars)
  2774. print(cur_dvars)
  2775. plt.figure()
  2776. plt.hist(study_FDs, bins=20)
  2777. # plt.title('FD (#volumes > 0.5mm): timmermann_DMT')
  2778. plt.title('FD (#volumes > 0.5mm out of %i total): timmermann_DMT' % len(df.framewise_displacement))
  2779. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_timmermann_DMT_FDabove0.5mm.png', dpi=600)
  2780. plt.figure()
  2781. plt.hist(np.array(study_FDs) / len(df.framewise_displacement), bins=20)
  2782. plt.title('FD (fraction of volumes > 0.5mm out of %i total): timmermann_DMT' % len(df.framewise_displacement))
  2783. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_timmermann_DMT_fracFDabove0.5mm.png', dpi=600)
  2784. plt.figure()
  2785. plt.hist(study_dvars, bins=20)
  2786. plt.title('DVARS (mean across TS): timmermann_DMT')
  2787. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_timmermann_DMT_dvars.png')
  2788. CCs = []
  2789. n_skipped = 0
  2790. conds = []
  2791. for sub_name in sub_strs:
  2792. print(sub_name)
  2793. sub_ts1 = pd.read_csv(sub_name, header=None)
  2794. subcort1_path = sub_name.replace('_schaefer%s' % n_rois, 'subcortical38')
  2795. subcort1 = pd.read_csv(subcort1_path, header=None)
  2796. claustrum1_path = sub_name.replace('_schaefer%s' % n_rois, 'claustrum')
  2797. claustrum1 = pd.read_csv(claustrum1_path, header=None)
  2798. tmp = clean(
  2799. signals=claustrum1.iloc[:, [0, 3]].to_numpy(),
  2800. confounds=claustrum1.iloc[:, [1, 2, 4, 5]].to_numpy(),
  2801. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  2802. claustrum1.iloc[:, [0, 3]] = tmp
  2803. cerebellum1_path = sub_name.replace('_schaefer%s' % n_rois, 'cerebellum')
  2804. cerebellum1 = pd.read_csv(cerebellum1_path, header=None)
  2805. sub_ts1 = pd.concat([sub_ts1, subcort1, claustrum1, cerebellum1], axis=1)
  2806. assert sub_ts1.shape[1] == 161
  2807. sub_ts_z1 = pd.DataFrame(StandardScaler().fit_transform(sub_ts1), columns=full_labels)
  2808. #print(sub_ts_z1)
  2809. cur_cond = 'PCB' if 'PCB' in sub_name else 'DMT'
  2810. conf_t_path1 = sub_name.split('_ses-')[0] + '_ses-%s_task-rest_run-1_desc-confounds_timeseries.tsv' % cur_cond
  2811. conf_j_path1 = conf_t_path.replace('.tsv', '.json')
  2812. # motion correction
  2813. df = pd.read_csv(conf_t_path1, delimiter='\t')
  2814. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  2815. if sub_motion_frac > 0.15:
  2816. print('Skipping subject: %s' % sub_name)
  2817. n_skipped += 1
  2818. continue
  2819. if not os.path.exists(conf_t_path1):
  2820. print('Skipping this subject: confound file not found!')
  2821. continue
  2822. conf1 = get_my_confounds_df(conf_t_path1, conf_j_path1, strategy)
  2823. if len(conf1) != 0:
  2824. conf1 = np.nan_to_num(conf1)
  2825. sub_ts_z_deconf1 = clean(
  2826. signals=sub_ts_z1.values, standardize=False, confounds=np.nan_to_num(conf1))
  2827. else:
  2828. continue
  2829. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf1.T))
  2830. # reg_avg_activity_bar.append(sub_ts.median(0).values)
  2831. # reg_avg_activity_bar_std.append(sub_ts.median(0).values)
  2832. #reg_avg_activity.append(sub_ts.mean(0).values)
  2833. study_id_all.append(11)
  2834. CCs.append(sub_CC)
  2835. conds.append(int(cur_cond == 'DMT'))
  2836. FDs_all.append(df.framewise_displacement.mean())
  2837. CCs_all.append(sub_CC)
  2838. conds_all.append(int(cur_cond == 'DMT'))
  2839. drug_all.append(4) # 0=psyloc (blue); 1=LSD (orange); 2=Aya (green); 3=Mesc; 4=DMT
  2840. CCs = np.array(CCs)
  2841. conds = np.array(conds)
  2842. masker.inverse_transform(sub_ts.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/timmermann_dmt_coverage.nii.gz')
  2843. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  2844. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  2845. import matplotlib.pylab as plt
  2846. plt.figure(figsize=(16, 10))
  2847. sns.set(font_scale=0.4)
  2848. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2849. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2850. plt.tight_layout()
  2851. plt.savefig('_results_uncorrected_data_pipelines_ana8/timmermann_dmt_avg_CC_plcb_%s.pdf' % strategy_suffix)
  2852. import matplotlib.pylab as plt
  2853. plt.figure(figsize=(16, 10))
  2854. sns.set(font_scale=0.4)
  2855. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2856. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  2857. plt.tight_layout()
  2858. plt.savefig('_results_uncorrected_data_pipelines_ana8/timmermann_dmt_avg_CC_drug_%s.pdf' % strategy_suffix)
  2859. import matplotlib.pylab as plt
  2860. plt.figure(figsize=(16, 10))
  2861. sns.set(font_scale=0.4)
  2862. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2863. center=0, xticklabels=full_labels, yticklabels=full_labels)
  2864. plt.tight_layout()
  2865. plt.savefig('_results_uncorrected_data_pipelines_ana8/timmermann_dmt_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  2866. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  2867. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  2868. # import matplotlib.pylab as plt
  2869. # plt.figure(figsize=(16, 10))
  2870. # sns.set(font_scale=0.4)
  2871. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2872. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  2873. # plt.tight_layout()
  2874. # plt.savefig('_results_uncorrected/Barrett_avg_CC_plcb_max.pdf')
  2875. # import matplotlib.pylab as plt
  2876. # plt.figure(figsize=(16, 10))
  2877. # sns.set(font_scale=0.4)
  2878. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2879. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  2880. # plt.tight_layout()
  2881. # plt.savefig('_results_uncorrected/Barrett_avg_CC_drug_max.pdf')
  2882. # import matplotlib.pylab as plt
  2883. # plt.figure(figsize=(16, 10))
  2884. # sns.set(font_scale=0.4)
  2885. # sns.heatmap(CC_avg_plcb - CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2886. # center=0, xticklabels=cort_labels, yticklabels=cort_labels)
  2887. # plt.tight_layout()
  2888. # plt.savefig('_results_uncorrected/Barrett_avg_CC_plcb-drug.pdf')
  2889. from sklearn.linear_model import LinearRegression
  2890. out_mat = np.zeros((161, 161))
  2891. CCs = np.nan_to_num(CCs)
  2892. for i_roi in range(161):
  2893. for j_roi in range(161):
  2894. if i_roi == j_roi:
  2895. continue
  2896. lr = LinearRegression(fit_intercept=True)
  2897. y = CCs[:, i_roi, j_roi]
  2898. #y = np.arctanh(CCs[:, i_roi, j_roi])
  2899. X = conds[:, None]
  2900. lr.fit(X, y)
  2901. out_mat[i_roi, j_roi] = lr.coef_[0]
  2902. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  2903. import matplotlib.pylab as plt
  2904. plt.figure(figsize=(20, 14))
  2905. sns.set(font_scale=0.4)
  2906. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  2907. center=0)
  2908. plt.tight_layout()
  2909. # plt.savefig('_results_uncorrected/barret_lrcoef.pdf')
  2910. plt.savefig('_results_uncorrected_data_pipelines_ana8/timmermann_dmt_avg_lrcoef_%s.pdf' % strategy_suffix)
  2911. # import matplotlib.pylab as plt
  2912. # plt.figure(figsize=(20, 14))
  2913. # sns.set(font_scale=0.4)
  2914. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  2915. # center=0, vmax=.35)
  2916. # plt.tight_layout()
  2917. # plt.savefig('_results_uncorrected/barret_lrcoef_viridis.pdf')
  2918. cum_intra_net = np.zeros((17))
  2919. cum_intra_net_cnt = np.zeros((17))
  2920. cum_inter_net = np.zeros((17))
  2921. cum_inter_net_cnt = np.zeros((17))
  2922. for i in range(n_rois): # rows
  2923. for j in range(n_rois): # columns
  2924. if i==j: # skip connections to self
  2925. continue
  2926. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  2927. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  2928. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  2929. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  2930. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  2931. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  2932. ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2933. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  2934. plt.title('Intra-network drug effects', fontsize=12)
  2935. plt.tight_layout()
  2936. # plt.savefig('_results_uncorrected/barrett_cumabs_intra.pdf')
  2937. plt.savefig('_results_uncorrected_data_pipelines_ana8/timmermann_dmt_avg_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  2938. ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2939. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  2940. plt.title('Inter-network drug effects', fontsize=12)
  2941. plt.tight_layout()
  2942. # plt.savefig('_results_uncorrected/barrett_cumabs_inter.pdf')
  2943. plt.savefig('_results_uncorrected_data_pipelines_ana8/timmermann_dmt_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  2944. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  2945. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2946. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2947. # plt.title('Intra-network drug effects', fontsize=12)
  2948. # plt.tight_layout()
  2949. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_norm.pdf')
  2950. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  2951. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2952. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2953. # plt.title('Inter-network drug effects', fontsize=12)
  2954. # plt.tight_layout()
  2955. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_norm.pdf')
  2956. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  2957. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2958. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2959. # plt.title('Intra-network drug effects', fontsize=12)
  2960. # plt.tight_layout()
  2961. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_regnorm.pdf')
  2962. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  2963. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2964. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  2965. # plt.title('Inter-network drug effects', fontsize=12)
  2966. # plt.tight_layout()
  2967. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_regnorm.pdf')
  2968. # # no abs
  2969. # cum_intra_net = np.zeros((17))
  2970. # cum_intra_net_cnt = np.zeros((17))
  2971. # cum_inter_net = np.zeros((17))
  2972. # cum_inter_net_cnt = np.zeros((17))
  2973. # for i in range(n_rois): # rows
  2974. # for j in range(n_rois): # columns
  2975. # if i==j: # skip connections to self
  2976. # continue
  2977. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  2978. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  2979. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  2980. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  2981. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  2982. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  2983. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  2984. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2985. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  2986. # plt.title('Intra-network drug effects', fontsize=12)
  2987. # plt.tight_layout()
  2988. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_regnorm_noabs.pdf')
  2989. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  2990. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  2991. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  2992. # plt.title('Inter-network drug effects', fontsize=12)
  2993. # plt.tight_layout()
  2994. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_regnorm_noabs.pdf')
  2995. # Siegel data: 6 subjects
  2996. del out_df
  2997. # TODO: do the cross-corr in run1 and in run3 for a given subject first, then average the two
  2998. # to obtain a single cross-corr matrix for a given subject
  2999. # goal being to have one set of obsevation per subject (for lat statistical inference)
  3000. sub_strs = glob.glob('/Users/danilo/f/project_METAPSYCHO_BOLDpsychCONS/_data_uncorrected_fullcolumns/Siegel/sub-*_ses-*_schaefer100_TS_noDenosing.csv')
  3001. # QC: FD + dvars
  3002. study_FDs = []
  3003. study_dvars = []
  3004. for sub_name in sub_strs:
  3005. conf_t_path = sub_name.split('_ses-')[0] + '_ses-base_task-rest_run-01_desc-confounds_timeseries.tsv'
  3006. sub_name = sub_strs[0].split('/')[-4]
  3007. print(sub_name)
  3008. try:
  3009. df = pd.read_csv(conf_t_path, delimiter='\t')
  3010. except:
  3011. continue
  3012. cur_fd = (df.framewise_displacement > 0.5).sum()
  3013. study_FDs.append(cur_fd)
  3014. print(cur_fd)
  3015. cur_dvars = df.dvars.mean()
  3016. study_dvars.append(cur_dvars)
  3017. print(cur_dvars)
  3018. plt.figure()
  3019. plt.hist(study_FDs, bins=20)
  3020. # plt.title('FD (#volumes > 0.5mm): timmermann_DMT')
  3021. plt.title('FD (#volumes > 0.5mm out of %i total): Siegel' % len(df.framewise_displacement))
  3022. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Siegel_FDabove0.5mm.png', dpi=600)
  3023. plt.figure()
  3024. plt.hist(np.array(study_FDs) / len(df.framewise_displacement), bins=20)
  3025. plt.title('FD (fraction of volumes > 0.5mm out of %i total): Siegel' % len(df.framewise_displacement))
  3026. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Siegel_fracFDabove0.5mm.png', dpi=600)
  3027. plt.figure()
  3028. plt.hist(study_dvars, bins=20)
  3029. plt.title('DVARS (mean across TS): Siegel')
  3030. plt.savefig('_results_uncorrected_data_pipelines_ana8/QC_Siegel_dvars.png')
  3031. CCs = []
  3032. n_skipped = 0
  3033. conds = []
  3034. for sub_name in sub_strs:
  3035. print(sub_name)
  3036. sub_ts1 = pd.read_csv(sub_name, header=None)
  3037. subcort1_path = sub_name.replace('_schaefer%s' % n_rois, '-subcortical38')
  3038. subcort1 = pd.read_csv(subcort1_path, header=None)
  3039. claustrum1_path = sub_name.replace('_schaefer%s' % n_rois, '_claustrum')
  3040. claustrum1 = pd.read_csv(claustrum1_path, header=None)
  3041. tmp = clean(
  3042. signals=claustrum1.iloc[:, [0, 3]].to_numpy(),
  3043. confounds=claustrum1.iloc[:, [1, 2, 4, 5]].to_numpy(),
  3044. detrend=False, standardize=False, standardize_confounds=False, filter=False)
  3045. claustrum1.iloc[:, [0, 3]] = tmp
  3046. cerebellum1_path = sub_name.replace('_schaefer%s' % n_rois, '_cerebellum')
  3047. cerebellum1 = pd.read_csv(cerebellum1_path, header=None)
  3048. sub_ts1 = pd.concat([sub_ts1, subcort1, claustrum1, cerebellum1], axis=1)
  3049. assert sub_ts1.shape[1] == 161
  3050. sub_ts_z1 = pd.DataFrame(StandardScaler().fit_transform(sub_ts1), columns=full_labels)
  3051. #print(sub_ts_z1)
  3052. cur_cond = 'base' if 'base' in sub_name else 'psil'
  3053. conf_t_path1 = sub_name.split('_ses-')[0] + '_ses-%s_task-rest_run-01_desc-confounds_timeseries.tsv' % cur_cond
  3054. conf_j_path1 = conf_t_path.replace('.tsv', '.json')
  3055. # motion correction
  3056. df = pd.read_csv(conf_t_path1, delimiter='\t')
  3057. sub_motion_frac = (df.framewise_displacement > 0.5).sum() / len(df.framewise_displacement)
  3058. if sub_motion_frac > 0.15:
  3059. print('Skipping subject: %s' % sub_name)
  3060. n_skipped += 1
  3061. continue
  3062. if not os.path.exists(conf_t_path1):
  3063. print('Skipping this subject: confound file not found!')
  3064. continue
  3065. conf1 = get_my_confounds_df(conf_t_path1, conf_j_path1, strategy)
  3066. if len(conf1) != 0:
  3067. conf1 = np.nan_to_num(conf1)
  3068. sub_ts_z_deconf1 = clean(
  3069. signals=sub_ts_z1.values, standardize=False, confounds=np.nan_to_num(conf1))
  3070. else:
  3071. continue
  3072. sub_CC = np.arctanh(np.corrcoef(sub_ts_z_deconf1.T))
  3073. # reg_avg_activity_bar.append(sub_ts.median(0).values)
  3074. # reg_avg_activity_bar_std.append(sub_ts.median(0).values)
  3075. #reg_avg_activity.append(sub_ts.mean(0).values)
  3076. study_id_all.append(12)
  3077. CCs.append(sub_CC)
  3078. conds.append(int(cur_cond == 'psil'))
  3079. FDs_all.append(df.framewise_displacement.mean())
  3080. CCs_all.append(sub_CC)
  3081. conds_all.append(int(cur_cond == 'psil'))
  3082. drug_all.append(0) # 0=psyloc (blue); 1=LSD (orange); 2=Aya (green); 3=Mesc; 4=DMT
  3083. CCs = np.array(CCs)
  3084. conds = np.array(conds)
  3085. masker.inverse_transform(sub_ts_z1.mean(0)).to_filename('_results_uncorrected_data_pipelines_ana8/siegel_coverage.nii.gz')
  3086. CC_avg_plcb = CCs[conds == 0, :, :].mean(0)
  3087. CC_avg_drug = CCs[conds == 1, :, :].mean(0)
  3088. import matplotlib.pylab as plt
  3089. plt.figure(figsize=(16, 10))
  3090. sns.set(font_scale=0.4)
  3091. sns.heatmap(CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3092. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  3093. plt.tight_layout()
  3094. plt.savefig('_results_uncorrected_data_pipelines_ana8/siegel_avg_CC_plcb_%s.pdf' % strategy_suffix)
  3095. import matplotlib.pylab as plt
  3096. plt.figure(figsize=(16, 10))
  3097. sns.set(font_scale=0.4)
  3098. sns.heatmap(CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3099. center=0, xticklabels=full_labels, yticklabels=full_labels, vmin=-1, vmax=+1)
  3100. plt.tight_layout()
  3101. plt.savefig('_results_uncorrected_data_pipelines_ana8/siegel_avg_CC_drug_%s.pdf' % strategy_suffix)
  3102. import matplotlib.pylab as plt
  3103. plt.figure(figsize=(16, 10))
  3104. sns.set(font_scale=0.4)
  3105. sns.heatmap(CC_avg_drug - CC_avg_plcb, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3106. center=0, xticklabels=full_labels, yticklabels=full_labels)
  3107. plt.tight_layout()
  3108. plt.savefig('_results_uncorrected_data_pipelines_ana8/siegel_avg_CC_drug-plcb_%s.pdf' % strategy_suffix)
  3109. # CC_avg_plcb_max = CCs[conds == 0, :, :].max(0)
  3110. # CC_avg_drug_max = CCs[conds == 1, :, :].max(0)
  3111. # import matplotlib.pylab as plt
  3112. # plt.figure(figsize=(16, 10))
  3113. # sns.set(font_scale=0.4)
  3114. # sns.heatmap(CC_avg_plcb_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3115. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  3116. # plt.tight_layout()
  3117. # plt.savefig('_results_uncorrected/Barrett_avg_CC_plcb_max.pdf')
  3118. # import matplotlib.pylab as plt
  3119. # plt.figure(figsize=(16, 10))
  3120. # sns.set(font_scale=0.4)
  3121. # sns.heatmap(CC_avg_drug_max, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3122. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-1, vmax=+1)
  3123. # plt.tight_layout()
  3124. # plt.savefig('_results_uncorrected/Barrett_avg_CC_drug_max.pdf')
  3125. # import matplotlib.pylab as plt
  3126. # plt.figure(figsize=(16, 10))
  3127. # sns.set(font_scale=0.4)
  3128. # sns.heatmap(CC_avg_plcb - CC_avg_drug, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3129. # center=0, xticklabels=cort_labels, yticklabels=cort_labels)
  3130. # plt.tight_layout()
  3131. # plt.savefig('_results_uncorrected/Barrett_avg_CC_plcb-drug.pdf')
  3132. from sklearn.linear_model import LinearRegression
  3133. out_mat = np.zeros((161, 161))
  3134. CCs = np.nan_to_num(CCs)
  3135. for i_roi in range(161):
  3136. for j_roi in range(161):
  3137. if i_roi == j_roi:
  3138. continue
  3139. lr = LinearRegression(fit_intercept=True)
  3140. y = CCs[:, i_roi, j_roi]
  3141. #y = np.arctanh(CCs[:, i_roi, j_roi])
  3142. X = conds[:, None]
  3143. lr.fit(X, y)
  3144. out_mat[i_roi, j_roi] = lr.coef_[0]
  3145. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  3146. import matplotlib.pylab as plt
  3147. plt.figure(figsize=(20, 14))
  3148. sns.set(font_scale=0.4)
  3149. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3150. center=0)
  3151. plt.tight_layout()
  3152. # plt.savefig('_results_uncorrected/barret_lrcoef.pdf')
  3153. plt.savefig('_results_uncorrected_data_pipelines_ana8/siegel_avg_lrcoef_%s.pdf' % strategy_suffix)
  3154. # import matplotlib.pylab as plt
  3155. # plt.figure(figsize=(20, 14))
  3156. # sns.set(font_scale=0.4)
  3157. # sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  3158. # center=0, vmax=.35)
  3159. # plt.tight_layout()
  3160. # plt.savefig('_results_uncorrected/barret_lrcoef_viridis.pdf')
  3161. cum_intra_net = np.zeros((17))
  3162. cum_intra_net_cnt = np.zeros((17))
  3163. cum_inter_net = np.zeros((17))
  3164. cum_inter_net_cnt = np.zeros((17))
  3165. for i in range(n_rois): # rows
  3166. for j in range(n_rois): # columns
  3167. if i==j: # skip connections to self
  3168. continue
  3169. if net17_labels[i] == net17_labels[j]: # intra-network edge !
  3170. cum_intra_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  3171. cum_intra_net_cnt[net17_labels[i] - 1] += 1
  3172. if net17_labels[i] != net17_labels[j]: # inter-network edge !
  3173. cum_inter_net[net17_labels[i] - 1] += np.abs(out_df.iloc[i, j])
  3174. cum_inter_net_cnt[net17_labels[i] - 1] += 1
  3175. ax = pd.DataFrame(cum_intra_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  3176. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  3177. plt.title('Intra-network drug effects', fontsize=12)
  3178. plt.tight_layout()
  3179. # plt.savefig('_results_uncorrected/barrett_cumabs_intra.pdf')
  3180. plt.savefig('_results_uncorrected_data_pipelines_ana8/siegel_avg_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  3181. ax = pd.DataFrame(cum_inter_net, index=net17_label_names).plot.bar(fontsize=8, legend=False)
  3182. plt.ylabel('cumulative absolute beta coefficients', fontsize=10)
  3183. plt.title('Inter-network drug effects', fontsize=12)
  3184. plt.tight_layout()
  3185. # plt.savefig('_results_uncorrected/barrett_cumabs_inter.pdf')
  3186. plt.savefig('_results_uncorrected_data_pipelines_ana8/siegel_cumabs_intra_regnorm_%s.pdf' % strategy_suffix)
  3187. # ax = pd.DataFrame(cum_intra_net / cum_intra_net_cnt,
  3188. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  3189. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  3190. # plt.title('Intra-network drug effects', fontsize=12)
  3191. # plt.tight_layout()
  3192. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_norm.pdf')
  3193. # ax = pd.DataFrame(cum_inter_net / cum_inter_net_cnt,
  3194. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  3195. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  3196. # plt.title('Inter-network drug effects', fontsize=12)
  3197. # plt.tight_layout()
  3198. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_norm.pdf')
  3199. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  3200. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  3201. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  3202. # plt.title('Intra-network drug effects', fontsize=12)
  3203. # plt.tight_layout()
  3204. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_regnorm.pdf')
  3205. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  3206. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  3207. # plt.ylabel('cumulative absolute beta coefficients (normalized)', fontsize=10)
  3208. # plt.title('Inter-network drug effects', fontsize=12)
  3209. # plt.tight_layout()
  3210. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_regnorm.pdf')
  3211. # # no abs
  3212. # cum_intra_net = np.zeros((17))
  3213. # cum_intra_net_cnt = np.zeros((17))
  3214. # cum_inter_net = np.zeros((17))
  3215. # cum_inter_net_cnt = np.zeros((17))
  3216. # for i in range(n_rois): # rows
  3217. # for j in range(n_rois): # columns
  3218. # if i==j: # skip connections to self
  3219. # continue
  3220. # if net17_labels[i] == net17_labels[j]: # intra-network edge !
  3221. # cum_intra_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  3222. # cum_intra_net_cnt[net17_labels[i] - 1] += 1
  3223. # if net17_labels[i] != net17_labels[j]: # inter-network edge !
  3224. # cum_inter_net[net17_labels[i] - 1] += out_df.iloc[i, j]
  3225. # cum_inter_net_cnt[net17_labels[i] - 1] += 1
  3226. # ax = pd.DataFrame(cum_intra_net / net7_regcnt,
  3227. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  3228. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  3229. # plt.title('Intra-network drug effects', fontsize=12)
  3230. # plt.tight_layout()
  3231. # plt.savefig('_results_uncorrected/barrett_cumabs_intra_regnorm_noabs.pdf')
  3232. # ax = pd.DataFrame(cum_inter_net / net7_regcnt,
  3233. # index=net17_label_names).plot.bar(fontsize=8, legend=False)
  3234. # plt.ylabel('average beta coefficients (normalized)', fontsize=10)
  3235. # plt.title('Inter-network drug effects', fontsize=12)
  3236. # plt.tight_layout()
  3237. # plt.savefig('_results_uncorrected/barrett_cumabs_inter_regnorm_noabs.pdf')
  3238. plt.close('all')
  3239. ##########################################################################################
  3240. # now running actual stats on all the aggregated data
  3241. ##########################################################################################
  3242. FDs_all = np.array(FDs_all)
  3243. CCs_all = np.array(CCs_all)
  3244. conds_all = np.array(conds_all)
  3245. study_id_all = np.array(study_id_all)
  3246. drug_all = np.array(drug_all)
  3247. n_studies = len(np.unique(study_id_all))
  3248. from scipy.stats import ttest_rel, ttest_ind
  3249. # appeal / R3: do subjects move their heads differently during placebo vs. target ?
  3250. from scipy.stats import ttest_rel, ttest_ind
  3251. n = min(sum(conds_all==0),
  3252. sum(conds_all==1)
  3253. )
  3254. t, p = ttest_rel(
  3255. FDs_all[(conds_all==0)][:n],
  3256. FDs_all[(conds_all==1)][:n]
  3257. )
  3258. print('all drugs')
  3259. print(p)
  3260. all_avg_pvalue = 0
  3261. all_avg_tvalue = 0
  3262. a_all = []
  3263. b_all = []
  3264. for i_drug in np.unique(drug_all):
  3265. n = min(sum((conds_all==0) & (drug_all==i_drug)),
  3266. sum((conds_all==1) & (drug_all==i_drug))
  3267. )
  3268. a = FDs_all[(conds_all==0) & (drug_all==i_drug)][:n]
  3269. b = FDs_all[(conds_all==1) & (drug_all==i_drug)][:n]
  3270. t, p = ttest_rel(
  3271. a, # cond_all is drug status
  3272. b
  3273. )
  3274. print(drug_labels[i_drug])
  3275. print(p)
  3276. all_avg_pvalue += p
  3277. all_avg_tvalue += t
  3278. a_all += list(a)
  3279. b_all += list(b)
  3280. print('--- average p value ---')
  3281. print(p / (np.max(drug_all) + 1)) # p-value = 0.09263450080062638 + higher order; FDup2 p= ; FDup3 p=; FDup4, log p=; exp p=; 1/x p=, sqrt(p) =
  3282. print('--- average t value ---')
  3283. print(t / (np.max(drug_all) + 1)) # p-value = 0.09263450080062638 + higher order; FDup2 p= ; FDup3 p=; FDup4, log p=; exp p=; 1/x p=, sqrt(p) =
  3284. #boxplot
  3285. import seaborn as sns
  3286. X = pd.DataFrame((a_all, b_all)).T
  3287. X.columns = ['placebo', 'drug']
  3288. plt.figure(figsize=(6, 10))
  3289. sns.boxplot(X)
  3290. plt.xticks(fontsize=14)
  3291. plt.yticks(fontsize=14)
  3292. plt.title('framewise displacement', fontsize=18)
  3293. plt.savefig('_results_uncorrected_data_pipelines_ana8/FD_dotbydot.pdf')
  3294. # drug by drug with higher transformations
  3295. X = np.zeros((7, 5))
  3296. X_t = np.zeros((7, 5))
  3297. for i_drug in np.unique(drug_all):
  3298. n = min(sum((conds_all==0) & (drug_all==i_drug)),
  3299. sum((conds_all==1) & (drug_all==i_drug))
  3300. )
  3301. a = FDs_all[(conds_all==0) & (drug_all==i_drug)][:n]
  3302. b = FDs_all[(conds_all==1) & (drug_all==i_drug)][:n]
  3303. t, p = ttest_rel(
  3304. a, # cond_all is drug status
  3305. b
  3306. )
  3307. print(drug_labels[i_drug])
  3308. print(p)
  3309. X[0, i_drug] = p
  3310. X_t[0, i_drug] = t
  3311. t, p = ttest_rel(
  3312. a*a, # cond_all is drug status
  3313. b*b
  3314. )
  3315. print(drug_labels[i_drug])
  3316. print(p)
  3317. X[1, i_drug] = p
  3318. X_t[1, i_drug] = t
  3319. t, p = ttest_rel(
  3320. a*a*a, # cond_all is drug status
  3321. b*b*b
  3322. )
  3323. print(drug_labels[i_drug])
  3324. print(p)
  3325. X[2, i_drug] = p
  3326. X_t[2, i_drug] = t
  3327. t, p = ttest_rel(
  3328. a*a*a*a, # cond_all is drug status
  3329. b*b*b*b
  3330. )
  3331. print(drug_labels[i_drug])
  3332. print(p)
  3333. X[3, i_drug] = p
  3334. X_t[3, i_drug] = t
  3335. t, p = ttest_rel(
  3336. np.log(a), # cond_all is drug status
  3337. np.log(b)
  3338. )
  3339. print(drug_labels[i_drug])
  3340. print(p)
  3341. X[4, i_drug] = p
  3342. X_t[4, i_drug] = t
  3343. t, p = ttest_rel(
  3344. 1 / np.array(a), # cond_all is drug status
  3345. 1 / np.array(b)
  3346. )
  3347. print(drug_labels[i_drug])
  3348. print(p)
  3349. X[5, i_drug] = p
  3350. X_t[5, i_drug] = t
  3351. t, p = ttest_rel(
  3352. np.sqrt(a), # cond_all is drug status
  3353. np.sqrt(b)
  3354. )
  3355. print(drug_labels[i_drug])
  3356. print(p)
  3357. X[6, i_drug] = p
  3358. X_t[6, i_drug] = t
  3359. tranfs = ['x', 'x2', 'x3', 'x4' , 'log(x)', '1/x', 'sqrt(x)']
  3360. pX = pd.DataFrame(X, columns=drug_labels, index=tranfs)
  3361. pX_t = pd.DataFrame(X_t, columns=drug_labels, index=tranfs)
  3362. pX.to_csv('_results_uncorrected_data_pipelines_ana8/FD_drugbydrug_pvalues.csv')
  3363. pX_t = np.abs(pX_t)
  3364. pX_t.to_csv('_results_uncorrected_data_pipelines_ana8/FD_drugbydrug_tvalues.csv')
  3365. # pX.to_csv('_results_uncorrected_data_pipelines_ana8/FD_drugbydrug_pvalues.csv', float_format='%.4')
  3366. # pX_t.to_csv('_results_uncorrected_data_pipelines_ana8/FD_drugbydrug_tvalues.csv', float_format='%.4')
  3367. #acc = cross_val_score(estimator=LinearSVC(), X=FDs_all[:, None], y=conds_all[:, None], cv=KFold(n_splits=10, random_state=43, shuffle=True)); print(acc.mean()); print(acc.std()*2)
  3368. # 0.5984875983061102
  3369. # 0.15332339004087756
  3370. CCs_ravelized = CCs_all.reshape(CCs_all.shape[0], CCs_all.shape[1]*CCs_all.shape[1])
  3371. CCs_ravelized = np.nan_to_num(CCs_ravelized)
  3372. y = np.array(FDs_all > np.median(FDs_all))[:, None]
  3373. acc = cross_val_score(estimator=LinearSVC(), X=CCs_ravelized, y=y, cv=KFold(n_splits=10, random_state=43, shuffle=True)); print(acc.mean()); print(acc.std()*2)
  3374. # 0.501814882032668 -> so, no part int he brain, systematically distinguishes between high- versus low-motion participant connectomes in a robust way
  3375. # 0.15367835036406347 most holistic analyses that we can think of
  3376. for i_drug in np.arange(5):
  3377. acc = cross_val_score(estimator=LinearSVC(), X=CCs_ravelized[drug_all==i_drug], y=y[drug_all==i_drug], cv=KFold(n_splits=10, random_state=43, shuffle=True)); print(acc.mean()); print(acc.std()*2)
  3378. # none of 5 drugs, has above chance SVC classifier; when assessed drug by drug; that conclusion extends to any between-network and with-network effects as well
  3379. from sklearn.model_selection import cross_val_score, LeaveOneGroupOut, KFold
  3380. from sklearn.svm import LinearSVC
  3381. from scipy.stats import pearsonr
  3382. out_mat_placebo = np.zeros((161, 161))
  3383. out_mat_drug = np.zeros((161, 161))
  3384. for i_study in np.unique(study_id_all):
  3385. for i_roi in range(161):
  3386. for j_roi in range(161):
  3387. if i_roi == j_roi:
  3388. continue
  3389. y = np.nan_to_num(CCs_all[:, i_roi, j_roi])
  3390. x = FDs_all
  3391. r, p = pearsonr(x[(conds_all==0) & (i_study==study_id_all)], y[(conds_all==0) & (i_study==study_id_all)])
  3392. out_mat_placebo[i_roi, j_roi] = r
  3393. r, p = pearsonr(x[(conds_all==1) & (i_study==study_id_all)], y[(conds_all==1) & (i_study==study_id_all)])
  3394. out_mat_drug[i_roi, j_roi] = r
  3395. out_df_placebo = pd.DataFrame(out_mat_placebo, columns=full_labels, index=full_labels)
  3396. out_df_placebo.to_csv('_results_uncorrected_data_pipelines_ana8/FD-FCmap_placebo_study%i_%s.csv' % (i_study+1, strategy_suffix))
  3397. out_df_drug = pd.DataFrame(out_mat_drug, columns=full_labels, index=full_labels)
  3398. out_df_drug.to_csv('_results_uncorrected_data_pipelines_ana8/FD-FCmap_drug_study%i_%s.csv' % (i_study+1, strategy_suffix))
  3399. print(ttest_ind(out_mat_placebo.ravel(), out_mat_drug.ravel()))
  3400. from scipy.stats import pearsonr
  3401. out_mat_placebo = np.zeros((161, 161))
  3402. out_mat_drug = np.zeros((161, 161))
  3403. for i_drug in np.unique(drug_all):
  3404. for i_roi in range(161):
  3405. for j_roi in range(161):
  3406. if i_roi == j_roi:
  3407. continue
  3408. y = np.nan_to_num(CCs_all[:, i_roi, j_roi])
  3409. x = FDs_all
  3410. r, p = pearsonr(x[(conds_all==0) & (i_drug==drug_all)], y[(conds_all==0) & (i_drug==drug_all)])
  3411. out_mat_placebo[i_roi, j_roi] = r
  3412. r, p = pearsonr(x[(conds_all==1) & (i_drug==drug_all)], y[(conds_all==1) & (i_drug==drug_all)])
  3413. out_mat_drug[i_roi, j_roi] = r
  3414. out_df_placebo = pd.DataFrame(out_mat_placebo, columns=full_labels, index=full_labels)
  3415. out_df_placebo.to_csv('_results_uncorrected_data_pipelines_ana8/FD-FCmap_placebo_psyche%s_%s.csv' % (drug_labels[i_drug], strategy_suffix))
  3416. out_df_drug = pd.DataFrame(out_mat_drug, columns=full_labels, index=full_labels)
  3417. out_df_drug.to_csv('_results_uncorrected_data_pipelines_ana8/FD-FCmap_drug_psyche%s_%s.csv' % (drug_labels[i_drug], strategy_suffix))
  3418. print(ttest_ind(out_mat_placebo.ravel(), out_mat_drug.ravel()))
  3419. # revision: compute FD susceptibility map
  3420. from scipy.stats import pearsonr
  3421. out_mat = np.zeros((161, 161))
  3422. out_mat_p = np.zeros((161, 161))
  3423. for i_roi in range(161):
  3424. for j_roi in range(161):
  3425. if i_roi == j_roi:
  3426. continue
  3427. y = np.nan_to_num(CCs_all[:, i_roi, j_roi])
  3428. x = FDs_all
  3429. r, p = pearsonr(x, y)
  3430. out_mat[i_roi, j_roi], out_mat_p[i_roi, j_roi] = r, p
  3431. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  3432. import matplotlib.pylab as plt
  3433. plt.close('all')
  3434. plt.figure(figsize=(20, 14))
  3435. sns.set(font_scale=0.4)
  3436. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5}, vmin=-1.0, vmax=1.0,
  3437. center=0)
  3438. plt.tight_layout()
  3439. plt.savefig('_results_uncorrected_data_pipelines_ana8/13studies_FD_suscept_%s.pdf' % strategy_suffix)
  3440. # out_mat[np.where(out_mat_p > (.05))] = 0
  3441. out_mat[np.where(out_mat_p > (.05/25921))] = 0
  3442. plt.figure(figsize=(20, 14))
  3443. sns.set(font_scale=0.4)
  3444. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5}, vmin=-1.0, vmax=1.0,
  3445. center=0)
  3446. plt.tight_layout()
  3447. plt.savefig('_results_uncorrected_data_pipelines_ana8/13studies_FD_suscept_p05_%s.pdf' % strategy_suffix)
  3448. for i_drug in np.unique(drug_all):
  3449. # revision: compute FD susceptibility map
  3450. from scipy.stats import pearsonr
  3451. out_mat = np.zeros((161, 161))
  3452. out_mat_p = np.zeros((161, 161))
  3453. for i_roi in range(161):
  3454. for j_roi in range(161):
  3455. if i_roi == j_roi:
  3456. continue
  3457. y = np.nan_to_num(CCs_all[:, i_roi, j_roi])
  3458. x = FDs_all
  3459. r, p = pearsonr(x[drug_all==i_drug], y[drug_all==i_drug])
  3460. out_mat[i_roi, j_roi], out_mat_p[i_roi, j_roi] = r, p
  3461. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  3462. import matplotlib.pylab as plt
  3463. plt.close('all')
  3464. plt.figure(figsize=(20, 14))
  3465. sns.set(font_scale=0.4)
  3466. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5}, vmin=-1.0, vmax=1.0,
  3467. center=0)
  3468. plt.tight_layout()
  3469. plt.savefig('_results_uncorrected_data_pipelines_ana8/13studies_FD_suscept_%s_drug%s.pdf' % (strategy_suffix, drug_labels[i_drug]))
  3470. # out_mat[np.where(out_mat_p > (.05))] = 0
  3471. out_mat[np.where(out_mat_p > (.05/25921))] = 0
  3472. plt.figure(figsize=(20, 14))
  3473. sns.set(font_scale=0.4)
  3474. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5}, vmin=-1.0, vmax=1.0,
  3475. center=0)
  3476. plt.tight_layout()
  3477. plt.savefig('_results_uncorrected_data_pipelines_ana8/13studies_FD_suscept_p05_%s_drug%s.pdf' % (strategy_suffix, drug_labels[i_drug]))
  3478. # aggregate statistics: reg-reg conn
  3479. from sklearn.linear_model import LinearRegression
  3480. out_mat = np.zeros((161, 161))
  3481. for i_roi in range(161):
  3482. for j_roi in range(161):
  3483. if i_roi == j_roi:
  3484. continue
  3485. lr = LinearRegression(fit_intercept=True)
  3486. y = np.nan_to_num(CCs_all[:, i_roi, j_roi])
  3487. X = conds_all[:, None]
  3488. lr.fit(X, y)
  3489. out_mat[i_roi, j_roi] = lr.coef_[0]
  3490. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  3491. import matplotlib.pylab as plt
  3492. plt.close('all')
  3493. plt.figure(figsize=(20, 14))
  3494. sns.set(font_scale=0.4)
  3495. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3496. center=0)
  3497. plt.tight_layout()
  3498. plt.savefig('_results_uncorrected_data_pipelines_ana8/13studies_lrcoef_%s.pdf' % strategy_suffix)
  3499. import matplotlib.pylab as plt
  3500. plt.figure(figsize=(20, 14))
  3501. sns.set(font_scale=0.4)
  3502. sns.heatmap(np.abs(out_df), cmap='viridis', square=True, cbar_kws={"shrink": 0.5},
  3503. center=0)#, vmax=.5)
  3504. plt.tight_layout()
  3505. plt.savefig('_results_uncorrected_data_pipelines_ana8/13studies_lrcoef_viridis_%s.pdf' % strategy_suffix)
  3506. # visu
  3507. from nilearn.input_data import NiftiLabelsMasker
  3508. masker = NiftiLabelsMasker(atlas.maps)
  3509. masker.fit()
  3510. regionwise_effects = np.abs(out_df).values.sum(1)[None, :]
  3511. out_nii1 = masker.inverse_transform(regionwise_effects)
  3512. out_nii2 = masker_cereb.inverse_transform(regionwise_effects[:, -17:])
  3513. out_nii = math_img('A + B', A=out_nii1, B=out_nii2)
  3514. out_nii.to_filename('_results_uncorrected_data_pipelines_ana8/13studies_avg_effects_%s.nii.gz' % strategy_suffix)
  3515. # aggregate statistics: reg-reg conn (PER DRUG)
  3516. from sklearn.linear_model import LinearRegression
  3517. for i_drug in np.unique(drug_all):
  3518. out_mat = np.zeros((161, 161))
  3519. for i_roi in range(161):
  3520. for j_roi in range(161):
  3521. if i_roi == j_roi:
  3522. continue
  3523. lr = LinearRegression(fit_intercept=True)
  3524. y = np.nan_to_num(CCs_all[drug_all == i_drug, i_roi, j_roi])
  3525. X = np.nan_to_num(conds_all[drug_all == i_drug, None])
  3526. lr.fit(X, y)
  3527. out_mat[i_roi, j_roi] = lr.coef_[0]
  3528. out_df = pd.DataFrame(out_mat, columns=full_labels, index=full_labels)
  3529. # visu
  3530. import matplotlib.pylab as plt
  3531. plt.close('all')
  3532. plt.figure(figsize=(20, 14))
  3533. sns.set(font_scale=0.4)
  3534. sns.heatmap(out_df, cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3535. center=0)
  3536. plt.tight_layout()
  3537. plt.savefig('_results_uncorrected_data_pipelines_ana8/13studies_lrcoef_%s_drug%s.pdf' % (strategy_suffix, drug_labels[i_drug]))
  3538. # from nilearn.input_data import NiftiLabelsMasker
  3539. # masker = NiftiLabelsMasker(atlas.maps)
  3540. # masker.fit()
  3541. # regionwise_effects = np.abs(out_df).values.sum(1)[None, :]
  3542. # out_nii = masker.inverse_transform(regionwise_effects)
  3543. from nilearn.input_data import NiftiLabelsMasker
  3544. masker = NiftiLabelsMasker(atlas.maps)
  3545. masker.fit()
  3546. regionwise_effects = np.abs(out_df).values.sum(1)[None, :]
  3547. out_nii1 = masker.inverse_transform(regionwise_effects)
  3548. out_nii2 = masker_cereb.inverse_transform(regionwise_effects[:, -17:])
  3549. out_nii = math_img('A + B', A=out_nii1, B=out_nii2)
  3550. out_nii.to_filename('_results_uncorrected_data_pipelines_ana8/13studies_avg_effects_%s_drug%s.nii.gz' % (strategy_suffix, drug_labels[i_drug]))
  3551. CC_avg_plcb = np.nanmean(CCs_all[(drug_all == i_drug) & (conds_all == 0), :, :], axis=0)
  3552. CC_avg_drug = np.nanmean(CCs_all[(drug_all == i_drug) & (conds_all == 1), :, :], axis=0)
  3553. plt.figure(figsize=(20, 14))
  3554. sns.set(font_scale=0.4)
  3555. # sns.heatmap(CC_avg_drug - CC_avg_plcb , cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3556. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-0.25, vmax=+0.25)
  3557. sns.heatmap(np.nan_to_num(CC_avg_drug - CC_avg_plcb) , cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3558. center=0, xticklabels=full_labels, yticklabels=full_labels)
  3559. plt.tight_layout()
  3560. pd.DataFrame(np.nan_to_num(CC_avg_drug - CC_avg_plcb), index=full_labels, columns=full_labels).to_csv('_results_uncorrected_data_pipelines_ana8/13studies_drug-plcb_%s_drug%s.csv' % (strategy_suffix, drug_labels[i_drug]))
  3561. plt.savefig('_results_uncorrected_data_pipelines_ana8/13studies_drug-plcb_%s_drug%s.pdf' % (strategy_suffix, drug_labels[i_drug]))
  3562. #all
  3563. CC_avg_plcb = np.nanmean(CCs_all[(conds_all == 0), :, :], axis=0)
  3564. CC_avg_drug = np.nanmean(CCs_all[(conds_all == 1), :, :], axis=0)
  3565. plt.figure(figsize=(20, 14))
  3566. sns.set(font_scale=0.4)
  3567. # sns.heatmap(CC_avg_drug - CC_avg_plcb , cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3568. # center=0, xticklabels=cort_labels, yticklabels=cort_labels, vmin=-0.25, vmax=+0.25)
  3569. sns.heatmap(np.nan_to_num(CC_avg_drug - CC_avg_plcb) , cmap='RdBu_r', square=True, cbar_kws={"shrink": 0.5},
  3570. center=0, xticklabels=full_labels, yticklabels=full_labels)
  3571. plt.tight_layout()
  3572. pd.DataFrame(np.nan_to_num(CC_avg_drug - CC_avg_plcb), index=full_labels, columns=full_labels).to_csv('_results_uncorrected_data_pipelines_ana8/13studies_drug-plcb_%s_drugALL.csv' % (strategy_suffix))
  3573. plt.savefig('_results_uncorrected_data_pipelines_ana8/13studies_drug-plcb_%s_drugALL.pdf' % (strategy_suffix))
  3574. # # average CCs by network (to stablize the estimates that we input into the BHM), HPinterc
  3575. # # net-net
  3576. for cur_net1 in np.unique(net17_labels):
  3577. for cur_net2 in np.unique(net17_labels):
  3578. if cur_net1 == cur_net2:
  3579. continue
  3580. print('-' * 80)
  3581. cur_net_name1 = net17_label_names[cur_net1 - 1]
  3582. cur_net_name2 = net17_label_names[cur_net2 - 1]
  3583. print(cur_net_name1)
  3584. print('-- and --')
  3585. print(cur_net_name2)
  3586. net_inds1 = np.where(net17_labels == cur_net1)[0]
  3587. net_inds2 = np.where(net17_labels == cur_net2)[0]
  3588. y = CCs_all[:, net_inds1, :][:, :, net_inds2]
  3589. y = y.reshape((len(y), len(net_inds1)*len(net_inds2))).mean(1)
  3590. print(pd.DataFrame(y).describe())
  3591. # count 273.000000
  3592. # mean 0.340264
  3593. # std 0.134900
  3594. # min 0.078441
  3595. # 25% 0.238487
  3596. # 50% 0.314088
  3597. # 75% 0.428571
  3598. # max 0.750653
  3599. n_drugs = len(np.unique(drug_all))
  3600. pm_varnames = []
  3601. with pm.Model() as hierarchical_model:
  3602. hp_drugclass = pm.Normal('hp_drugclass', mu=0., sigma=1, shape=n_drugs)
  3603. hp_drugclass_priors = list(np.zeros(n_studies))
  3604. for j_drug in range(n_drugs):
  3605. for k_study in np.unique(study_id_all[drug_all == j_drug]):
  3606. hp_drugclass_priors[k_study] = hp_drugclass[j_drug]
  3607. alpha_drugclass = pm.Normal('alpha_drugclass', mu=hp_drugclass_priors, sigma=1, shape=n_studies)
  3608. # hp_cond = pm.Normal('hp_cond', mu=0., sigma=1, shape=1)
  3609. # alpha_cond = pm.Normal('alpha_cond', mu=hp_cond, sigma=1, shape=2)
  3610. # alpha_cond = pm.Normal('alpha_cond', mu=0, sigma=1, shape=2)
  3611. # beta_cond = pm.Normal('beta_cond', mu=0, sigma=1)
  3612. hp_beta = pm.Normal('hp_beta', mu=0., sigma=1, shape=1)
  3613. slope_betas = pm.Normal('slope_betas', mu=hp_beta, sigma=1, shape=n_drugs)
  3614. # beta_study_priors = list(np.zeros(n_studies))
  3615. # for j_drug in range(n_drugs):
  3616. # for k_study in np.unique(study_id_all[drug_all == j_drug]):
  3617. # beta_study_priors[k_study] = hp_beta[j_drug]
  3618. # beta_inter = pm.Normal('beta_inter_cond_drug', mu=beta_study_priors, sigma=2, shape=n_studies)
  3619. # reg_effect = alpha_cond[conds]
  3620. reg_effect = alpha_drugclass[study_id_all] + slope_betas[drug_all] * conds_all
  3621. eps = pm.HalfCauchy('eps', 5) # Model error
  3622. group_like = pm.Normal('beh_like', mu=reg_effect, sigma=eps, observed=y)
  3623. with hierarchical_model:
  3624. hierarchical_trace = pm.sample(draws=10000, n_init=5000, #init='advi',
  3625. chains=3, cores=9, progressbar=True,
  3626. random_seed=[1, 2, 3]) # one per chain needed
  3627. print(pm.summary(hierarchical_trace, hdi_prob=0.66))
  3628. OUT_DIR = '_results_uncorrected_data_pipelines_ana8'
  3629. output_name = 'net-net_HPinterc_effect_%s-%s' % (cur_net_name1, cur_net_name2)
  3630. t = hierarchical_trace
  3631. # for cur_roi in hierarchical_model.vars:
  3632. for cur_roi in hierarchical_model.named_vars:
  3633. from matplotlib.lines import Line2D
  3634. cur_roi = cur_roi
  3635. plt.close('all')
  3636. # THRESH = 0.5
  3637. # THRESH = 1.0
  3638. n_last_chains = 500
  3639. try:
  3640. suffix = ''
  3641. fig = arviz.plot_posterior(t, var_names=cur_roi, textsize=15.0,
  3642. hdi_prob=0.66)
  3643. # fig = pm.plot_posterior(t[-n_last_chains:], varnames=[cur_roi],
  3644. # credible_interval=0.95)
  3645. # try:
  3646. # for i_higher_cat in range(n_meta_cat):
  3647. # fig[i_higher_cat].set_xlim(-THRESH, THRESH) # make plots more comparable
  3648. # except:
  3649. # pass
  3650. plt.tight_layout()
  3651. plt.savefig('%s/%s_%s_posterior%s.png' % (OUT_DIR, output_name, cur_roi, suffix), dpi=150)
  3652. fig = arviz.plot_trace(t, var_names=[cur_roi])
  3653. # max_abs_mode = np.max(np.abs(hierarchical_trace2[-n_last_chains:][cur_roi].mean(0)))
  3654. # fig = pm.traceplot(t[-n_last_chains:], varnames=[cur_roi])
  3655. # max_abs_mode = np.max(np.abs(t[-n_last_chains:][cur_roi].mean(0)))
  3656. # fig[0][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3657. # try:
  3658. # fig[1][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3659. # except:
  3660. # pass
  3661. # try:
  3662. # if max_abs_mode < THRESH and not 'nuisance' in cur_roi:
  3663. # fig[0][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3664. # except:
  3665. # pass
  3666. # post_lines = fig[0][0].get_lines()
  3667. # custom_lines = [Line2D([0], [0], color=l.get_c(), lw=4) for l in post_lines]
  3668. # if subgroup_labels is None:
  3669. # subgroup_labels = ['subgroup %i' % i for i in range(len(custom_lines))]
  3670. # fig[0][0].legend(custom_lines, subgroup_labels, loc='upper left', prop={'size': 7.5})
  3671. plt.tight_layout()
  3672. plt.savefig('%s/%s_%s%s.png' % (OUT_DIR, output_name, cur_roi,
  3673. suffix), dpi=150)
  3674. # plt.savefig('%s/%s_%s.png' % (OUT_DIR, output_name, cur_roi), dpi=150)
  3675. except:
  3676. pass
  3677. # # average CCs by network (to stablize the estimates that we input into the BHM), HPinterc
  3678. # # net-net (across drug average)
  3679. for cur_net1 in np.unique(net17_labels):
  3680. for cur_net2 in np.unique(net17_labels):
  3681. if cur_net1 == cur_net2:
  3682. continue
  3683. print('-' * 80)
  3684. cur_net_name1 = net17_label_names[cur_net1 - 1]
  3685. cur_net_name2 = net17_label_names[cur_net2 - 1]
  3686. print(cur_net_name1)
  3687. print('-- and --')
  3688. print(cur_net_name2)
  3689. net_inds1 = np.where(net17_labels == cur_net1)[0]
  3690. net_inds2 = np.where(net17_labels == cur_net2)[0]
  3691. y = CCs_all[:, net_inds1, :][:, :, net_inds2]
  3692. y = y.reshape((len(y), len(net_inds1)*len(net_inds2))).mean(1)
  3693. print(pd.DataFrame(y).describe())
  3694. # count 273.000000
  3695. # mean 0.340264
  3696. # std 0.134900
  3697. # min 0.078441
  3698. # 25% 0.238487
  3699. # 50% 0.314088
  3700. # 75% 0.428571
  3701. # max 0.750653
  3702. n_drugs = len(np.unique(drug_all))
  3703. pm_varnames = []
  3704. with pm.Model() as hierarchical_model:
  3705. hp_drugclass = pm.Normal('hp_drugclass', mu=0., sigma=1, shape=n_drugs)
  3706. hp_drugclass_priors = list(np.zeros(n_studies))
  3707. for j_drug in range(n_drugs):
  3708. for k_study in np.unique(study_id_all[drug_all == j_drug]):
  3709. hp_drugclass_priors[k_study] = hp_drugclass[j_drug]
  3710. alpha_drugclass = pm.Normal('alpha_drugclass', mu=hp_drugclass_priors, sigma=1, shape=n_studies)
  3711. # hp_cond = pm.Normal('hp_cond', mu=0., sigma=1, shape=1)
  3712. # alpha_cond = pm.Normal('alpha_cond', mu=hp_cond, sigma=1, shape=2)
  3713. # alpha_cond = pm.Normal('alpha_cond', mu=0, sigma=1, shape=2)
  3714. # beta_cond = pm.Normal('beta_cond', mu=0, sigma=1)
  3715. #hp_beta = pm.Normal('hp_beta', mu=0., sigma=1, shape=1)
  3716. slope_betas = pm.Normal('slope_betas', mu=0, sigma=1, shape=1)
  3717. # beta_study_priors = list(np.zeros(n_studies))
  3718. # for j_drug in range(n_drugs):
  3719. # for k_study in np.unique(study_id_all[drug_all == j_drug]):
  3720. # beta_study_priors[k_study] = hp_beta[j_drug]
  3721. # beta_inter = pm.Normal('beta_inter_cond_drug', mu=beta_study_priors, sigma=2, shape=n_studies)
  3722. # reg_effect = alpha_cond[conds]
  3723. reg_effect = alpha_drugclass[study_id_all] + slope_betas * conds_all
  3724. eps = pm.HalfCauchy('eps', 5) # Model error
  3725. group_like = pm.Normal('beh_like', mu=reg_effect, sigma=eps, observed=y)
  3726. with hierarchical_model:
  3727. hierarchical_trace = pm.sample(draws=10000, n_init=5000, #init='advi',
  3728. chains=3, cores=9, progressbar=True,
  3729. random_seed=[1, 2, 3]) # one per chain needed
  3730. print(pm.summary(hierarchical_trace, hdi_prob=0.66))
  3731. OUT_DIR = '_results_uncorrected_data_pipelines_ana8'
  3732. output_name = 'net-net_HPinterc_effect_%s-%s_across' % (cur_net_name1, cur_net_name2)
  3733. t = hierarchical_trace
  3734. for cur_roi in hierarchical_model.named_vars:
  3735. from matplotlib.lines import Line2D
  3736. cur_roi = cur_roi
  3737. plt.close('all')
  3738. # THRESH = 0.5
  3739. # THRESH = 1.0
  3740. n_last_chains = 500
  3741. try:
  3742. suffix = ''
  3743. fig = arviz.plot_posterior(t, var_names=cur_roi, textsize=15.0,
  3744. hdi_prob=0.66)
  3745. # fig = pm.plot_posterior(t[-n_last_chains:], varnames=[cur_roi],
  3746. # credible_interval=0.95)
  3747. # try:
  3748. # for i_higher_cat in range(n_meta_cat):
  3749. # fig[i_higher_cat].set_xlim(-THRESH, THRESH) # make plots more comparable
  3750. # except:
  3751. # pass
  3752. plt.tight_layout()
  3753. plt.savefig('%s/%s_%s_posterior%s.png' % (OUT_DIR, output_name, cur_roi, suffix), dpi=150)
  3754. fig = arviz.plot_trace(t, var_names=[cur_roi])
  3755. # max_abs_mode = np.max(np.abs(hierarchical_trace2[-n_last_chains:][cur_roi].mean(0)))
  3756. # fig = pm.traceplot(t[-n_last_chains:], varnames=[cur_roi])
  3757. # max_abs_mode = np.max(np.abs(t[-n_last_chains:][cur_roi].mean(0)))
  3758. # fig[0][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3759. # try:
  3760. # fig[1][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3761. # except:
  3762. # pass
  3763. # try:
  3764. # if max_abs_mode < THRESH and not 'nuisance' in cur_roi:
  3765. # fig[0][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3766. # except:
  3767. # pass
  3768. # post_lines = fig[0][0].get_lines()
  3769. # custom_lines = [Line2D([0], [0], color=l.get_c(), lw=4) for l in post_lines]
  3770. # if subgroup_labels is None:
  3771. # subgroup_labels = ['subgroup %i' % i for i in range(len(custom_lines))]
  3772. # fig[0][0].legend(custom_lines, subgroup_labels, loc='upper left', prop={'size': 7.5})
  3773. plt.tight_layout()
  3774. plt.savefig('%s/%s_%s%s.png' % (OUT_DIR, output_name, cur_roi,
  3775. suffix), dpi=150)
  3776. # plt.savefig('%s/%s_%s.png' % (OUT_DIR, output_name, cur_roi), dpi=150)
  3777. except:
  3778. pass
  3779. # # average CCs by network (to stablize the estimates that we input into the BHM), HPinterc
  3780. # # net-THA-D
  3781. net_THAD_labels = np.array([s.startswith('THA-D') * 20 for s in full_labels])
  3782. for cur_net1 in np.unique(net17_labels):
  3783. for cur_net2 in np.unique(net_THAD_labels):
  3784. if cur_net2 == 0:
  3785. continue
  3786. print('-' * 80)
  3787. cur_net_name1 = net17_label_names[cur_net1 - 1]
  3788. cur_net_name2 = 'THA-D'
  3789. print(cur_net_name1)
  3790. print('-- and --')
  3791. print(cur_net_name2)
  3792. net_inds1 = np.where(net17_labels == cur_net1)[0]
  3793. net_inds2 = np.where(net_THAD_labels == cur_net2)[0]
  3794. y = CCs_all[:, net_inds1, :][:, :, net_inds2]
  3795. y = y.reshape((len(y), len(net_inds1)*len(net_inds2))).mean(1)
  3796. print(pd.DataFrame(y).describe())
  3797. # count 273.000000
  3798. # mean 0.340264
  3799. # std 0.134900
  3800. # min 0.078441
  3801. # 25% 0.238487
  3802. # 50% 0.314088
  3803. # 75% 0.428571
  3804. # max 0.750653
  3805. n_drugs = len(np.unique(drug_all))
  3806. pm_varnames = []
  3807. with pm.Model() as hierarchical_model:
  3808. hp_drugclass = pm.Normal('hp_drugclass', mu=0., sigma=1, shape=n_drugs)
  3809. hp_drugclass_priors = list(np.zeros(n_studies))
  3810. for j_drug in range(n_drugs):
  3811. for k_study in np.unique(study_id_all[drug_all == j_drug]):
  3812. hp_drugclass_priors[k_study] = hp_drugclass[j_drug]
  3813. alpha_drugclass = pm.Normal('alpha_drugclass', mu=hp_drugclass_priors, sigma=1, shape=n_studies)
  3814. # hp_cond = pm.Normal('hp_cond', mu=0., sigma=1, shape=1)
  3815. # alpha_cond = pm.Normal('alpha_cond', mu=hp_cond, sigma=1, shape=2)
  3816. # alpha_cond = pm.Normal('alpha_cond', mu=0, sigma=1, shape=2)
  3817. # beta_cond = pm.Normal('beta_cond', mu=0, sigma=1)
  3818. hp_beta = pm.Normal('hp_beta', mu=0., sigma=1, shape=1)
  3819. slope_betas = pm.Normal('slope_betas', mu=hp_beta, sigma=1, shape=n_drugs)
  3820. # beta_study_priors = list(np.zeros(n_studies))
  3821. # for j_drug in range(n_drugs):
  3822. # for k_study in np.unique(study_id_all[drug_all == j_drug]):
  3823. # beta_study_priors[k_study] = hp_beta[j_drug]
  3824. # beta_inter = pm.Normal('beta_inter_cond_drug', mu=beta_study_priors, sigma=2, shape=n_studies)
  3825. # reg_effect = alpha_cond[conds]
  3826. reg_effect = alpha_drugclass[study_id_all] + slope_betas[drug_all] * conds_all
  3827. eps = pm.HalfCauchy('eps', 5) # Model error
  3828. group_like = pm.Normal('beh_like', mu=reg_effect, sigma=eps, observed=y)
  3829. with hierarchical_model:
  3830. hierarchical_trace = pm.sample(draws=10000, n_init=5000, #init='advi',
  3831. chains=3, cores=9, progressbar=True,
  3832. random_seed=[1, 2, 3]) # one per chain needed
  3833. print(pm.summary(hierarchical_trace, hdi_prob=0.66))
  3834. OUT_DIR = '_results_uncorrected_data_pipelines_ana8'
  3835. output_name = 'net-THAD_HPinterc_effect_%s-%s' % (cur_net_name1, cur_net_name2)
  3836. t = hierarchical_trace
  3837. for cur_roi in hierarchical_model.named_vars:
  3838. from matplotlib.lines import Line2D
  3839. cur_roi = cur_roi
  3840. plt.close('all')
  3841. # THRESH = 0.5
  3842. # THRESH = 1.0
  3843. n_last_chains = 500
  3844. try:
  3845. suffix = ''
  3846. fig = arviz.plot_posterior(t, var_names=cur_roi, textsize=15.0,
  3847. hdi_prob=0.66)
  3848. # fig = pm.plot_posterior(t[-n_last_chains:], varnames=[cur_roi],
  3849. # credible_interval=0.95)
  3850. # try:
  3851. # for i_higher_cat in range(n_meta_cat):
  3852. # fig[i_higher_cat].set_xlim(-THRESH, THRESH) # make plots more comparable
  3853. # except:
  3854. # pass
  3855. plt.tight_layout()
  3856. plt.savefig('%s/%s_%s_posterior%s.png' % (OUT_DIR, output_name, cur_roi, suffix), dpi=150)
  3857. fig = arviz.plot_trace(t, var_names=[cur_roi])
  3858. # max_abs_mode = np.max(np.abs(hierarchical_trace2[-n_last_chains:][cur_roi].mean(0)))
  3859. # fig = pm.traceplot(t[-n_last_chains:], varnames=[cur_roi])
  3860. # max_abs_mode = np.max(np.abs(t[-n_last_chains:][cur_roi].mean(0)))
  3861. # fig[0][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3862. # try:
  3863. # fig[1][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3864. # except:
  3865. # pass
  3866. # try:
  3867. # if max_abs_mode < THRESH and not 'nuisance' in cur_roi:
  3868. # fig[0][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3869. # except:
  3870. # pass
  3871. # post_lines = fig[0][0].get_lines()
  3872. # custom_lines = [Line2D([0], [0], color=l.get_c(), lw=4) for l in post_lines]
  3873. # if subgroup_labels is None:
  3874. # subgroup_labels = ['subgroup %i' % i for i in range(len(custom_lines))]
  3875. # fig[0][0].legend(custom_lines, subgroup_labels, loc='upper left', prop={'size': 7.5})
  3876. plt.tight_layout()
  3877. plt.savefig('%s/%s_%s%s.png' % (OUT_DIR, output_name, cur_roi,
  3878. suffix), dpi=150)
  3879. # plt.savefig('%s/%s_%s.png' % (OUT_DIR, output_name, cur_roi), dpi=150)
  3880. except:
  3881. pass
  3882. # # average CCs by network (to stablize the estimates that we input into the BHM), HPinterc
  3883. # # net-THA-D (across drug average)
  3884. net_THAD_labels = np.array([s.startswith('THA-D') * 20 for s in full_labels])
  3885. for cur_net1 in np.unique(net17_labels):
  3886. for cur_net2 in np.unique(net_THAD_labels):
  3887. if cur_net2 == 0:
  3888. continue
  3889. print('-' * 80)
  3890. cur_net_name1 = net17_label_names[cur_net1 - 1]
  3891. cur_net_name2 = 'THA-D'
  3892. print(cur_net_name1)
  3893. print('-- and --')
  3894. print(cur_net_name2)
  3895. net_inds1 = np.where(net17_labels == cur_net1)[0]
  3896. net_inds2 = np.where(net_THAD_labels == cur_net2)[0]
  3897. y = CCs_all[:, net_inds1, :][:, :, net_inds2]
  3898. y = y.reshape((len(y), len(net_inds1)*len(net_inds2))).mean(1)
  3899. print(pd.DataFrame(y).describe())
  3900. # count 273.000000
  3901. # mean 0.340264
  3902. # std 0.134900
  3903. # min 0.078441
  3904. # 25% 0.238487
  3905. # 50% 0.314088
  3906. # 75% 0.428571
  3907. # max 0.750653
  3908. n_drugs = len(np.unique(drug_all))
  3909. pm_varnames = []
  3910. with pm.Model() as hierarchical_model:
  3911. hp_drugclass = pm.Normal('hp_drugclass', mu=0., sigma=1, shape=n_drugs)
  3912. hp_drugclass_priors = list(np.zeros(n_studies))
  3913. for j_drug in range(n_drugs):
  3914. for k_study in np.unique(study_id_all[drug_all == j_drug]):
  3915. hp_drugclass_priors[k_study] = hp_drugclass[j_drug]
  3916. alpha_drugclass = pm.Normal('alpha_drugclass', mu=hp_drugclass_priors, sigma=1, shape=n_studies)
  3917. # hp_cond = pm.Normal('hp_cond', mu=0., sigma=1, shape=1)
  3918. # alpha_cond = pm.Normal('alpha_cond', mu=hp_cond, sigma=1, shape=2)
  3919. # alpha_cond = pm.Normal('alpha_cond', mu=0, sigma=1, shape=2)
  3920. # beta_cond = pm.Normal('beta_cond', mu=0, sigma=1)
  3921. #hp_beta = pm.Normal('hp_beta', mu=0., sigma=1, shape=1)
  3922. slope_betas = pm.Normal('slope_betas', mu=0, sigma=1, shape=1)
  3923. # beta_study_priors = list(np.zeros(n_studies))
  3924. # for j_drug in range(n_drugs):
  3925. # for k_study in np.unique(study_id_all[drug_all == j_drug]):
  3926. # beta_study_priors[k_study] = hp_beta[j_drug]
  3927. # beta_inter = pm.Normal('beta_inter_cond_drug', mu=beta_study_priors, sigma=2, shape=n_studies)
  3928. # reg_effect = alpha_cond[conds]
  3929. reg_effect = alpha_drugclass[study_id_all] + slope_betas * conds_all
  3930. eps = pm.HalfCauchy('eps', 5) # Model error
  3931. group_like = pm.Normal('beh_like', mu=reg_effect, sigma=eps, observed=y)
  3932. with hierarchical_model:
  3933. hierarchical_trace = pm.sample(draws=10000, n_init=5000, #init='advi',
  3934. chains=3, cores=9, progressbar=True,
  3935. random_seed=[1, 2, 3]) # one per chain needed
  3936. print(pm.summary(hierarchical_trace, hdi_prob=0.66))
  3937. OUT_DIR = '_results_uncorrected_data_pipelines_ana8'
  3938. output_name = 'net-THAD_HPinterc_effect_%s-%s_across' % (cur_net_name1, cur_net_name2)
  3939. t = hierarchical_trace
  3940. for cur_roi in hierarchical_model.named_vars:
  3941. from matplotlib.lines import Line2D
  3942. cur_roi = cur_roi
  3943. plt.close('all')
  3944. # THRESH = 0.5
  3945. # THRESH = 1.0
  3946. n_last_chains = 500
  3947. try:
  3948. suffix = ''
  3949. fig = arviz.plot_posterior(t, var_names=cur_roi, textsize=15.0,
  3950. hdi_prob=0.66)
  3951. # fig = pm.plot_posterior(t[-n_last_chains:], varnames=[cur_roi],
  3952. # credible_interval=0.95)
  3953. # try:
  3954. # for i_higher_cat in range(n_meta_cat):
  3955. # fig[i_higher_cat].set_xlim(-THRESH, THRESH) # make plots more comparable
  3956. # except:
  3957. # pass
  3958. plt.tight_layout()
  3959. plt.savefig('%s/%s_%s_posterior%s.png' % (OUT_DIR, output_name, cur_roi, suffix), dpi=150)
  3960. fig = arviz.plot_trace(t, var_names=[cur_roi])
  3961. # max_abs_mode = np.max(np.abs(hierarchical_trace2[-n_last_chains:][cur_roi].mean(0)))
  3962. # fig = pm.traceplot(t[-n_last_chains:], varnames=[cur_roi])
  3963. # max_abs_mode = np.max(np.abs(t[-n_last_chains:][cur_roi].mean(0)))
  3964. # fig[0][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3965. # try:
  3966. # fig[1][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3967. # except:
  3968. # pass
  3969. # try:
  3970. # if max_abs_mode < THRESH and not 'nuisance' in cur_roi:
  3971. # fig[0][0].set_xlim(-THRESH, THRESH) # make plots more comparable
  3972. # except:
  3973. # pass
  3974. # post_lines = fig[0][0].get_lines()
  3975. # custom_lines = [Line2D([0], [0], color=l.get_c(), lw=4) for l in post_lines]
  3976. # if subgroup_labels is None:
  3977. # subgroup_labels = ['subgroup %i' % i for i in range(len(custom_lines))]
  3978. # fig[0][0].legend(custom_lines, subgroup_labels, loc='upper left', prop={'size': 7.5})
  3979. plt.tight_layout()
  3980. plt.savefig('%s/%s_%s%s.png' % (OUT_DIR, output_name, cur_roi,
  3981. suffix), dpi=150)
  3982. # plt.savefig('%s/%s_%s.png' % (OUT_DIR, output_name, cur_roi), dpi=150)
  3983. except:
  3984. pass
  3985. # # average CCs by network (to stablize the estimates that we input into the BHM), HPinterc
  3986. # # net-GP
  3987. # In [22]: np.array(full_labels)[net_GP_labels > 0]
  3988. # Out[22]: array(['pGP-rh', 'aGP-rh', 'pGP-lh', 'aGP-lh'], dtype='<U36')
  3989. net_GP_labels = np.array([(s.find('GP') != -1) * 20 for s in full_labels])
  3990. for cur_net1 in np.unique(net17_labels):
  3991. for cur_net2 in np.unique(net_GP_labels):
  3992. if cur_net2 == 0:
  3993. continue
  3994. print('-' * 80)
  3995. cur_net_name1 = net17_label_names[cur_net1 - 1]
  3996. cur_net_name2 = 'GP'
  3997. print(cur_net_name1)
  3998. print('-- and --')
  3999. print(cur_net_name2)
  4000. net_inds1 = np.where(net17_labels == cur_net1)[0]
  4001. net_inds2 = np.where(net_GP_labels == cur_net2)[0]
  4002. y = CCs_all[:, net_inds1, :][:, :, net_inds2]
  4003. y = y.reshape((len(y), len(net_inds1)*len(net_inds2))).mean(1)
  4004. print(pd.DataFrame(y).describe())
  4005. # count 273.000000
  4006. # mean 0.340264
  4007. # std 0.134900
  4008. # min 0.078441
  4009. # 25% 0.238487
  4010. # 50% 0.314088
  4011. # 75% 0.428571
  4012. # max 0.750653
  4013. n_drugs = len(np.unique(drug_all))
  4014. pm_varnames = []
  4015. with pm.Model() as hierarchical_model:
  4016. hp_drugclass = pm.Normal('hp_drugclass', mu=0., sigma=1, shape=n_drugs)
  4017. hp_drugclass_priors = list(np.zeros(n_studies))
  4018. for j_drug in range(n_drugs):
  4019. for k_study in np.unique(study_id_all[drug_all == j_drug]):
  4020. hp_drugclass_priors[k_study] = hp_drugclass[j_drug]
  4021. alpha_drugclass = pm.Normal('alpha_drugclass', mu=hp_drugclass_priors, sigma=1, shape=n_studies)
  4022. # hp_cond = pm.Normal('hp_cond', mu=0., sigma=1, shape=1)
  4023. # alpha_cond = pm.Normal('alpha_cond', mu=hp_cond, sigma=1, shape=2)
  4024. # alpha_cond = pm.Normal('alpha_cond', mu=0, sigma=1, shape=2)
  4025. # beta_cond = pm.Normal('beta_cond', mu=0, sigma=1)
  4026. hp_beta = pm.Normal('hp_beta', mu=0., sigma=1, shape=1)
  4027. slope_betas = pm.Normal('slope_betas', mu=hp_beta, sigma=1, shape=n_drugs)
  4028. # beta_study_priors = list(np.zeros(n_studies))
  4029. # for j_drug in range(n_drugs):
  4030. # for k_study in np.unique(study_id_all[drug_all == j_drug]):
  4031. # beta_study_priors[k_study] = hp_beta[j_drug]
  4032. # beta_inter = pm.Normal('beta_inter_cond_drug', mu=beta_study_priors, sigma=2, shape=n_studies)
  4033. # reg_effect = alpha_cond[conds]
  4034. reg_effect = alpha_drugclass[study_id_all] + slope_betas[drug_all] * conds_all
  4035. eps = pm.HalfCauchy('eps', 5) # Model error
  4036. group_like = pm.Normal('beh_like', mu=reg_effect, sigma=eps, observed=y)
  4037. with hierarchical_model:
  4038. hierarchical_trace = pm.sample(draws=10000, n_init=5000, #init='advi',
  4039. chains=3, cores=9, progressbar=True,
  4040. random_seed=[1, 2, 3]) # one per chain needed
  4041. print(pm.summary(hierarchical_trace, hdi_prob=0.66))
  4042. OUT_DIR = '_results_uncorrected_data_pipelines_ana8'
  4043. output_name = 'net-GP_HPinterc_effect_%s-%s' % (cur_net_name1, cur_net_name2)
  4044. t = hierarchical_trace
  4045. for cur_roi in hierarchical_model.named_vars:
  4046. from matplotlib.lines import Line2D
  4047. cur_roi = cur_roi
  4048. plt.close('all')
  4049. # THRESH = 0.5
  4050. # THRESH = 1.0
  4051. n_last_chains = 500
  4052. try:
  4053. suffix = ''
  4054. fig = arviz.plot_posterior(t, var_names=cur_roi, textsize=15.0,
  4055. hdi_prob=0.66)
  4056. # fig = pm.plot_posterior(t[-n_last_chains:], varnames=[cur_roi],
  4057. #

ana8_uncorrected_data_pipelines_250820_NM.py at commit 0c58406, no license · at the source

Overview

Authors: Manesh Girn1, Manoj K Doss2, Leor Roseman3, Katrin H Preller4, Fernanda Palhano-Fontes5, Lorenzo Pasquini1, Frederick S Barrett6, Pablo Mallaroni7, Natasha L Mason7, Christopher Timmermann3, Drummond E McCulloch8, Patrick M Fisher8, Brian S Winston6, Flora Moujaes4, Felix Muller9, Matthias E Liechti9, Franz X Vollenweider4, Johannes G Ramaekers7, Kim Kuypers7, Draulio B Araujo5
and 7 other authorsOlaf Sporns10, Joshua Siegel11, Nico Dosenbach11, David J Nutt3, Robin L Carhart-Harris1, Emmanuel A Stamatakis12, Danilo Bzdok13,14
14 affiliations
  1. Department of Neurology, University of California San Francisco, San Francisco, CA USA
  2. Department of Psychiatry and Behavioral Sciences, Center for Psychedelic Research and Therapy, The University of Texas at Austin Dell Medical School, Austin, TX USA
  3. Department of Psychology, University of Exeter, Exeter, UK
  4. Department of Adult Psychiatry and Psychotherapy, University of Zurich, Zurich, Switzerland
  5. Brain Institute, Universidade Federal do Rio Grande do Norte, Natal, Brazil
  6. Center for Psychedelic and Consciousness Research, Johns Hopkins University School of Medicine, Baltimore, MD USA
  7. Department of Neuropsychology and Psychopharmacology, Faculty of Psychology and Neuroscience, Maastricht University, Maastricht, the Netherlands
  8. Neurobiology Research Unit, Rigshospitalet, Copenhagen, Denmark
  9. Department of Clinical Research, Clinical Pharmacology, University Hospital Basel, University of Basel, Basel, Switzerland
  10. Department of Psychological and Brain Sciences, Indiana University, Bloomington, IN USA
  11. Department of Psychiatry, NYU Langone Center for Psychedelic Medicine, NYU Grossman School of Medicine, New York, NY USA
  12. Division of Anaesthesia and Department of Clinical Neurosciences, University of Cambridge, Cambridge, UK
  13. Department of Biomedical Engineering, The Neuro - Montreal Neurological Institute (MNI), McConnell Brain Imaging Centre (BIC), McGill University, Montreal, Quebec Canada
  14. Mila - Quebec Artificial Intelligence Institute, Montreal, Quebec Canada
Journal: Nature medicine, volume 32, issue 4, pages 1543-1554
Dates: received 25 March 2025; accepted 12 February 2026; published online 6 April 2026; in print 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s41591-026-04287-9 · PMID 41942645 · PMCID PMC13099416 · OpenAlex W7150978140
Open access: hybrid, a free copy (OpenAlex)
Status: code verified
Categories: fMRI (modality), human (organism), systems (subfield)
Methods: Connectivity, Smoothing, state filtering, decompositions, fMRI & imaging
Keywords: Computational biology and bioinformatics, Medical research
MeSH: Brain*, Hallucinogens*, Nerve Net*, Banisteriopsis, Bayes Theorem, Brain Mapping, Humans, Lysergic Acid Diethylamide, Magnetic Resonance Imaging, N,N-Dimethyltryptamine, Psilocybin (* major topic)
Topic: Psychedelics and Drug Studies (Clinical Psychology, Psychology), according to OpenAlex
Funding: NIA NIH HHS (T32 AG027668)
Citations: cited by 12 papers (Europe PMC); 67 references in the paper

Abstract

The abstract is not reproduced here: the paper's license (CC BY-NC-ND) does not allow it. Read it in the paper, at the publisher or on Europe PMC.

Repository

Its files are read in the Code ↔ Paper reader above, with 2 matches between paragraphs and lines of code.

banilo/BOLD_psychedelics_consortium

License: none: the authors keep all their rights
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Commit: 0c5840620e54026734f9035a6d49ad54ef46d9a4, 11 December 2025
Languages: Python (1)
Size: 12,692 files, 1 script
Software Heritage: not archived
Found in: “Code availability”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: ArviZ (1 file), Matplotlib (1 file), NiBabel (1 file), Nilearn (1 file), NumPy (1 file), pandas (1 file), PyMC (1 file), scikit-learn (1 file), SciPy (1 file), seaborn (1 file)
Availability: 1 check, the latest on 29 September 2026: the link answers
  • 29 September 2026: the link answers
2 files

Code availability statement

The paper has a code availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

Read it in the paper: doi.org/10.1038/s41591-026-04287-9.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 1 script, each with its path and the digest of its content;
  • 2 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data availability statement

The paper has a data availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

  • no repository, dataset or request procedure was recognized in it

Read it in the paper: doi.org/10.1038/s41591-026-04287-9.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 29 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 27 authors, 2 keywords, 11 MeSH terms, 1 funder, 64 references.

Cite

This paper

Girn, M., Doss, M. K., Roseman, L., Preller, K. H., Palhano-Fontes, F., Pasquini, L., Barrett, F. S., Mallaroni, P., Mason, N. L., Timmermann, C., McCulloch, D. E., Fisher, P. M., Winston, B. S., Moujaes, F., Muller, F., Liechti, M. E., Vollenweider, F. X., Ramaekers, J. G., Kuypers, K., . . . Bzdok, D. (2026). An international mega-analysis of psychedelic drug effects on brain circuit function. Nature medicine, 32(4), 1543-1554. https://doi.org/10.1038/s41591-026-04287-9

BibTeX

@article{girn2026international,
author = {Girn, Manesh and Doss, Manoj K and Roseman, Leor and Preller, Katrin H and Palhano-Fontes, Fernanda and Pasquini, Lorenzo and Barrett, Frederick S and Mallaroni, Pablo and Mason, Natasha L and Timmermann, Christopher and McCulloch, Drummond E and Fisher, Patrick M and Winston, Brian S and Moujaes, Flora and Muller, Felix and Liechti, Matthias E and Vollenweider, Franz X and Ramaekers, Johannes G and Kuypers, Kim and Araujo, Draulio B and Sporns, Olaf and Siegel, Joshua and Dosenbach, Nico and Nutt, David J and Carhart-Harris, Robin L and Stamatakis, Emmanuel A and Bzdok, Danilo},
title = {{An international mega-analysis of psychedelic drug effects on brain circuit function}},
journal = {Nature medicine},
year = {2026},
month = apr,
volume = {32},
number = {4},
pages = {1543--1554},
publisher = {Nature Portfolio},
issn = {1078-8956},
doi = {10.1038/s41591-026-04287-9},
url = {https://doi.org/10.1038/s41591-026-04287-9},
pmid = {41942645},
pmcid = {PMC13099416}
}

RIS

TY - JOUR
AU - Girn, Manesh
AU - Doss, Manoj K
AU - Roseman, Leor
AU - Preller, Katrin H
AU - Palhano-Fontes, Fernanda
AU - Pasquini, Lorenzo
AU - Barrett, Frederick S
AU - Mallaroni, Pablo
AU - Mason, Natasha L
AU - Timmermann, Christopher
AU - McCulloch, Drummond E
AU - Fisher, Patrick M
AU - Winston, Brian S
AU - Moujaes, Flora
AU - Muller, Felix
AU - Liechti, Matthias E
AU - Vollenweider, Franz X
AU - Ramaekers, Johannes G
AU - Kuypers, Kim
AU - Araujo, Draulio B
AU - Sporns, Olaf
AU - Siegel, Joshua
AU - Dosenbach, Nico
AU - Nutt, David J
AU - Carhart-Harris, Robin L
AU - Stamatakis, Emmanuel A
AU - Bzdok, Danilo
TI - An international mega-analysis of psychedelic drug effects on brain circuit function
T2 - Nature medicine
J2 - Nat Med
PY - 2026
DA - 2026/04/06
VL - 32
IS - 4
SP - 1543
EP - 1554
SN - 1078-8956
PB - Nature Portfolio
DO - 10.1038/s41591-026-04287-9
UR - https://doi.org/10.1038/s41591-026-04287-9
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41591-026-04287-9",
"type": "article-journal",
"title": "An international mega-analysis of psychedelic drug effects on brain circuit function",
"container-title": "Nature medicine",
"author": [
{
"family": "Girn",
"given": "Manesh"
},
{
"family": "Doss",
"given": "Manoj K"
},
{
"family": "Roseman",
"given": "Leor"
},
{
"family": "Preller",
"given": "Katrin H"
},
{
"family": "Palhano-Fontes",
"given": "Fernanda"
},
{
"family": "Pasquini",
"given": "Lorenzo"
},
{
"family": "Barrett",
"given": "Frederick S"
},
{
"family": "Mallaroni",
"given": "Pablo"
},
{
"family": "Mason",
"given": "Natasha L"
},
{
"family": "Timmermann",
"given": "Christopher"
},
{
"family": "McCulloch",
"given": "Drummond E"
},
{
"family": "Fisher",
"given": "Patrick M"
},
{
"family": "Winston",
"given": "Brian S"
},
{
"family": "Moujaes",
"given": "Flora"
},
{
"family": "Muller",
"given": "Felix"
},
{
"family": "Liechti",
"given": "Matthias E"
},
{
"family": "Vollenweider",
"given": "Franz X"
},
{
"family": "Ramaekers",
"given": "Johannes G"
},
{
"family": "Kuypers",
"given": "Kim"
},
{
"family": "Araujo",
"given": "Draulio B"
},
{
"family": "Sporns",
"given": "Olaf"
},
{
"family": "Siegel",
"given": "Joshua"
},
{
"family": "Dosenbach",
"given": "Nico"
},
{
"family": "Nutt",
"given": "David J"
},
{
"family": "Carhart-Harris",
"given": "Robin L"
},
{
"family": "Stamatakis",
"given": "Emmanuel A"
},
{
"family": "Bzdok",
"given": "Danilo"
}
],
"container-title-short": "Nat Med",
"volume": "32",
"issue": "4",
"page": "1543-1554",
"DOI": "10.1038/s41591-026-04287-9",
"PMID": "41942645",
"PMCID": "PMC13099416",
"ISSN": "1078-8956",
"publisher": "Nature Portfolio",
"URL": "https://doi.org/10.1038/s41591-026-04287-9",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
6
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s41586-026-10910-z [code]
Psychedelics align brain activity with context.
Journal: Nature
In common: NiBabel, SciPy, NumPy, fMRI, 16 references, 2 authors
[2] doi:10.1038/s41467-026-74215-5 [code]
Multi-metric evaluations of acute psychedelic effects on fMRI brain entropy.
Journal: Nature communications
In common: scikit-learn, SciPy, Matplotlib, 1 other tool, fMRI, 15 references, author Drummond E-Wen McCulloch
[3] doi:10.1002/hbm.70596 [code]
Modeled Long-Term Effects of Psilocybin on Dynamic Activity and Effective Connectivity of Fronto-Striatal-Thalamic Circuits.
Journal: Human brain mapping
In common: systems, 10 references, author David J Nutt
[4] doi:10.1162/imag.a.1262 [code]
Frame-wise multi-echo distortion correction for superior functional MRI.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: Nilearn, NiBabel, seaborn, 4 other tools, fMRI, 4 references, author Nico UF Dosenbach
[5] doi:10.1371/journal.pbio.3003684 [code]
The retrieval of previously learned motor memories is facilitated by the reinstatement of default mode network manifold structures.
Journal: PLoS biology
In common: Nilearn, NiBabel, seaborn, 5 other tools, fMRI, 7 references
[6] doi:10.1162/netn.a.547 [code]
An evaluation of the efficacy of single-echo and multi-echo fMRI denoising strategies.
Journal: Network neuroscience (Cambridge, Mass.)
In common: Nilearn, NiBabel, seaborn, 5 other tools, fMRI, 6 references
[7] doi:10.1038/s41467-026-75959-w [code]
Charting higher-order models of brain function beyond pairwise interactions.
Journal: Nature communications
In common: Nilearn, NiBabel, seaborn, 5 other tools, 6 references
[8] doi:10.1162/imag.a.1269 [code]
From early to contemporary normative modeling: Mapping individual differences in neurophysiological signals.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: ArviZ, PyMC, Nilearn, 7 other tools, 1 reference
[9] doi:10.1038/s41467-026-72940-5 [code]
Cerebellar growth is associated with domain-specific cerebral maturation and socio-linguistic behavior.
Journal: Nature communications
In common: ArviZ, PyMC, NiBabel, 6 other tools, 2 references
[10] doi:10.21203/rs.3.rs-9326213/v1 [code]
Multi-task fMRI outperforms resting-state fMRI for revealing task-invariant organization of the human brain
Journal: Research Square (preprint)
In common: Nilearn, NiBabel, seaborn, 5 other tools, fMRI, 5 references

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.