OSCR

Mind the brain age: How segmentation and template selection reshape structural connectomes.

Code ↔ Paper

16 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 16 matches · 2 of them tie a paragraph to a whole file without given lines: weak matches, whose lines are not tinted
  1. [1] § Materials and Methods › Tractography pipeline ↔ src/Preprocess_your_images/pre_processing_pipeline_ADNI.sh, lines 309 to 364 · score 0.90 · dwi2fod, dwi2response, msmt_csd, brain mask, FODs, dhollander · Report a mismatch
  2. [2] § Results › Pipeline-dependent associations ↔ src/Analyze_your_connectomes/results.ipynb, lines 456 to 579 · score 0.80 · ATR MED ACT, ATR LOW ACT, global efficiency, Assigned streamlines, FAST ACT, WMH ACT · Report a mismatch
  3. [3] § Results › Pipeline-dependent associations ↔ src/Analyze_your_connectomes/results.ipynb, lines 456 to 579 · score 0.79 · MoCA, global efficiency, assigned streamlines, FAST ACT, WMH ACT, scatter · Report a mismatch
  4. [4] § Materials and Methods › Image preprocessing › Anatomical MRI preprocessing ↔ src/Preprocess_your_images/pre_processing_pipeline_ADNI.sh, lines 53 to 132 · score 0.79 · antsRegistration, DWI volumes, template space, MI, FSL, rigid · Report a mismatch
  5. [5] § Materials and Methods › Tractography pipeline ↔ src/Generate_your_connectomes/tractography_analysis_ADNI.sh, lines 91 to 162 · score 0.79 · iFOD2, brain mask, MRtrix, backtracking, tckgen, tcksift2 · Report a mismatch
  6. [6] § Materials and Methods › Image preprocessing › Diffusion MRI preprocessing ↔ src/Preprocess_your_images/pre_processing_pipeline_ADNI.sh, lines 53 to 132 · score 0.72 · MP PCA, brain mask, MRtrix3, ANTs, FSL, preprocessing · Report a mismatch
  7. [7] § Results › Global network properties ↔ src/Analyze_your_connectomes/results.ipynb, lines 187 to 257 · score 0.68 · global efficiency, assigned streamlines, FAST ACT, WMH ACT, S2, density · Report a mismatch
  8. [8] § Materials and Methods › Connectome construction and graph-theoretical analysis ↔ src/Generate_your_connectomes/tractography_analysis_ADNI.sh, lines 1 to 52 · score 0.67 · MRtrix3, Tian, Schaefer, S1, parcellations, subcortical · Report a mismatch
  9. [9] § Materials and Methods › Statistical analysis ↔ Anima/math-tools/statistical_tests/animaFDRCorrection.h, the whole file · a weak match · score 0.67 · Benjamini Hochberg, discovery rate, FDR, thresholds · Report a mismatch
  10. [10] § Materials and Methods › Data › MRI procedure ↔ Anima/quantitative-mri/mr-simulation/stimulated_spin_echo_simulator/animaStimulatedSpinEchoImageFilter.h, lines 10 to 76 · score 0.64 · spin echo, flip angle, MRI · Report a mismatch
  11. [11] § Materials and Methods › Connectome construction and graph-theoretical analysis ↔ src/Preprocess_your_images/pre_processing_pipeline_ADNI.sh, lines 1 to 50 · score 0.63 · MRtrix3, Tian, S1, parcellations, subcortical, T1w · Report a mismatch
  12. [12] § Materials and Methods › Experimental conditions ↔ src/Generate_your_connectomes/tractography_analysis_ADNI.sh, lines 91 to 162 · score 0.62 · TT image, template space, FSL, CSF, tractography, T1w · Report a mismatch
  13. [13] § Materials and Methods › Statistical analysis ↔ src/Analyze_your_connectomes/extract_connectome_metrics.py, lines 109 to 132 · score 0.62 · Pearson correlation coefficients, connectome metrics, global · Report a mismatch
  14. [14] § Results › Template effect on nodal network properties ↔ src/Analyze_your_connectomes/results.ipynb, lines 1249 to 1293 · score 0.62 · local efficiency, FAST ACT, WMH ACT, nodal, subcortical, clustering · Report a mismatch
  15. [15] § Materials and Methods › Statistical analysis ↔ src/Analyze_your_connectomes/results.ipynb, lines 604 to 670 · score 0.57 · connectome metrics, Pearson, sex, MMSE, MoCA, Age · Report a mismatch
  16. [16] § Materials and Methods › Statistical analysis ↔ Anima/math-tools/statistical_tests/animaFDRCorrection.h, the whole file · a weak match · score 0.51 · Benjamini Hochberg FDR · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Jupyter notebook · 1,572 lines · 51 KB · MIT · 5 matches

  1. # %%
  2. path_to_metrics= #path to the metrics csv file
  3. save_directory= #path to the directory where you want to save the results
  4. path_to_clin= #path to the clinical data excel file
  5. path_to_parcellation= #path to the parcellation txt/csv file
  6. base_dir = #path to the base directory where the rconnectivity matrices are stored
  7. # %%
  8. import os
  9. import re
  10. import glob
  11. import numpy as np
  12. import pandas as pd
  13. input_csv = os.path.join(path_to_metrics, "connectome_no_density_metrics_global.csv")
  14. output_csv = os.path.join(path_to_metrics, "connectome_no_density_metrics_global_with_assigned_streamlines_new.csv")
  15. technique_mapping = {
  16. "20": "ATR-LOW-ACT",
  17. "35": "ATR-MED-ACT",
  18. "50": "ATR-HIGH-ACT",
  19. "act": "FAST-ACT",
  20. "no_act": "NOACT",
  21. "noact": "NOACT",
  22. "freesurfer": "WMH-ACT",
  23. }
  24. template_mapping = {
  25. "MNI152NLin2009cAsym": "MNI",
  26. "MNI": "MNI",
  27. "MIITRA-MIITRA": "MIITRA",
  28. "MIITRA": "MIITRA",
  29. }
  30. def normalize_excelid(x):
  31. if pd.isna(x):
  32. return np.nan
  33. x = str(x).strip().upper()
  34. x = x.replace("sub-", "").replace("SUB-", "")
  35. x = x.replace("_", "").replace("-", "").replace("S", "_S_")
  36. x = re.sub(r"\.0$", "", x)
  37. return x
  38. def normalize_template(x):
  39. if pd.isna(x):
  40. return np.nan
  41. x = str(x).strip()
  42. return template_mapping.get(x, x)
  43. def normalize_technique(x):
  44. if pd.isna(x):
  45. return np.nan
  46. x = str(x).strip()
  47. return technique_mapping.get(x, x)
  48. def parse_connectome_filename(fname):
  49. base = os.path.basename(fname)
  50. m = re.match(
  51. r"^connectome_10M_(?P<raw_pipeline_id>.+?)_(?P<raw_template>MNI152NLin2009cAsym|MNI|MIITRA)_unassigned\.txt$",
  52. base
  53. )
  54. if m is None:
  55. return None
  56. raw_pipeline_id = m.group("raw_pipeline_id")
  57. raw_template = m.group("raw_template")
  58. if raw_template in ["MNI152NLin2009cAsym", "MNI"]:
  59. template = "MNI"
  60. else:
  61. template = "MIITRA"
  62. return {
  63. "raw_pipeline_id": raw_pipeline_id,
  64. "technique": normalize_technique(raw_pipeline_id),
  65. "raw_template": raw_template,
  66. "template": template,
  67. }
  68. def compute_assigned_streamlines(txt_file):
  69. M = np.loadtxt(txt_file)
  70. if M.ndim == 1:
  71. M = np.atleast_2d(M)
  72. return float(M[1:, 1:].sum())
  73. df_metrics = pd.read_csv(input_csv).copy()
  74. if "sparsity" not in df_metrics.columns:
  75. raise KeyError("La colonna 'sparsity' non è presente nel CSV.")
  76. df_metrics["sparsity"] = pd.to_numeric(df_metrics["sparsity"], errors="coerce") * 100
  77. if "assigned_streamlines" in df_metrics.columns:
  78. df_metrics = df_metrics.drop(columns=["assigned_streamlines"])
  79. required_cols = ["excel_id", "template", "technique"]
  80. missing_cols = [c for c in required_cols if c not in df_metrics.columns]
  81. if missing_cols:
  82. raise KeyError(f"Mancano queste colonne nel CSV: {missing_cols}")
  83. df_metrics["excelid_merge"] = df_metrics["excel_id"].map(normalize_excelid)
  84. df_metrics["template_merge"] = df_metrics["template"].map(normalize_template)
  85. df_metrics["technique_merge"] = df_metrics["technique"].map(normalize_technique)
  86. txt_files = glob.glob(os.path.join(base_dir, "sub-*", "dwi", "connectome_10M_*unassigned.txt"))
  87. rows = []
  88. for f in sorted(txt_files):
  89. subject_id = os.path.basename(os.path.dirname(os.path.dirname(f)))
  90. meta = parse_connectome_filename(f)
  91. if meta is None:
  92. continue
  93. rows.append({
  94. "excelid_merge": normalize_excelid(subject_id),
  95. "template_merge": meta["template"],
  96. "technique_merge": meta["technique"],
  97. "assigned_streamlines": compute_assigned_streamlines(f) / 100000,
  98. })
  99. df_assigned = pd.DataFrame(rows)
  100. df_assigned = df_assigned.drop_duplicates(
  101. subset=["excelid_merge", "template_merge", "technique_merge"]
  102. )
  103. df_metrics = df_metrics.merge(
  104. df_assigned,
  105. on=["excelid_merge", "template_merge", "technique_merge"],
  106. how="left"
  107. )
  108. df_metrics = df_metrics.drop(columns=["excelid_merge", "template_merge", "technique_merge"])
  109. df_metrics.to_csv(output_csv, index=False)
  110. display_cols = [
  111. c for c in [
  112. "excel_id", "folder_id", "template", "technique",
  113. "assigned_streamlines", "sparsity"
  114. ] if c in df_metrics.columns
  115. ]
  116. print(df_metrics[display_cols].head())
  117. print(f"Saved: {output_csv}")
  118. # %%
  119. import pandas as pd
  120. import seaborn as sns
  121. import matplotlib.pyplot as plt
  122. import matplotlib.font_manager as fm
  123. import numpy as np
  124. from scipy.stats import ttest_ind,ttest_rel,shapiro,wilcoxon
  125. available_fonts = [f.name for f in fm.fontManager.ttflist]
  126. print("Font available:")
  127. for font in sorted([f for f in available_fonts if "Comic" in f or "Impact" in f or "Courier" in f]):
  128. print(f"- {font}")
  129. sns.set(style="whitegrid", font_scale=1.1)
  130. plt.rcParams['font.family'] = 'sans-serif'
  131. plt.rcParams['font.sans-serif'] = ['Arial', 'Comic Sans MS', 'Impact', 'Courier New']
  132. plt.rcParams['font.size'] = 12
  133. plt.rcParams['axes.titlesize'] = 30
  134. plt.rcParams['axes.labelsize'] = 10
  135. sns.set(font='Arial')
  136. plt.figure(figsize=(6, 2))
  137. plt.text(0.5, 0.5, "Test Font - ABCDEFG 123",
  138. ha='center', va='center', fontsize=14)
  139. plt.axis('off')
  140. plt.tight_layout()
  141. plt.show()
  142. # %%
  143. # ===== BOXPLOT with FDR correction + paired lines =====
  144. #Figure 3 and S2
  145. from statsmodels.stats.multitest import fdrcorrection
  146. import matplotlib as mpl
  147. import matplotlib.pyplot as plt
  148. import os
  149. import pandas as pd
  150. import seaborn as sns
  151. import numpy as np
  152. from scipy.stats import ttest_rel, wilcoxon, shapiro
  153. mpl.rcParams["font.family"] = "Arial"
  154. plt.style.use("seaborn-v0_8-whitegrid")
  155. font_to_use = "Arial"
  156. df = pd.read_csv(os.path.join(path_to_metrics, "connectome_no_density_metrics_global_with_assigned_streamlines_new.csv")).copy()
  157. all_results = []
  158. output_dir = os.path.join(save_directory, "boxplots")
  159. os.makedirs(output_dir, exist_ok=True)
  160. metrics = [
  161. "sparsity",
  162. "mean_connectivity",
  163. "assortativity",
  164. "avg_clustering",
  165. "global_efficiency",
  166. "avg_shortest_path",
  167. "transitivity",
  168. "assigned_streamlines",
  169. ]
  170. technique_mapping = {
  171. "20": "ATR-LOW-ACT",
  172. "35": "ATR-MED-ACT",
  173. "50": "ATR-HIGH-ACT",
  174. "act": "FAST-ACT",
  175. "freesurfer": "WMH-ACT",
  176. "no_act": "NOACT",
  177. "noact": "NOACT"
  178. }
  179. template_mapping = {
  180. "MNI152NLin2009cAsym": "MNI",
  181. "MNI": "MNI",
  182. "MIITRA-MIITRA": "MIITRA",
  183. "MIITRA": "MIITRA"
  184. }
  185. technique_order = [
  186. "FAST-ACT",
  187. "ATR-LOW-ACT",
  188. "ATR-MED-ACT",
  189. "ATR-HIGH-ACT",
  190. "WMH-ACT",
  191. "NOACT"
  192. ]
  193. template_order = ["MIITRA", "MNI"]
  194. df["technique"] = df["technique"].astype(str).map(technique_mapping).fillna(df["technique"].astype(str))
  195. df["template"] = df["template"].astype(str).map(template_mapping).fillna(df["template"].astype(str))
  196. df = df[df["technique"].isin(technique_order)].copy()
  197. df = df[df["template"].isin(template_order)].copy()
  198. df["technique"] = pd.Categorical(df["technique"], categories=technique_order, ordered=True)
  199. df["template"] = pd.Categorical(df["template"], categories=template_order, ordered=True)
  200. techniques = [t for t in technique_order if t in df["technique"].dropna().unique()]
  201. templates = template_order
  202. # ===== raw p-values =====
  203. for metric in metrics:
  204. for i, tech in enumerate(techniques):
  205. group = df[df["technique"] == tech]
  206. template_data = {}
  207. subjects = []
  208. for template in templates:
  209. template_group = group[group["template"] == template]
  210. template_data[template] = template_group.set_index("excel_id")[metric]
  211. subjects.append(set(template_group["excel_id"]))
  212. if len(subjects) < 2:
  213. continue
  214. common_subjects = list(subjects[0].intersection(subjects[1]))
  215. if len(common_subjects) > 1:
  216. data1 = pd.to_numeric(template_data[templates[0]].loc[common_subjects], errors="coerce").values
  217. data2 = pd.to_numeric(template_data[templates[1]].loc[common_subjects], errors="coerce").values
  218. valid = np.isfinite(data1) & np.isfinite(data2)
  219. data1 = data1[valid]
  220. data2 = data2[valid]
  221. if len(data1) > 1:
  222. diff = data1 - data2
  223. _, norm_p = shapiro(diff)
  224. if norm_p > 0.05:
  225. _, p_val = ttest_rel(data1, data2)
  226. test_type = "paired t-test"
  227. else:
  228. try:
  229. _, p_val = wilcoxon(data1, data2)
  230. except ValueError:
  231. p_val = np.nan
  232. test_type = "Wilcoxon test"
  233. print(f"Using {test_type} for {tech} on {metric} with p_raw={p_val:.4f}")
  234. all_results.append((metric, tech, p_val, i, test_type))
  235. # ===== Global FDR correction =====
  236. valid_results = [(m, t, p, pos, test_type) for (m, t, p, pos, test_type) in all_results if pd.notna(p)]
  237. raw_pvals = [p for (_, _, p, _, _) in valid_results]
  238. reject, pvals_corrected = fdrcorrection(raw_pvals, alpha=0.05, method='indep')
  239. corrected_dict = {}
  240. for (m, t, p_raw, pos, test_type), p_corr, rej in zip(valid_results, pvals_corrected, reject):
  241. corrected_dict[(m, t)] = (p_raw, p_corr, rej, pos, test_type)
  242. df_pvalues = pd.DataFrame([
  243. (m, t, test_type, p_raw, p_corr, rej, pos)
  244. for (m, t, p_raw, pos, test_type), p_corr, rej in zip(valid_results, pvals_corrected, reject)
  245. ], columns=["metric", "technique", "test_type", "p_raw", "p_corr", "significant", "pos"])
  246. df_pvalues.to_csv(os.path.join(output_dir, "pvalues_corrected_global.csv"), index=False)
  247. # ===== Plotting =====
  248. for metric in metrics:
  249. plt.figure(figsize=(10, 6))
  250. ax = sns.boxplot(
  251. data=df,
  252. x="technique",
  253. y=metric,
  254. hue="template",
  255. order=technique_order,
  256. hue_order=template_order,
  257. palette="rocket",
  258. showfliers=False,
  259. boxprops=dict(facecolor="None", linewidth=1.2),
  260. whiskerprops=dict(linewidth=1.2),
  261. capprops=dict(linewidth=1.2),
  262. medianprops=dict(linewidth=1.4),
  263. )
  264. sns.stripplot(
  265. data=df,
  266. x="technique",
  267. y=metric,
  268. hue="template",
  269. order=technique_order,
  270. hue_order=template_order,
  271. dodge=True,
  272. jitter=0.12,
  273. size=3.2,
  274. alpha=0.65,
  275. palette="rocket",
  276. edgecolor="none",
  277. linewidth=0,
  278. ax=ax,
  279. zorder=2
  280. )
  281. # paired lines
  282. box_width = 0.8
  283. n_hue = len(template_order)
  284. offsets = np.linspace(-box_width/4, box_width/4, n_hue)
  285. for i, tech in enumerate(techniques):
  286. group = df[df["technique"] == tech].copy()
  287. wide = group.pivot_table(
  288. index="excel_id",
  289. columns="template",
  290. values=metric,
  291. aggfunc="first"
  292. )
  293. if all(t in wide.columns for t in template_order):
  294. wide = wide.dropna(subset=template_order)
  295. x1 = i + offsets[0]
  296. x2 = i + offsets[1]
  297. for _, row in wide.iterrows():
  298. ax.plot(
  299. [x1, x2],
  300. [row[template_order[0]], row[template_order[1]]],
  301. color="gray",
  302. alpha=0.20,
  303. linewidth=0.7,
  304. zorder=1
  305. )
  306. # remove duplicated legend due to stripplot overlay
  307. handles, labels = ax.get_legend_handles_labels()
  308. if len(handles) >= 2:
  309. ax.legend_.remove()
  310. y_min, y_max = ax.get_ylim()
  311. max_box_height = float('-inf')
  312. for i, tech in enumerate(techniques):
  313. group = df[df["technique"] == tech]
  314. for template in templates:
  315. data = group[group["template"] == template][metric].dropna()
  316. if len(data) > 1:
  317. q1, q3 = np.percentile(data, [25, 75])
  318. iqr = q3 - q1
  319. upper_whisker = min(data.max(), q3 + 1.5 * iqr)
  320. max_box_height = max(max_box_height, upper_whisker)
  321. if not np.isfinite(max_box_height):
  322. max_box_height = y_max
  323. spacing = (y_max - y_min) * 0.02
  324. bar_height = min(max_box_height + spacing, y_max)
  325. text_height = bar_height + spacing
  326. for i, tech in enumerate(techniques):
  327. key = (metric, tech)
  328. if key in corrected_dict:
  329. p_raw, p_corr, rej, pos, test_type = corrected_dict[key]
  330. if rej:
  331. ax.plot([pos-0.2, pos+0.2], [bar_height, bar_height], 'k-', linewidth=1.5)
  332. if p_corr < 0.001:
  333. significance = "§"
  334. elif p_corr < 0.01:
  335. significance = "‡"
  336. else:
  337. significance = "†"
  338. ax.text(
  339. pos, text_height, significance,
  340. ha="center", va="bottom",
  341. fontsize=14, fontname=font_to_use
  342. )
  343. ax.set_ylim(y_min, max_box_height + (y_max - y_min) * 0.1)
  344. plt.xlabel("Pipeline", fontsize=14, fontname=font_to_use)
  345. plt.ylabel(metric.replace("_", " ").capitalize(), fontsize=14, fontname=font_to_use)
  346. plt.xticks(rotation=25, ha='right', fontsize=9, fontname=font_to_use)
  347. labels = ax.get_xticklabels()
  348. plt.setp(labels, ha="center", rotation_mode="anchor", position=(0, -0.05))
  349. # single legend
  350. if metric == "sparsity":
  351. legend_handles = handles[:2]
  352. legend_labels = labels[:2]
  353. lg = ax.legend(legend_handles, legend_labels, title="Template")
  354. plt.setp(lg.get_title(), fontname=font_to_use)
  355. plt.setp(lg.get_texts(), fontname=font_to_use)
  356. else:
  357. lg = ax.get_legend()
  358. if lg is not None:
  359. lg.remove()
  360. plt.tight_layout()
  361. outpath = os.path.join(output_dir, f"{metric}_boxplot.png")
  362. plt.savefig(outpath, dpi=300, bbox_inches="tight")
  363. plt.close()
  364. # %%
  365. # ===== SCATTERPLOTS =====
  366. # Figure 4a and Figures S3a-S6a
  367. import os, re
  368. from scipy.stats import pearsonr
  369. import numpy as np
  370. import matplotlib as mpl
  371. import matplotlib.pyplot as plt
  372. import seaborn as sns
  373. import pandas as pd
  374. mpl.rcParams["font.family"] = "Arial"
  375. plt.style.use("seaborn-v0_8-whitegrid")
  376. df_conn = #data frame containing the connectome metrics
  377. df_clin = #data frame containing the clinical data
  378. # Merge su excel_id / Subject
  379. df = pd.merge(df_conn, df_clin, left_on="excel_id", right_on="Subject")
  380. technique_mapping = {
  381. "20": "ATR-LOW-ACT",
  382. "35": "ATR-MED-ACT",
  383. "50": "ATR-HIGH-ACT",
  384. "act": "FAST-ACT",
  385. "freesurfer": "WMH-ACT",
  386. "no_act": "NOACT",
  387. "noact": "NOACT"
  388. }
  389. template_mapping = {
  390. "MNI152NLin2009cAsym": "MNI",
  391. "MNI": "MNI",
  392. "MIITRA-MIITRA": "MIITRA",
  393. "MIITRA": "MIITRA"
  394. }
  395. technique_order = [
  396. "FAST-ACT",
  397. "ATR-LOW-ACT",
  398. "ATR-MED-ACT",
  399. "ATR-HIGH-ACT",
  400. "WMH-ACT",
  401. "NOACT"
  402. ]
  403. template_order = ["MIITRA", "MNI"]
  404. df["technique"] = df["technique"].astype(str).map(technique_mapping).fillna(df["technique"].astype(str))
  405. df["template"] = df["template"].astype(str).map(template_mapping).fillna(df["template"].astype(str))
  406. df = df[df["technique"].isin(technique_order)].copy()
  407. df = df[df["template"].isin(template_order)].copy()
  408. df["technique"] = pd.Categorical(df["technique"], categories=technique_order, ordered=True)
  409. df["template"] = pd.Categorical(df["template"], categories=template_order, ordered=True)
  410. metrics = [
  411. "sparsity", "mean_connectivity", "assortativity", "avg_clustering",
  412. "global_efficiency", "avg_shortest_path", "transitivity","assigned_streamlines",
  413. ]
  414. clinical_vars = ["WMH_WM", "PET_CENTILOID", "MMSE", "MOCA"]
  415. clinical_vars_mapping = {
  416. "WMH_WM": "WMHB (%)",
  417. "PET_CENTILOID": "Amyloid PET Centiloid",
  418. "MMSE": "MMSE Score",
  419. "MOCA": "MoCA Score"
  420. }
  421. palette = dict(zip(technique_order, sns.color_palette("tab10", n_colors=len(technique_order))))
  422. output_dir = os.path.join(save_directory, "scatterplots")
  423. os.makedirs(output_dir, exist_ok=True)
  424. for metric in metrics:
  425. for clinical_var in clinical_vars:
  426. display_clin = clinical_vars_mapping.get(clinical_var, clinical_var)
  427. safe_display = re.sub(r"[^A-Za-z0-9_-]+", "_", display_clin).strip("_")
  428. for template in template_order:
  429. subset_template = df[df["template"] == template].copy()
  430. if subset_template.empty:
  431. continue
  432. plt.figure(figsize=(10, 6))
  433. plt.title(f"{template}", fontsize=20)
  434. plt.xlabel(display_clin, fontsize=16)
  435. plt.ylabel(metric.replace("_", " ").capitalize(), fontsize=16)
  436. handles, labels = [], []
  437. for tech in technique_order:
  438. subset = subset_template[subset_template["technique"] == tech]
  439. if subset.empty:
  440. continue
  441. x = pd.to_numeric(subset[clinical_var], errors="coerce")
  442. y = pd.to_numeric(subset[metric], errors="coerce")
  443. valid = x.notna() & y.notna()
  444. x, y = x[valid], y[valid]
  445. if len(x) == 0:
  446. continue
  447. plt.scatter(x, y, color=palette[tech], alpha=0.6)
  448. if len(x) > 1 and x.nunique() > 1 and y.nunique() > 1:
  449. m, b = np.polyfit(x, y, 1)
  450. x_sorted = np.array(sorted(x), dtype=np.float64)
  451. line = plt.plot(x_sorted, m * x_sorted + b, color=palette[tech], linestyle="--")
  452. r, p = pearsonr(x, y)
  453. labels.append(f"{tech} (R²={r**2:.2f})")
  454. handles.append(line[0])
  455. if handles:
  456. plt.legend(handles=handles, labels=labels, title="Pipeline")
  457. plt.tight_layout()
  458. filename = f"{metric}_vs_{safe_display}_{template}.png"
  459. filepath = os.path.join(output_dir, filename)
  460. plt.savefig(filepath, dpi=300)
  461. plt.close()
  462. # %%
  463. # ============================================
  464. # LMM for slopes + q-values + Pearson r
  465. # ============================================
  466. # Figure 4b, Figures S3b-S6b
  467. import os, numpy as np, pandas as pd, itertools
  468. import matplotlib.pyplot as plt
  469. import seaborn as sns
  470. from scipy.stats import chi2, norm, pearsonr
  471. import statsmodels.formula.api as smf
  472. from statsmodels.stats.multitest import multipletests
  473. import matplotlib as mpl
  474. mpl.rcParams["font.family"] = "Arial"
  475. plt.style.use("default")
  476. TITLE_FONTSIZE = 18
  477. AXIS_LABEL_FONTSIZE = 18
  478. TICK_FONTSIZE = 22
  479. ANNOT_FONTSIZE = 20
  480. CBAR_LABEL_FONTSIZE = 18
  481. CBAR_TICK_FONTSIZE = 18
  482. # ============== CONFIG ==============
  483. output_dir = os.path.join(save_directory, "PIPELINE_LMM")
  484. os.makedirs(output_dir, exist_ok=True)
  485. os.makedirs(os.path.join(output_dir, "heatmaps"), exist_ok=True)
  486. os.makedirs(os.path.join(output_dir, "slopes"), exist_ok=True)
  487. os.makedirs(os.path.join(output_dir, "pearson"), exist_ok=True)
  488. df_conn = # data frame containing the connectome metrics
  489. df_clin = # data frame containing the clinical data
  490. df = pd.merge(df_conn, df_clin, left_on="excel_id", right_on="Subject")
  491. metrics = [
  492. "sparsity", "mean_connectivity", "assortativity", "avg_clustering",
  493. "global_efficiency", "avg_shortest_path", "transitivity", "assigned_streamlines"
  494. ]
  495. technique_mapping = {
  496. "20": "ATR-LOW-ACT",
  497. "35": "ATR-MED-ACT",
  498. "50": "ATR-HIGH-ACT",
  499. "act": "FAST-ACT",
  500. "freesurfer": "WMH-ACT",
  501. "no_act": "NOACT",
  502. "noact": "NOACT"
  503. }
  504. templates_mapping = {
  505. "MNI152NLin2009cAsym": "MNI",
  506. "MNI": "MNI",
  507. "MIITRA-MIITRA": "MIITRA",
  508. "MIITRA": "MIITRA"
  509. }
  510. technique_order = [
  511. "FAST-ACT",
  512. "ATR-LOW-ACT",
  513. "ATR-MED-ACT",
  514. "ATR-HIGH-ACT",
  515. "WMH-ACT",
  516. "NOACT"
  517. ]
  518. template_order = ["MIITRA", "MNI"]
  519. pipeline_order = [
  520. f"{template}-{technique}"
  521. for template in template_order
  522. for technique in technique_order
  523. ]
  524. df["template"] = df["template"].astype(str).map(templates_mapping).fillna(df["template"].astype(str))
  525. df["technique"] = df["technique"].astype(str).map(technique_mapping).fillna(df["technique"].astype(str))
  526. df = df[df["template"].isin(template_order)].copy()
  527. df = df[df["technique"].isin(technique_order)].copy()
  528. clinical_vars = [
  529. "WMH_WM",
  530. "PET_CENTILOID",
  531. "MMSE",
  532. "MOCA"
  533. ]
  534. covariates = ["Age", "Sex", "CEREBRUM_TCV"]
  535. rename_map = {}
  536. FALLBACK_OLS = True
  537. # ============== PREP DATA ==============
  538. if rename_map:
  539. df = df.rename(columns=rename_map)
  540. needed_base = ["Subject", "template", "technique"] + covariates
  541. missing = [c for c in needed_base if c not in df.columns]
  542. if missing:
  543. raise KeyError(f"Missing required columns: {missing}")
  544. df["template"] = pd.Categorical(df["template"], categories=template_order, ordered=True)
  545. df["technique"] = pd.Categorical(df["technique"], categories=technique_order, ordered=True)
  546. df["pipeline"] = df["template"].astype(str) + "-" + df["technique"].astype(str)
  547. df["pipeline"] = pd.Categorical(df["pipeline"], categories=pipeline_order, ordered=True)
  548. df["Sex"] = df["Sex"].astype("category")
  549. # ============== HELPER ==============
  550. def linear_combo(fe_params, cov, terms, sign=None):
  551. names = fe_params.index.tolist()
  552. L = np.zeros(len(names))
  553. if sign is None:
  554. sign = [1.0] * len(terms)
  555. for t, s in zip(terms, sign):
  556. if t in names:
  557. L[names.index(t)] += s
  558. est = float(L @ fe_params.values)
  559. var = float(L @ cov.values @ L)
  560. se = np.sqrt(max(var, 0.0))
  561. z = est / se if se > 0 else np.nan
  562. p = 2 * (1 - norm.cdf(abs(z))) if np.isfinite(z) else np.nan
  563. zcrit = norm.ppf(0.975)
  564. low, high = est - zcrit * se, est + zcrit * se
  565. return est, se, z, p, low, high
  566. def slope_terms_for_pipeline(clinical, level, baseline_level):
  567. if level == baseline_level:
  568. return [clinical]
  569. return [clinical, f"{clinical}:C(pipeline)[T.{level}]"]
  570. def build_pairwise_q_matrix(fe_params, cov, clinical, pipe_levels):
  571. baseline = pipe_levels[0]
  572. pairs, pvals = [], []
  573. for i, j in itertools.combinations(pipe_levels, 2):
  574. terms_i = slope_terms_for_pipeline(clinical, i, baseline)
  575. terms_j = slope_terms_for_pipeline(clinical, j, baseline)
  576. terms = terms_i + terms_j
  577. signs = [1.0] * len(terms_i) + [-1.0] * len(terms_j)
  578. est, se, z, p, low, high = linear_combo(fe_params, cov, terms, signs)
  579. pairs.append((i, j))
  580. pvals.append(p)
  581. pvals = np.array(pvals, dtype=float)
  582. ok = np.isfinite(pvals)
  583. qvals = np.full_like(pvals, np.nan)
  584. if ok.sum() > 0:
  585. _, q_ok, _, _ = multipletests(pvals[ok], method="fdr_bh")
  586. qvals[ok] = q_ok
  587. qmat = pd.DataFrame(np.nan, index=pipe_levels, columns=pipe_levels)
  588. for (i, j), q in zip(pairs, qvals):
  589. qmat.loc[i, j] = q
  590. qmat.loc[j, i] = q
  591. np.fill_diagonal(qmat.values, np.nan)
  592. return qmat
  593. def omnibus_chisq_for_interaction(fe_params, cov, clinical, pipe_levels):
  594. names = fe_params.index.tolist()
  595. baseline = pipe_levels[0]
  596. inter_names = [f"{clinical}:C(pipeline)[T.{lvl}]" for lvl in pipe_levels if lvl != baseline]
  597. idx = [names.index(nm) for nm in inter_names if nm in names]
  598. if len(idx) == 0:
  599. return np.nan, np.nan, 0
  600. b = fe_params.values[idx]
  601. S = cov.values[np.ix_(idx, idx)]
  602. try:
  603. stat = float(b.T @ np.linalg.inv(S) @ b)
  604. df_omni = len(idx)
  605. p = 1 - chi2.cdf(stat, df_omni)
  606. return stat, p, df_omni
  607. except np.linalg.LinAlgError:
  608. return np.nan, np.nan, len(idx)
  609. def q_to_star(q):
  610. if q < 0.001:
  611. return "§"
  612. elif q < 0.01:
  613. return "‡"
  614. elif q < 0.05:
  615. return "†"
  616. return ""
  617. # ============== MAIN LOOP ==============
  618. for metric in metrics:
  619. if metric not in df.columns:
  620. print(f"⚠️ Missing metric, skipping: {metric}")
  621. continue
  622. for clinical in clinical_vars:
  623. if clinical not in df.columns:
  624. print(f"⚠️ Missing clinical variable, skipping: {clinical}")
  625. continue
  626. needed = [metric, clinical, "Subject", "pipeline"] + covariates
  627. dat = df.dropna(subset=[c for c in needed if c in df.columns]).copy()
  628. if dat.empty:
  629. print(f"⚠️ Missing data for {metric} ~ {clinical}.")
  630. continue
  631. counts = dat.groupby("Subject").size()
  632. dat = dat[dat["Subject"].isin(counts[counts >= 2].index)].copy()
  633. if dat["Subject"].nunique() < 2:
  634. print(f"⚠️ Too few subjects with ≥2 observations for {metric} ~ {clinical}.")
  635. continue
  636. dat["pipeline"] = pd.Categorical(dat["pipeline"], categories=pipeline_order, ordered=True)
  637. dat["pipeline"] = dat["pipeline"].cat.remove_unused_categories()
  638. dat["Sex"] = dat["Sex"].astype("category")
  639. pipe_levels = dat["pipeline"].cat.categories.tolist()
  640. if len(pipe_levels) < 2:
  641. print(f"⚠️ Less than 2 pipelines present in the data for {metric} ~ {clinical}.")
  642. continue
  643. formula = f"{metric} ~ {clinical} * C(pipeline) + Age + C(Sex) + CEREBRUM_TCV"
  644. fit_obj = None
  645. model_used = None
  646. try:
  647. md = smf.mixedlm(formula, data=dat, groups=dat["Subject"])
  648. fit_obj = md.fit(reml=True, method="lbfgs", maxiter=2000)
  649. model_used = "MixedLM"
  650. except Exception as e:
  651. if FALLBACK_OLS:
  652. try:
  653. ols = smf.ols(formula, data=dat).fit(
  654. cov_type="cluster",
  655. cov_kwds={"groups": dat["Subject"]}
  656. )
  657. fit_obj = ols
  658. model_used = "OLS_cluster"
  659. print(f"ℹ️ Fallback OLS cluster for {metric} ~ {clinical}: {e}")
  660. except Exception as e2:
  661. print(f"❌ Fit failed also for OLS ({metric} ~ {clinical}): {e2}")
  662. continue
  663. else:
  664. print(f"❌ Fit MixedLM failed for {metric} ~ {clinical}: {e}")
  665. continue
  666. fe = fit_obj.params
  667. cov = fit_obj.cov_params()
  668. stat, p_omni, df_omni = omnibus_chisq_for_interaction(fe, cov, clinical, pipe_levels)
  669. baseline = pipe_levels[0]
  670. rows = []
  671. for lvl in pipe_levels:
  672. terms = slope_terms_for_pipeline(clinical, lvl, baseline)
  673. est, se, z, p, low, high = linear_combo(fe, cov, terms)
  674. rows.append({
  675. "metric": metric,
  676. "clinical_var": clinical,
  677. "pipeline": lvl,
  678. "slope": est,
  679. "se": se,
  680. "z": z,
  681. "p": p,
  682. "ci_low": low,
  683. "ci_high": high,
  684. "model": model_used,
  685. "omnibus_chi2": stat,
  686. "omnibus_df": df_omni,
  687. "omnibus_p": p_omni,
  688. "n_rows": dat.shape[0],
  689. "n_subjects": dat["Subject"].nunique()
  690. })
  691. slopes_df = pd.DataFrame(rows)
  692. slopes_path = os.path.join(
  693. output_dir,
  694. "slopes",
  695. f"SLOPES__{metric}__{clinical}.csv".replace(" ", "_")
  696. )
  697. slopes_df.to_csv(slopes_path, index=False)
  698. qmat = build_pairwise_q_matrix(fe, cov, clinical, pipe_levels)
  699. qcsv = os.path.join(
  700. output_dir,
  701. "heatmaps",
  702. f"PAIRWISE_Q__{metric}__{clinical}.csv".replace(" ", "_")
  703. )
  704. qmat.to_csv(qcsv)
  705. annot_mat = qmat.copy().astype(str)
  706. for i in range(qmat.shape[0]):
  707. for j in range(qmat.shape[1]):
  708. val = qmat.iloc[i, j]
  709. annot_mat.iloc[i, j] = q_to_star(val) if np.isfinite(val) else ""
  710. mask = np.triu(np.ones_like(qmat, dtype=bool), k=1)
  711. fig, ax = plt.subplots(figsize=(1.2 * len(pipe_levels), 1.0 * len(pipe_levels)))
  712. hm = sns.heatmap(
  713. qmat.astype(float),
  714. annot=annot_mat,
  715. fmt="",
  716. cmap="viridis_r",
  717. vmin=0,
  718. vmax=0.25,
  719. mask=mask,
  720. square=True,
  721. cbar_kws={"label": "q (BH)", "shrink": 0.9, "pad": 0.02},
  722. annot_kws={"fontsize": ANNOT_FONTSIZE, "fontweight": "bold"}
  723. )
  724. ax.tick_params(axis="x", labelsize=TICK_FONTSIZE, rotation=90)
  725. ax.tick_params(axis="y", labelsize=TICK_FONTSIZE, rotation=0)
  726. cbar = hm.collections[0].colorbar
  727. cbar.ax.tick_params(labelsize=CBAR_TICK_FONTSIZE)
  728. cbar.set_label("q (BH)", fontsize=CBAR_LABEL_FONTSIZE)
  729. plt.tight_layout()
  730. qpng = os.path.join(
  731. output_dir,
  732. "heatmaps",
  733. f"PAIRWISE_Q__{metric}__{clinical}.png".replace(" ", "_")
  734. )
  735. plt.savefig(qpng, dpi=200)
  736. plt.close()
  737. corr_rows = []
  738. for lvl in pipe_levels:
  739. sub = dat[dat["pipeline"] == lvl]
  740. x = pd.to_numeric(sub[clinical], errors="coerce")
  741. y = pd.to_numeric(sub[metric], errors="coerce")
  742. mask_xy = x.notna() & y.notna()
  743. x, y = x[mask_xy], y[mask_xy]
  744. if len(x) >= 3:
  745. r, p_r = pearsonr(x, y)
  746. corr_rows.append({
  747. "metric": metric,
  748. "clinical_var": clinical,
  749. "pipeline": lvl,
  750. "r": r,
  751. "r2": r**2,
  752. "n": len(x),
  753. "p_r": p_r
  754. })
  755. else:
  756. corr_rows.append({
  757. "metric": metric,
  758. "clinical_var": clinical,
  759. "pipeline": lvl,
  760. "r": np.nan,
  761. "r2": np.nan,
  762. "n": len(x),
  763. "p_r": np.nan
  764. })
  765. corr_df = pd.DataFrame(corr_rows)
  766. corr_path = os.path.join(
  767. output_dir,
  768. "pearson",
  769. f"PEARSON__{metric}__{clinical}.csv".replace(" ", "_")
  770. )
  771. corr_df.to_csv(corr_path, index=False)
  772. print(
  773. f"✅ {metric} ~ {clinical} | model={model_used} | omnibus p={p_omni:.3g} | "
  774. f"slopes→ {os.path.basename(slopes_path)} | heatmap→ {os.path.basename(qpng)}"
  775. )
  776. # %%
  777. # ============================================
  778. # OMNIBUS SUMMARY
  779. # ============================================
  780. # Table S2 and figure 5
  781. import os, re, glob
  782. import numpy as np
  783. import pandas as pd
  784. import matplotlib.pyplot as plt
  785. import seaborn as sns
  786. from statsmodels.stats.multitest import multipletests
  787. mpl.rcParams["font.family"] = "Arial"
  788. plt.style.use("default")
  789. # ========== CONFIG ==========
  790. base_dir = os.path.join(save_directory,"PIPELINE_LMM")
  791. slopes_dir = os.path.join(base_dir, "slopes")
  792. heatm_dir = os.path.join(base_dir, "heatmaps")
  793. out_dir = os.path.join(base_dir, "summary")
  794. os.makedirs(out_dir, exist_ok=True)
  795. ALPHA_FDR = 0.05 # q-values threshold
  796. # ========== 1) LOAD SLOPES__*.csv AND BUILD OMNIBUS TABLE ==========
  797. rows = []
  798. files = sorted(glob.glob(os.path.join(slopes_dir, "SLOPES__*.csv")))
  799. if not files:
  800. raise FileNotFoundError(f"No SLOPES__*.csv files found in {slopes_dir}")
  801. for f in files:
  802. df = pd.read_csv(f)
  803. if df.empty:
  804. continue
  805. head = df.iloc[0]
  806. metric = head["metric"]
  807. clin = head["clinical_var"]
  808. chi2 = head.get("omnibus_chi2", np.nan)
  809. df_ = head.get("omnibus_df", np.nan)
  810. p_omni = head.get("omnibus_p", np.nan)
  811. model = head.get("model", "")
  812. n_rows = head.get("n_rows", df.shape[0])
  813. n_subj = head.get("n_subjects", np.nan)
  814. n_pipe = df["pipeline"].nunique() if "pipeline" in df.columns else np.nan
  815. rows.append({
  816. "metric": metric,
  817. "clinical_var": clin,
  818. "omnibus_chi2": chi2,
  819. "omnibus_df": df_,
  820. "omnibus_p": p_omni,
  821. "model": model,
  822. "n_rows": n_rows,
  823. "n_subjects": n_subj,
  824. "n_pipeline": n_pipe,
  825. "slopes_path": os.path.basename(f)
  826. })
  827. omni = pd.DataFrame(rows).sort_values(["metric","clinical_var"]).reset_index(drop=True)
  828. # FDR BH on omnibus p values
  829. omni["q_bh_omnibus"] = np.nan
  830. p = omni["omnibus_p"].to_numpy(dtype=float)
  831. ok = np.isfinite(p)
  832. if ok.sum() > 0:
  833. _, q, _, _ = multipletests(p[ok], method="fdr_bh")
  834. omni.loc[ok, "q_bh_omnibus"] = q
  835. # save full omnibus table
  836. omni_csv = os.path.join(out_dir, "omnibus_summary.csv")
  837. omni.to_csv(omni_csv, index=False)
  838. print(f"✅ Salvato: {omni_csv}")
  839. pivot = omni.pivot_table(index="metric", columns="clinical_var", values="q_bh_omnibus", aggfunc="first")
  840. pivot_csv = os.path.join(out_dir, "omnibus_q_matrix.csv")
  841. pivot.to_csv(pivot_csv)
  842. print(f"✅ Saved: {pivot_csv}")
  843. # %%
  844. # ============================
  845. # MERGE SLOPES + PEARSON (r, r2, p_r)
  846. # ============================
  847. #Table S3-S6
  848. import os, re, glob
  849. import numpy as np
  850. import pandas as pd
  851. from statsmodels.stats.multitest import multipletests
  852. # --- CONFIG ---
  853. base_dir = os.path.join(save_directory, "PIPELINE_LMM")
  854. slopes_dir = os.path.join(base_dir, "slopes")
  855. pearson_dir = os.path.join(base_dir, "pearson")
  856. out_dir = os.path.join(base_dir, "summary")
  857. os.makedirs(out_dir, exist_ok=True)
  858. def add_fdr(group, pcol, qcol):
  859. p = pd.to_numeric(group[pcol], errors="coerce").to_numpy()
  860. ok = np.isfinite(p)
  861. q = np.full_like(p, np.nan, dtype=float)
  862. if ok.sum() > 0:
  863. _, q_vals, _, _ = multipletests(p[ok], method="fdr_bh")
  864. q[ok] = q_vals
  865. group[qcol] = q
  866. return group
  867. # --- Utility ---
  868. pat = re.compile(r"__(?P<metric>.+?)__(?P<clin>.+?)\.csv$", flags=re.IGNORECASE)
  869. def parse_metric_clin(path_or_name: str):
  870. m = pat.search(os.path.basename(path_or_name).replace(" ", "_"))
  871. if m:
  872. return m.group("metric").replace("_", " "), m.group("clin").replace("_", " ")
  873. return None, None
  874. # ========== 1) Upload SLOPES ==========
  875. s_files = sorted(glob.glob(os.path.join(slopes_dir, "SLOPES__*.csv")))
  876. if not s_files:
  877. raise FileNotFoundError(f"NO file SLOPES__*.csv in {slopes_dir}")
  878. slopes_rows = []
  879. for f in s_files:
  880. df = pd.read_csv(f)
  881. if df.empty:
  882. continue
  883. if not {"metric","clinical_var"} <= set(df.columns):
  884. met, clin = parse_metric_clin(f)
  885. if "metric" not in df.columns: df["metric"] = met
  886. if "clinical_var" not in df.columns: df["clinical_var"] = clin
  887. if "pipeline" in df.columns:
  888. df["pipeline"] = df["pipeline"].astype(str).str.strip()
  889. if "p" in df.columns:
  890. df = df.rename(columns={"p": "p_slope"})
  891. rename_map = {
  892. "ci_low":"slope_ci_low","ci_lower":"slope_ci_low",
  893. "ci_high":"slope_ci_high","ci_upper":"slope_ci_high"
  894. }
  895. df = df.rename(columns={k:v for k,v in rename_map.items() if k in df.columns})
  896. keep_cols = [c for c in [
  897. "metric","clinical_var","pipeline",
  898. "slope","slope_ci_low","slope_ci_high","p_slope",
  899. "model","n_rows","n_subjects"
  900. ] if c in df.columns]
  901. slopes_rows.append(df[keep_cols])
  902. slopes_all = pd.concat(slopes_rows, ignore_index=True)
  903. if "p_slope" in slopes_all.columns:
  904. slopes_all = slopes_all.groupby(["metric","clinical_var"], as_index=False)\
  905. .apply(add_fdr, pcol="p_slope", qcol="q_slope_bh")\
  906. .reset_index(drop=True)
  907. # ========== 2) Upload PEARSON (metric, clinical_var, pipeline, r, r2, n, p_r) ==========
  908. p_files = sorted(glob.glob(os.path.join(pearson_dir, "PEARSON__*.csv")))
  909. pearson_rows = []
  910. for f in p_files:
  911. df = pd.read_csv(f)
  912. if df.empty:
  913. continue
  914. if not {"metric","clinical_var"} <= set(df.columns):
  915. met, clin = parse_metric_clin(f)
  916. if "metric" not in df.columns: df["metric"] = met
  917. if "clinical_var" not in df.columns: df["clinical_var"] = clin
  918. if "pipeline" in df.columns:
  919. df["pipeline"] = df["pipeline"].astype(str).str.strip()
  920. # p_r -> p_pearson ; r -> r_pearson ; r2 e n
  921. rename_map = {"r":"r_pearson", "p_r":"p_pearson"}
  922. df = df.rename(columns=rename_map)
  923. keep_cols = [c for c in [
  924. "metric","clinical_var","pipeline",
  925. "r_pearson","r2","n","p_pearson"
  926. ] if c in df.columns]
  927. pearson_rows.append(df[keep_cols])
  928. pearson_all = pd.DataFrame()
  929. if pearson_rows:
  930. pearson_all = pd.concat(pearson_rows, ignore_index=True)
  931. if "p_pearson" in pearson_all.columns:
  932. pearson_all = pearson_all.groupby(["metric","clinical_var"], as_index=False)\
  933. .apply(add_fdr, pcol="p_pearson", qcol="q_pearson_bh")\
  934. .reset_index(drop=True)
  935. # ========== 3) Merge(metric, clinical_var, pipeline) ==========
  936. if pearson_all.empty:
  937. merged = slopes_all.copy()
  938. else:
  939. merged = pd.merge(
  940. slopes_all, pearson_all,
  941. on=["metric","clinical_var","pipeline"],
  942. how="outer",
  943. validate="m:m"
  944. )
  945. # Saving
  946. sort_cols = [c for c in ["metric","clinical_var","pipeline"] if c in merged.columns]
  947. merged = merged.sort_values(sort_cols).reset_index(drop=True)
  948. out_csv = os.path.join(out_dir, "SLOPES_PEARSON__merged_long.csv")
  949. merged.to_csv(out_csv, index=False)
  950. print(f"✅ Saved: {out_csv}")
  951. # %%
  952. # ============================================
  953. # csv file for brain regions
  954. # ============================================
  955. import pandas as pd
  956. txt_path = # txt file containing the brain region labels
  957. with open(txt_path, "r") as f:
  958. lines = [line.strip() for line in f if line.strip()]
  959. records = []
  960. for i in range(0, len(lines), 2):
  961. label = lines[i]
  962. parts = lines[i+1].split()
  963. idx = int(parts[0]) - 1 # 🔑 shift da 1-based → 0-based
  964. r,g,b,a = map(int, parts[1:])
  965. records.append((idx, label, r,g,b,a))
  966. df = pd.DataFrame(records, columns=["node","label","R","G","B","A"])
  967. def parse_network(label, node):
  968. if node < 16: # primi 16 nodi = Subcortical
  969. return "Subcortical"
  970. if "Vis" in label: return "Vis"
  971. if "SomMot" in label: return "SomMot"
  972. if "DorsAttn" in label: return "DorsAttn"
  973. if "SalVentAttn" in label: return "SalVentAttn"
  974. if "Limbic" in label: return "Limbic"
  975. if "Cont" in label: return "Cont"
  976. if "Default" in label: return "Default"
  977. return "Unknown"
  978. df["network7"] = [parse_network(lab, n) for lab,n in zip(df["label"], df["node"])]
  979. # Saving CSV
  980. csv_path = os.path.join(path_to_parcellation, "Schaefer/Cortex-Subcortex/Schaefer2018_400Parcels_7Networks_withSubcortical.csv")
  981. df.to_csv(csv_path, index=False)
  982. print("Saved:", csv_path)
  983. print("Noded min:", df["node"].min(), "max:", df["node"].max(), "count:", df["node"].nunique())
  984. # %%
  985. # ============================================
  986. # Template effect on nodal metrics
  987. # ============================================
  988. # Figure 6 and Figure S7
  989. import os, itertools, numpy as np, pandas as pd
  990. import matplotlib as mpl
  991. import matplotlib.pyplot as plt
  992. import seaborn as sns
  993. import statsmodels.formula.api as smf
  994. from statsmodels.stats.multitest import multipletests
  995. from scipy.stats import norm
  996. import matplotlib.patches as mpatches
  997. import matplotlib.ticker as mtick
  998. # ---------- FONT & STYLE ----------
  999. FONT_FAMILY = "Arial"
  1000. BASE_FONT_SZ = 10
  1001. TITLE_SIZE = 22
  1002. LABEL_SIZE = 22
  1003. TICK_SIZE = 22
  1004. LEGEND_SIZE = 20
  1005. XTICK_ROT = 90
  1006. mpl.rcParams.update({
  1007. "font.family": FONT_FAMILY,
  1008. "font.size": BASE_FONT_SZ,
  1009. "axes.titlesize": TITLE_SIZE,
  1010. "axes.labelsize": LABEL_SIZE,
  1011. "xtick.labelsize": TICK_SIZE,
  1012. "ytick.labelsize": TICK_SIZE,
  1013. "legend.fontsize": LEGEND_SIZE,
  1014. })
  1015. plt.style.use("default")
  1016. # ---------- PATHS ----------
  1017. base_out = os.path.join(save_directory, "NODAL_TEMPLATE_EFFECT")
  1018. dirs = {
  1019. "root": base_out,
  1020. "estimates": os.path.join(base_out, "estimates"),
  1021. "pairwise_node": os.path.join(base_out, "pairwise_node"),
  1022. "heatmaps": os.path.join(base_out, "heatmaps"),
  1023. "summaries": os.path.join(base_out, "summaries"),
  1024. }
  1025. for d in dirs.values():
  1026. os.makedirs(d, exist_ok=True)
  1027. node_csv = os.path.join(path_to_metrics, "connectome_no_density_metrics_local.csv")
  1028. # Yeo-7 mapping
  1029. yeo7_csv = os.path.join(
  1030. path_to_parcellation,
  1031. "Schaefer/Cortex-Subcortex/Schaefer2018_400Parcels_7Networks_withSubcortical.csv"
  1032. )
  1033. # ---------- PARAMS ----------
  1034. FALLBACK_OLS = True
  1035. ALPHA = 0.001
  1036. NODES_TO_RUN = None
  1037. NET_STRIPE_WIDTH = 0.18
  1038. # Nodal metrics
  1039. metrics = ["degree", "strength", "clustering", "betweenness", "closeness", "local_efficiency"]
  1040. # Covariates
  1041. covariates = ["Age", "Sex", "CEREBRUM_TCV"]
  1042. # Mapping
  1043. technique_mapping = {
  1044. "20": "ATR-LOW-ACT",
  1045. "35": "ATR-MED-ACT",
  1046. "50": "ATR-HIGH-ACT",
  1047. "act": "FAST-ACT",
  1048. "freesurfer": "WMH-ACT",
  1049. "no_act": "NOACT",
  1050. "noact": "NOACT"
  1051. }
  1052. templates_mapping = {
  1053. "MNI152NLin2009cAsym": "MNI",
  1054. "MNI": "MNI",
  1055. "MIITRA-MIITRA": "MIITRA",
  1056. "MIITRA": "MIITRA"
  1057. }
  1058. technique_order = [
  1059. "FAST-ACT",
  1060. "ATR-LOW-ACT",
  1061. "ATR-MED-ACT",
  1062. "ATR-HIGH-ACT",
  1063. "WMH-ACT",
  1064. "NOACT"
  1065. ]
  1066. template_order = ["MNI", "MIITRA"]
  1067. # ---------- COLOR LUT PER NETWORK ----------
  1068. net_order = ["Subcortical", "Vis", "SomMot", "DorsAttn",
  1069. "SalVentAttn", "Limbic", "Cont", "Default", "Unknown"]
  1070. lut = {
  1071. "Subcortical": (0.894, 0.102, 0.110),
  1072. "Vis": (0.216, 0.494, 0.722),
  1073. "SomMot": (0.302, 0.686, 0.290),
  1074. "DorsAttn": (0.596, 0.306, 0.639),
  1075. "SalVentAttn": (1.000, 0.498, 0.0),
  1076. "Limbic": (1.000, 1.000, 0.200),
  1077. "Cont": (0.651, 0.337, 0.157),
  1078. "Default": (0.969, 0.506, 0.749),
  1079. "Unknown": (0.70, 0.70, 0.70),
  1080. }
  1081. # ---------- LOAD ----------
  1082. df_node = # data frame containing the nodal metrics
  1083. df_clin = # data frame containing the clinical data
  1084. # Merge
  1085. merge_keys_node = [c for c in ["excel_id", "Subject", "subject", "SUBJECT_ID"] if c in df_node.columns]
  1086. merge_keys_clin = [c for c in ["Subject", "excel_id", "subject", "SUBJECT_ID"] if c in df_clin.columns]
  1087. if not merge_keys_node or not merge_keys_clin:
  1088. raise KeyError("Non trovo una chiave comune per il merge (es. 'excel_id' o 'Subject').")
  1089. left_key, right_key = merge_keys_node[0], merge_keys_clin[0]
  1090. df = pd.merge(df_node, df_clin, left_on=left_key, right_on=right_key, how="inner")
  1091. # Mapping/casting
  1092. df["template"] = df["template"].astype(str).map(templates_mapping).fillna(df["template"].astype(str))
  1093. df["technique"] = df["technique"].astype(str).map(technique_mapping).fillna(df["technique"].astype(str))
  1094. df = df[df["template"].isin(template_order)].copy()
  1095. df = df[df["technique"].isin(technique_order)].copy()
  1096. df["template"] = pd.Categorical(df["template"], categories=template_order, ordered=True)
  1097. df["technique"] = pd.Categorical(df["technique"], categories=technique_order, ordered=True)
  1098. df["Sex"] = df["Sex"].astype("category")
  1099. n_nodes = int(df["node"].nunique())
  1100. node_list = sorted(df["node"].unique()) if NODES_TO_RUN is None else list(NODES_TO_RUN)
  1101. # ---------- YEO-7 ANNOTATIONS (con auto-detect 0/1-based) ----------
  1102. node_ann = pd.read_csv(yeo7_csv)
  1103. node_ann_sub = node_ann[["node", "network7"]].copy()
  1104. node_ann_sub["node"] = node_ann_sub["node"].astype(int)
  1105. node_ann_sub = node_ann_sub.drop_duplicates(subset=["node"], keep="first")
  1106. eff_nodes_all = pd.Index(df["node"].unique()).astype(int)
  1107. ann_nodes_all = pd.Index(node_ann_sub["node"].unique()).astype(int)
  1108. if set(eff_nodes_all).issubset(set((ann_nodes_all - 1).tolist())) and 0 in eff_nodes_all:
  1109. node_ann_sub["node"] = node_ann_sub["node"] - 1
  1110. node_ann_sub["network7"] = node_ann_sub["network7"].replace({"SUBCORTICAL": "Subcortical"})
  1111. node_ann_sub["network7"] = node_ann_sub["network7"].fillna("Unknown")
  1112. # ---------- HELPERS ----------
  1113. def linear_combo(fe_params, cov, terms, signs=None):
  1114. names = fe_params.index.tolist()
  1115. L = np.zeros(len(names))
  1116. if signs is None:
  1117. signs = [1.0] * len(terms)
  1118. for t, s in zip(terms, signs):
  1119. if t in names:
  1120. L[names.index(t)] += s
  1121. est = float(L @ fe_params.values)
  1122. var = float(L @ cov.values @ L)
  1123. se = np.sqrt(max(var, 0.0))
  1124. z = est / se if se > 0 else np.nan
  1125. p = 2 * (1 - norm.cdf(abs(z))) if np.isfinite(z) else np.nan
  1126. zcrit = norm.ppf(0.975)
  1127. return est, se, z, p, est - zcrit * se, est + zcrit * se
  1128. def template_effect_terms_for_tech(level, baseline_tech):
  1129. terms = ["C(template)[T.MIITRA]"]
  1130. if level != baseline_tech:
  1131. terms.append(f"C(template)[T.MIITRA]:C(technique)[T.{level}]")
  1132. return terms
  1133. # ---------- MAIN ----------
  1134. for metric in metrics:
  1135. if metric not in df.columns:
  1136. print(f"⚠️ Metrica assente: {metric}")
  1137. continue
  1138. est_rows = []
  1139. pairwise_tests = []
  1140. needed = ["Subject", "node", "template", "technique", "Age", "Sex", "CEREBRUM_TCV", metric]
  1141. dat_all = df.dropna(subset=[c for c in needed if c in df.columns]).copy()
  1142. if dat_all.empty:
  1143. print(f"⚠️ No data {metric}")
  1144. continue
  1145. for node in node_list:
  1146. dat = dat_all[dat_all["node"] == node].copy()
  1147. if dat.empty or dat["Subject"].nunique() < 2:
  1148. continue
  1149. dat["Sex"] = dat["Sex"].astype("category")
  1150. dat["template"] = pd.Categorical(dat["template"], categories=template_order, ordered=True)
  1151. tech_levels_node = [t for t in technique_order if t in dat["technique"].astype(str).unique()]
  1152. if len(tech_levels_node) < 2:
  1153. continue
  1154. dat["technique"] = pd.Categorical(dat["technique"], categories=tech_levels_node, ordered=True)
  1155. formula = f"{metric} ~ C(template)*C(technique) + Age + C(Sex) + CEREBRUM_TCV"
  1156. try:
  1157. md = smf.mixedlm(formula, data=dat, groups=dat["Subject"])
  1158. fit_obj = md.fit(reml=True, method="lbfgs", maxiter=2000)
  1159. except Exception:
  1160. if FALLBACK_OLS:
  1161. try:
  1162. fit_obj = smf.ols(formula, data=dat).fit(
  1163. cov_type="cluster",
  1164. cov_kwds={"groups": dat["Subject"]}
  1165. )
  1166. except Exception:
  1167. continue
  1168. else:
  1169. continue
  1170. fe, cov = fit_obj.params, fit_obj.cov_params()
  1171. baseline_tech = tech_levels_node[0]
  1172. # Template effect per pipeline
  1173. for lvl in tech_levels_node:
  1174. terms = template_effect_terms_for_tech(lvl, baseline_tech)
  1175. est, se, z, p, lo, hi = linear_combo(fe, cov, terms)
  1176. est_rows.append({
  1177. "metric": metric,
  1178. "node": node,
  1179. "technique": lvl,
  1180. "template_effect": est,
  1181. "p": p
  1182. })
  1183. # Pairwise template effect per node
  1184. for i, j in itertools.combinations(tech_levels_node, 2):
  1185. terms_i = template_effect_terms_for_tech(i, baseline_tech)
  1186. terms_j = template_effect_terms_for_tech(j, baseline_tech)
  1187. terms = terms_i + terms_j
  1188. signs = [1.0] * len(terms_i) + [-1.0] * len(terms_j)
  1189. est, se, z, p, lo, hi = linear_combo(fe, cov, terms, signs)
  1190. pairwise_tests.append({
  1191. "metric": metric,
  1192. "node": node,
  1193. "tech_i": i,
  1194. "tech_j": j,
  1195. "p": p
  1196. })
  1197. # ---- EFFECTS: saving ----
  1198. est_df = pd.DataFrame(est_rows)
  1199. if est_df.empty:
  1200. print(f"⚠️ No fit for {metric}")
  1201. continue
  1202. est_df["technique"] = pd.Categorical(est_df["technique"], categories=technique_order, ordered=True)
  1203. est_df = est_df.sort_values(["node", "technique"]).reset_index(drop=True)
  1204. est_path = os.path.join(dirs["estimates"], f"TEMPLATE_EFFECT__{metric}.csv")
  1205. est_df.to_csv(est_path, index=False)
  1206. # FDR
  1207. p_mat = est_df.pivot_table(index="node", columns="technique", values="p", aggfunc="first")
  1208. eff_mat = est_df.pivot_table(index="node", columns="technique", values="template_effect", aggfunc="first")
  1209. p_mat = p_mat.reindex(columns=[t for t in technique_order if t in p_mat.columns])
  1210. eff_mat = eff_mat.reindex(columns=[t for t in technique_order if t in eff_mat.columns])
  1211. pvals_flat = p_mat.values.flatten()
  1212. mask = np.isfinite(pvals_flat)
  1213. q_flat = np.full_like(pvals_flat, np.nan, dtype=float)
  1214. if mask.sum() > 0:
  1215. _, q_ok, _, _ = multipletests(pvals_flat[mask], method="fdr_bh")
  1216. q_flat[mask] = q_ok
  1217. q_mat = pd.DataFrame(q_flat.reshape(p_mat.shape), index=p_mat.index, columns=p_mat.columns)
  1218. # --- HEATMAP (masked) ---
  1219. eff_masked = eff_mat.copy()
  1220. eff_masked[q_mat >= ALPHA] = 0
  1221. eff_masked_withnet = (
  1222. eff_masked.reset_index()
  1223. .rename(columns={"index": "node"})
  1224. .merge(node_ann_sub, on="node", how="left")
  1225. )
  1226. eff_masked_withnet["network7"] = eff_masked_withnet["network7"].replace({"SUBCORTICAL": "Subcortical"})
  1227. eff_masked_withnet["network7"] = eff_masked_withnet["network7"].fillna("Unknown")
  1228. mat = eff_masked_withnet.set_index("node").drop(columns="network7")
  1229. row_net = eff_masked_withnet.set_index("node").loc[mat.index, "network7"]
  1230. row_colors = row_net.map(lambda k: lut.get(k, lut["Unknown"])).tolist()
  1231. vmax = np.nanpercentile(np.abs(eff_mat.values), 95)
  1232. vmax = vmax if np.isfinite(vmax) and vmax > 0 else 1.0
  1233. vmin = -vmax
  1234. fig, ax = plt.subplots(figsize=(12, 8))
  1235. ax = sns.heatmap(
  1236. mat,
  1237. cmap="RdBu_r",
  1238. center=0,
  1239. vmin=vmin,
  1240. vmax=vmax,
  1241. cbar_kws={
  1242. "label": "Template effect (MIITRA − MNI)",
  1243. "format": mtick.FormatStrFormatter('%.1e')
  1244. },
  1245. yticklabels=False
  1246. )
  1247. ncols = mat.shape[1]
  1248. for y, color in enumerate(row_colors):
  1249. ax.add_patch(plt.Rectangle((ncols, y), NET_STRIPE_WIDTH, 1, color=color, lw=0, clip_on=False))
  1250. ax.set_title(f"{metric}")
  1251. ax.set_xlabel("Pipeline")
  1252. ax.set_ylabel("Node")
  1253. plt.setp(ax.get_xticklabels(), rotation=XTICK_ROT, ha="right")
  1254. handles = [
  1255. mpatches.Patch(color=lut[n], label=n)
  1256. for n in net_order if n in row_net.unique()
  1257. ]
  1258. ax.legend(
  1259. handles=handles,
  1260. bbox_to_anchor=(0.5, -0.35),
  1261. loc="upper center",
  1262. title="Yeo7 Networks + Subcortical",
  1263. ncol=8,
  1264. frameon=False
  1265. )
  1266. plt.tight_layout()
  1267. heat_path = os.path.join(dirs["heatmaps"], f"HEATMAP_TEMPLATE_EFFECT_MASKED__{metric}_netColor.png")
  1268. plt.savefig(heat_path, dpi=220, bbox_inches="tight")
  1269. plt.close(fig)
  1270. # ---- NETWORK SUMMARY (CSV + barplot) ----
  1271. tmp = est_df.merge(node_ann_sub, on="node", how="left")
  1272. q_long = q_mat.stack().reset_index().rename(columns={0: "q", "level_0": "node", "level_1": "technique"})
  1273. tmp = tmp.merge(q_long, on=["node", "technique"], how="left")
  1274. tmp = tmp.dropna(subset=["network7", "template_effect"])
  1275. net_sum = (
  1276. tmp.groupby(["network7", "technique"], as_index=False)
  1277. .agg(
  1278. mean_effect=("template_effect", "mean"),
  1279. med_effect=("template_effect", "median"),
  1280. n_nodes=("node", "nunique"),
  1281. pct_sig=("q", lambda x: 100 * np.mean(np.array(x) < ALPHA) if x.notna().sum() > 0 else np.nan)
  1282. )
  1283. )
  1284. net_sum["technique"] = pd.Categorical(net_sum["technique"], categories=technique_order, ordered=True)
  1285. net_sum = net_sum.sort_values(["technique", "network7"]).reset_index(drop=True)
  1286. net_csv = os.path.join(dirs["summaries"], f"NETWORK_SUMMARY__{metric}.csv")
  1287. net_sum.to_csv(net_csv, index=False)
  1288. plt.figure(figsize=(12, 6))
  1289. ax = sns.barplot(data=net_sum, x="technique", y="pct_sig", hue="network7", palette=lut)
  1290. ax.set_xlabel("Pipeline")
  1291. ax.set_ylabel(f"% nodes with q<{ALPHA}")
  1292. ax.set_title(f"{metric}")
  1293. plt.setp(ax.get_xticklabels(), rotation=XTICK_ROT, ha="right")
  1294. ax.legend(title="Yeo7 Networks + Subcortical", frameon=False, ncol=3)
  1295. plt.tight_layout()
  1296. net_fig = os.path.join(dirs["summaries"], f"NETWORK_PCTSIG__{metric}.png")
  1297. plt.savefig(net_fig, dpi=200)
  1298. plt.close()
  1299. print(f"✅ {metric} → effects: {os.path.basename(est_path)} | heatmap: {os.path.basename(heat_path)}")

results.ipynb at commit 7fed980, under MIT · at the source

Overview

Authors: Carlo Ferritto1, Giulia Lioi2, Pierre-Yves Jonin1,3, Julie Coloigner1
  1. Univ Rennes, CNRS, Inria, Inserm, IRISA UMR 6074, EMPENN — ERL U 1228, Rennes, France
  2. IMT Atlantique, Lab-STICC UMR CNRS 6285, Brest, France
  3. Neurology Department, Rennes University Hospital, Rennes, France
Journal: Imaging neuroscience (Cambridge, Mass.), volume 4, article IMAG.a.1384
Dates: received 19 December 2025; accepted 4 September 2026; published online 30 September 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1162/imag.a.1384 · PMID 42824529 · PMCID PMC13628500 · OpenAlex W7120739026
Open access: diamond, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: structural MRI / diffusion (modality), human (organism), methods / tools (subfield)
Methods: Statistics, Smoothing, state filtering, decompositions, Machine learning, Connectivity, fMRI & imaging, Physiology & signal measures
Keywords: structural connectome, tractography, brain aging
MeSH: Aging*, Brain*, Connectome*, Diffusion Tensor Imaging*, Aged, Aged, 80 and over, Diffusion Magnetic Resonance Imaging, Female, Humans, Image Processing, Computer-Assisted, Male, Neural Pathways, White Matter (* major topic)
Topic: Advanced Neuroimaging Techniques and Applications (Radiology, Nuclear Medicine and Imaging, Medicine), according to OpenAlex
Citations: not cited yet (Europe PMC); 60 references in the paper

Abstract

Diffusion-weighted MRI samples the directional diffusion of water in vivo, and tractography uses this information to reconstruct brain fiber pathways. Mapping streamlines to an anatomical parcellation yields structural connectomes. However, in older adults, where white matter alterations and atrophy are common, the choice of reference template and tissue segmentation could be particularly consequential for obtaining accurate, interpretable structural connectomes. Using a conventional pipeline, we evaluated how these two factors, the normalization template and the segmentation used to constrain anatomically guided tractography, affect connectome estimates in cognitively healthy elderly participants. These methodological choices produced systematic and significant differences in network topology and their relationships with clinically relevant variables across standard connectome measures, particularly in patients with white matter hyperintensities. Age-appropriate normalization and lesion-aware anatomically constrained tractography yielded networks with more plausible anatomy and more consistent relationships with cognition and imaging measures, whereas unconstrained tracking inflated density without improving interpretability. These findings demonstrate that structural connectome outcomes are contingent upon template and segmentation selection. We, therefore, advocate for explicit reporting of these methodological parameters and recommend the use of age-appropriate templates combined with white matter lesion-aware segmentation incorporating anatomically informed constraints.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

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

Inria-Empenn/Anima-Public

License: AGPL-3.0
State: the link answers, verified on 3 October 2026
Evidence: files inventoried
Commit: d9fb323d4d15b228318e42b42df16c7ebbf8f6df, 4 March 2026
Languages: C/C++ (267), Shell (1), Python (1)
Size: 960 files, 269 scripts
Software Heritage: not archived
Found in: the text, “Footnotes”
Holds: README, license file, tests, continuous integration, documentation
Not found: CITATION.cff, environment file
Availability: 1 check, the latest on 3 October 2026: the link answers
  • 3 October 2026: the link answers
271 files

CarloFerritto/Structural_connectomes_in_Aging

License: MIT
State: the link answers, verified on 3 October 2026
Evidence: files inventoried
Commit: 7fed9808782e3e200a2ba87ba793179a8306930b, 23 June 2026
Languages: Python (7), Shell (2), Jupyter (1)
Size: 20 files, 10 scripts
Software Heritage: not archived
Found in: “Data and Code Availability”
Holds: README, license file, environment (src/environment_analysis.yaml, src/environment_preprocessing_and_metrics.yml), 1 notebook
Not found: CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (6 files), pandas (4 files), ANTs (2 files), FSL (2 files), Matplotlib (2 files), MRtrix3 (2 files), SciPy (2 files), NetworkX (1 file), seaborn (1 file), statsmodels (1 file)
Availability: 1 check, the latest on 3 October 2026: the link answers
  • 3 October 2026: the link answers
12 files

The paper's code and data availability statement is in the Data section.

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:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 279 scripts, each with its path and the digest of its content;
  • 16 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 and Code Availability

The dataset used in this study is available at https://ida.loni.usc.edu and described in Weiner et al. (2017). The code developed is openly accessible at https://github.com/CarloFerritto/Structural_connectomes_in_Aging

Reproduced under the paper's license (CC BY), from the paper cited above.

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, 3 October 2026: the first record

Recorded: type, language, journal, volume, pages, dates, 4 authors, 3 keywords, 13 MeSH terms, 57 references.

Cite

This paper

Ferritto, C., Lioi, G., Jonin, P.-Y., & Coloigner, J. (2026). Mind the brain age: How segmentation and template selection reshape structural connectomes. Imaging neuroscience (Cambridge, Mass.), 4, IMAG.a.1384. https://doi.org/10.1162/imag.a.1384

BibTeX

@article{ferritto2026mind,
author = {Ferritto, Carlo and Lioi, Giulia and Jonin, Pierre-Yves and Coloigner, Julie},
title = {{Mind the brain age: How segmentation and template selection reshape structural connectomes}},
journal = {Imaging neuroscience (Cambridge, Mass.)},
year = {2026},
month = sep,
volume = {4},
pages = {IMAG.a.1384},
publisher = {MIT Press},
issn = {2837-6056},
doi = {10.1162/imag.a.1384},
url = {https://doi.org/10.1162/imag.a.1384},
pmid = {42824529},
pmcid = {PMC13628500}
}

RIS

TY - JOUR
AU - Ferritto, Carlo
AU - Lioi, Giulia
AU - Jonin, Pierre-Yves
AU - Coloigner, Julie
TI - Mind the brain age: How segmentation and template selection reshape structural connectomes
T2 - Imaging neuroscience (Cambridge, Mass.)
J2 - Imaging Neurosci (Camb)
PY - 2026
DA - 2026/09/30
VL - 4
SP - IMAG.a.1384
SN - 2837-6056
PB - MIT Press
DO - 10.1162/imag.a.1384
UR - https://doi.org/10.1162/imag.a.1384
LA - en
ER -

CSL-JSON

{
"id": "10.1162/imag.a.1384",
"type": "article-journal",
"title": "Mind the brain age: How segmentation and template selection reshape structural connectomes",
"container-title": "Imaging neuroscience (Cambridge, Mass.)",
"author": [
{
"family": "Ferritto",
"given": "Carlo"
},
{
"family": "Lioi",
"given": "Giulia"
},
{
"family": "Jonin",
"given": "Pierre-Yves"
},
{
"family": "Coloigner",
"given": "Julie"
}
],
"container-title-short": "Imaging Neurosci (Camb)",
"volume": "4",
"page": "IMAG.a.1384",
"DOI": "10.1162/imag.a.1384",
"PMID": "42824529",
"PMCID": "PMC13628500",
"ISSN": "2837-6056",
"publisher": "MIT Press",
"URL": "https://doi.org/10.1162/imag.a.1384",
"language": "en",
"issued": {
"date-parts": [
[
2026,
9,
30
]
]
}
}

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.1162/netn_a_00330 [code]
The human brain connectome weighted by the myelin content and total intra-axonal cross-sectional area of white matter tracts.
Journal: Network neuroscience (Cambridge, Mass.)
In common: MRtrix3, ANTs, FSL, 4 other tools, structural MRI / diffusion, 19 references
[2] doi:10.1002/hbm.26239 [code]
Integrated diffusion image operator (iDIO): A pipeline for automated configuration and processing of diffusion MRI data.
Journal: Human brain mapping
In common: MRtrix3, ANTs, FSL, 4 other tools, methods / tools, structural MRI / diffusion, 14 references
[3] doi:10.1162/imag.a.49 [code]
Mapping the aggregate g-ratio of white matter tracts using multi-modal MRI.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: MRtrix3, ANTs, FSL, 5 other tools, structural MRI / diffusion, 11 references
[4] doi:10.1162/imag.a.1325 [code]
Decoding everyday levels of musical training from subcortical white-matter architecture.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: MRtrix3, FSL, statsmodels, 5 other tools, structural MRI / diffusion, 11 references
[5] doi:10.3389/fnins.2024.1385847 [code]
A practical guide for combining functional regions of interest and white matter bundles.
Journal: Frontiers in neuroscience
In common: ANTs, FSL, pandas, 3 other tools, methods / tools, structural MRI / diffusion, 11 references
[6] doi:10.1038/s41467-024-46023-2 [code]
Genetic architecture of the structural connectome.
Journal: Nature communications
In common: MRtrix3, ANTs, FSL, 4 other tools, structural MRI / diffusion, 11 references
[7] doi:10.1016/j.nicl.2025.103817 [code]
Structural connectome manifold changes related to body mass index and their associations with eating psychopathology.
Journal: NeuroImage. Clinical
In common: MRtrix3, ANTs, NetworkX, 7 other tools, structural MRI / diffusion, 8 references
[8] doi:10.1002/hbm.26578 [code]
Fibre orientation atlas guided rapid segmentation of white matter tracts.
Journal: Human brain mapping
In common: MRtrix3, ANTs, FSL, 4 other tools, methods / tools, structural MRI / diffusion, 9 references
[9] doi:10.1162/netn_a_00382 [code]
Comparison of different group-level templates in gradient-based multimodal connectivity analysis.
Journal: Network neuroscience (Cambridge, Mass.)
In common: NetworkX, statsmodels, seaborn, 4 other tools, 13 references
[10] doi:10.1162/netn_a_00368 [code]
Modeling the impact of MRI acquisition bias on structural connectomes: Harmonizing structural connectomes.
Journal: Network neuroscience (Cambridge, Mass.)
In common: MRtrix3, ANTs, NetworkX, 7 other tools, methods / tools, structural MRI / diffusion, 6 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.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1162/imag.a.1384.svg)](https://openscicode.org/badge/doi/10.1162/imag.a.1384)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1162/imag.a.1384.svg
   :target: https://openscicode.org/badge/doi/10.1162/imag.a.1384
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1162/imag.a.1384"><img src="https://openscicode.org/badge/doi/10.1162/imag.a.1384.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge 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: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

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