OSCR

Investigating the amyloid-tau-neurodegeneration framework in Alzheimer's disease using semi-supervised multimodal imaging data fusion.

Code ↔ Paper

1 match 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.

One block of code here has a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.

The 1 match
  1. [1] § METHODS › SBF model ↔ Scripts/run_end_to_end.py, lines 536 to 594 · score 0.54 · spatial maps, dimensionality, AMY, CT, vertex, GM · block oscr:b:V2ZG2HQES8QYM-N · 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

Python · 680 lines · 33 KB · MIT · 1 match

  1. #!/usr/bin/env python3
  2. """Final ADNI SBF: fresh dictionaries and validation-selected neural state.
  3. Each invocation is one seed/round. It reads raw training and validation
  4. imaging from a view containing no held-out-test directories, learns five new
  5. dictionaries, projects/normalizes coefficients, and trains the repaired model
  6. for epochs 0..120 with fixed equal loss weights. Validation selects one epoch
  7. using conventional R2 only after positive-correlation, finite-range,
  8. prediction-scale, and calibration gates. Validation never supplies gradients
  9. and held-out test data remain inaccessible to this training process.
  10. """
  11. from __future__ import annotations
  12. import argparse
  13. import copy
  14. import csv
  15. from datetime import datetime, timezone
  16. import hashlib
  17. import json
  18. import math
  19. import os
  20. from pathlib import Path
  21. import platform
  22. import sys
  23. import nibabel as nib
  24. import numpy as np
  25. import torch
  26. from torch.utils.data import DataLoader
  27. import run_loss_ablation as base
  28. import run_nested_cv as common
  29. import sbf_utils as sbf
  30. MODALITIES = ["CT", "TAU", "PSA", "GM", "AMY"]
  31. FILETYPES = [".mgh", ".gz", ".mgh", ".gz", ".gz"]
  32. EXPECTED_N = {"train": 192, "validation": 41}
  33. UPSTREAM_COMMIT = "cb0b2e7d07526d203204df2b8822107eab78d971"
  34. def prediction_selection_gate(train_metrics: dict, validation_metrics: dict,
  35. prediction: np.ndarray,
  36. allowed_min: np.ndarray,
  37. allowed_max: np.ndarray) -> tuple[bool, dict]:
  38. """Prespecified gate applied before validation R2 can select an epoch."""
  39. required = (
  40. validation_metrics["r"], validation_metrics["r2_conventional"],
  41. validation_metrics["rmse"], validation_metrics["prediction_sd_ratio"],
  42. validation_metrics["calibration_slope_y_on_prediction"],
  43. train_metrics["r2_conventional"],
  44. )
  45. finite = bool(np.isfinite(np.asarray(required, dtype=float)).all() and
  46. np.isfinite(prediction).all())
  47. in_range = bool(finite and
  48. np.all(prediction >= allowed_min[None, :]) and
  49. np.all(prediction <= allowed_max[None, :]))
  50. positive_r = bool(finite and validation_metrics["r"] > 0.0)
  51. positive_r2 = bool(finite and validation_metrics["r2_conventional"] > 0.0)
  52. positive_train_r2 = bool(finite and train_metrics["r2_conventional"] > 0.0)
  53. sd_valid = bool(finite and
  54. 0.25 <= validation_metrics["prediction_sd_ratio"] <= 2.0)
  55. calibration_valid = bool(
  56. finite and 0.25 <=
  57. validation_metrics["calibration_slope_y_on_prediction"] <= 2.0)
  58. audit = {
  59. "finite": finite,
  60. "prediction_in_training_derived_range": in_range,
  61. "positive_validation_r": positive_r,
  62. "positive_validation_conventional_r2": positive_r2,
  63. "positive_training_conventional_r2": positive_train_r2,
  64. "validation_prediction_sd_ratio_in_0p25_to_2": sd_valid,
  65. "validation_calibration_slope_in_0p25_to_2": calibration_valid,
  66. }
  67. return bool(all(audit.values())), audit
  68. def utc_now() -> str:
  69. return datetime.now(timezone.utc).isoformat()
  70. def sha256(path: Path) -> str:
  71. digest = hashlib.sha256()
  72. with path.open("rb") as stream:
  73. for block in iter(lambda: stream.read(4 * 1024 * 1024), b""):
  74. digest.update(block)
  75. return digest.hexdigest()
  76. def write_json(path: Path, obj: object) -> None:
  77. with path.open("w") as stream:
  78. json.dump(obj, stream, indent=2, allow_nan=False, default=str)
  79. stream.write("\n")
  80. def write_csv(path: Path, rows: list[dict]) -> None:
  81. with path.open("w", newline="") as stream:
  82. writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
  83. writer.writeheader()
  84. writer.writerows(rows)
  85. def load_target(path: Path, n: int) -> np.ndarray:
  86. values = sbf.load_nidp_csv(path)
  87. target = np.asarray(values[:, [0]], dtype=np.float32)
  88. if target.shape != (n, 1) or not np.isfinite(target).all():
  89. raise ValueError(f"Invalid target {path}: {target.shape}")
  90. return target
  91. def split_name(name: str) -> str:
  92. lower = name.lower()
  93. if lower.endswith("_train"):
  94. return "train"
  95. if lower.endswith("_validation"):
  96. return "validation"
  97. if lower.endswith("_test"):
  98. raise RuntimeError(f"Held-out-test directory unexpectedly visible: {name}")
  99. raise ValueError(f"Cannot identify split: {name}")
  100. def finite_correlation_summary(maps: np.ndarray) -> dict:
  101. maps = np.asarray(maps, dtype=np.float64)
  102. if maps.ndim != 2 or maps.shape[1] != 50:
  103. raise ValueError(f"Expected feature x 50 maps, got {maps.shape}")
  104. if not np.isfinite(maps).all() or np.any(np.std(maps, axis=0) == 0):
  105. raise RuntimeError("Spatial maps are nonfinite or contain a constant component")
  106. corr = np.abs(np.corrcoef(maps.T))
  107. values = corr[np.triu_indices(50, 1)]
  108. if values.size != 1225 or not np.isfinite(values).all():
  109. raise RuntimeError("Invalid spatial-map correlation matrix")
  110. return {
  111. "median_abs_r": float(np.median(values)),
  112. "p90_abs_r": float(np.quantile(values, 0.90)),
  113. "p95_abs_r": float(np.quantile(values, 0.95)),
  114. "p99_abs_r": float(np.quantile(values, 0.99)),
  115. "max_abs_r": float(np.max(values)),
  116. "fraction_abs_r_gt_0p95": float(np.mean(values > 0.95)),
  117. }
  118. def bh_significant_loading_correlations(latent: np.ndarray,
  119. target: np.ndarray) -> dict:
  120. from scipy.stats import pearsonr
  121. target = np.asarray(target).ravel()
  122. rows = []
  123. for component in range(latent.shape[1]):
  124. result = pearsonr(np.asarray(latent[:, component]), target)
  125. rows.append({"component": component + 1,
  126. "r": float(result.statistic), "p": float(result.pvalue)})
  127. order = np.argsort([row["p"] for row in rows])
  128. m = len(rows)
  129. adjusted = np.empty(m, dtype=float)
  130. running = 1.0
  131. for rank_index in range(m - 1, -1, -1):
  132. original_index = int(order[rank_index])
  133. rank = rank_index + 1
  134. running = min(running, rows[original_index]["p"] * m / rank)
  135. adjusted[original_index] = min(1.0, running)
  136. for index, row in enumerate(rows):
  137. row["p_bh"] = float(adjusted[index])
  138. row["significant_bh_0p05"] = bool(adjusted[index] < 0.05)
  139. return {
  140. "n_significant_bh_0p05": int(sum(row["significant_bh_0p05"] for row in rows)),
  141. "median_abs_r": float(np.median(np.abs([row["r"] for row in rows]))),
  142. "max_abs_r": float(np.max(np.abs([row["r"] for row in rows]))),
  143. "components": rows,
  144. }
  145. def prepare_dictionary_data(args, output: Path, train_target: np.ndarray):
  146. fs_home = Path(os.environ["FREESURFER_HOME"])
  147. fsl_home = Path(os.environ["FSLDIR"])
  148. opts = {
  149. "brain_data_main_folder": str(Path(args.input_view)),
  150. "output_dir": str(output),
  151. "modalities_order": MODALITIES,
  152. "modalities_order_filetypes": FILETYPES,
  153. "fs_path": str(fs_home / "bin"),
  154. "path_to_fsavg": str(fs_home / "subjects" / "fsaverage"),
  155. "fsl_path": str(fsl_home),
  156. }
  157. visible = sorted(path.name for path in Path(args.input_view).iterdir()
  158. if path.is_dir())
  159. expected = sorted([f"{m}_train" for m in MODALITIES] +
  160. [f"{m}_validation" for m in MODALITIES])
  161. if visible != expected:
  162. raise RuntimeError(f"Input view must contain exactly {expected}; found {visible}")
  163. # Dummy masks allow raw validation imaging to be projected without opening
  164. # validation targets. No test directories are visible to this process.
  165. img_data, img_info, loaded_names = sbf.SBF_load(
  166. opts, train_target, np.zeros((1, 1), dtype=np.float32),
  167. np.zeros((EXPECTED_N["validation"], 1), dtype=np.float32))
  168. grouped = {split: {} for split in EXPECTED_N}
  169. for directory_name, matrix, loader_scale in zip(
  170. loaded_names, img_data, img_info["scaling_data_transform"]):
  171. split = split_name(directory_name)
  172. modality = sbf.clean_modality_name(directory_name)
  173. if modality in grouped[split]:
  174. raise RuntimeError(f"Duplicate {split} {modality}")
  175. # Match the validated adaptive-dictionary preprocessing: retain the
  176. # legacy within-split voxel centering but undo its split-specific RMS.
  177. grouped[split][modality] = np.asarray(matrix * loader_scale,
  178. dtype=np.float32)
  179. for split, n in EXPECTED_N.items():
  180. if set(grouped[split]) != set(MODALITIES):
  181. raise RuntimeError(f"Missing {split} modality: {sorted(grouped[split])}")
  182. for modality in MODALITIES:
  183. if grouped[split][modality].shape[0] != n:
  184. raise RuntimeError(f"Bad {split} {modality} shape: "
  185. f"{grouped[split][modality].shape}")
  186. train = [grouped["train"][m] for m in MODALITIES]
  187. validation = [grouped["validation"][m] for m in MODALITIES]
  188. return opts, img_info, train, validation
  189. def fresh_dictionary_stage(args, output: Path, train, validation):
  190. dictionary_dir = output / "dictionary_artifacts"
  191. coefficient_dir = output / "coefficient_diagnostics"
  192. dictionary_dir.mkdir()
  193. coefficient_dir.mkdir()
  194. # The third API slot is a duplicate of validation, solely because the
  195. # upstream function has a fixed three-split signature. It is not test data.
  196. placeholder = [matrix.copy() for matrix in validation]
  197. (dictionaries, raw_train, raw_validation, raw_placeholder,
  198. solver_diagnostics, input_transforms) = sbf.parallel_dictionary_learning(
  199. [matrix.copy() for matrix in train],
  200. [matrix.copy() for matrix in validation], placeholder,
  201. args.dictionary_dim, n_jobs=1, lambda_l1=args.alpha,
  202. projection_max_iter=args.projection_max_iter,
  203. projection_tol=args.projection_tol, random_seed=args.seed,
  204. dictionary_update_ridge=args.ridge_factor)
  205. write_json(coefficient_dir / "fista_solver_diagnostics.json",
  206. solver_diagnostics)
  207. unconverged = [(entry["modality_index"], split)
  208. for entry in solver_diagnostics
  209. for split in ("train", "validation", "test")
  210. if not entry[split]["converged"]]
  211. if unconverged:
  212. raise RuntimeError(f"Fixed-dictionary FISTA did not converge: {unconverged}")
  213. for index, (dictionary, transform) in enumerate(zip(
  214. dictionaries, input_transforms)):
  215. np.save(dictionary_dir / f"modality_{index}_dictionary.npy", dictionary)
  216. np.savez_compressed(
  217. dictionary_dir / f"modality_{index}_input_transform.npz",
  218. feature_mean=transform["feature_mean"],
  219. global_rms=np.asarray([transform["global_rms"]], dtype=np.float64))
  220. np.savez_compressed(
  221. coefficient_dir / f"modality_{index}_raw_coefficients.npz",
  222. train=raw_train[index], validation=raw_validation[index])
  223. standardized_train, standardized_validation = [], []
  224. scale_diagnostics = []
  225. for index in range(len(MODALITIES)):
  226. z_train, z_validation, z_placeholder, active, diagnostics = (
  227. sbf._coefficient_scale_guard(
  228. raw_train[index], raw_validation[index], raw_placeholder[index],
  229. args.inactive_sd_ratio))
  230. if not np.array_equal(z_validation, z_placeholder):
  231. raise RuntimeError("Validation placeholder projection was not identical")
  232. mean = np.mean(raw_train[index], axis=0, dtype=np.float64)
  233. sd = np.std(raw_train[index], axis=0, ddof=0, dtype=np.float64)
  234. np.savez_compressed(
  235. dictionary_dir / f"modality_{index}_coefficient_normalization.npz",
  236. mean=mean, sd=sd, active=active)
  237. centered = raw_train[index][:, active].astype(np.float64) - mean[active]
  238. effective_rank = int(np.linalg.matrix_rank(centered))
  239. diagnostics.update({
  240. "modality_index": index,
  241. "active_direction_indices": np.flatnonzero(active).tolist(),
  242. "active_coefficient_effective_rank": effective_rank,
  243. "third_projection_role": "validation duplicate; no test data",
  244. })
  245. if int(np.sum(active)) < 50 or effective_rank < 50:
  246. raise RuntimeError(f"Modality {index} has fewer than 50 usable directions")
  247. if diagnostics["split_stats"]["validation"]["standardized_abs_max"] > 100:
  248. raise RuntimeError(f"Modality {index} violates coefficient scale gate")
  249. standardized_train.append(z_train)
  250. standardized_validation.append(z_validation)
  251. scale_diagnostics.append(diagnostics)
  252. write_json(coefficient_dir / "scale_guard_diagnostics.json", scale_diagnostics)
  253. return dictionaries, standardized_train, standardized_validation
  254. def map_diagnostics(model, latent_train, coefficient_train, dictionaries):
  255. q = torch.softmax(model.mod_weight.detach().cpu(), dim=1).numpy()
  256. parameter_summaries, output_summaries, output_dictionary_maps = [], [], []
  257. covariate = np.ones((latent_train.shape[0], 1), dtype=np.float32)
  258. for index in range(len(MODALITIES)):
  259. parameter_dictionary = (model.spatial_loading[index].detach().cpu().numpy()
  260. * q[:, index][None, :])
  261. parameter_maps = dictionaries[index] @ parameter_dictionary
  262. output_dictionary = sbf.sKPCR_regression(
  263. latent_train, coefficient_train[index], covariate)
  264. output_maps = dictionaries[index] @ output_dictionary
  265. parameter_summaries.append({"modality_index": index,
  266. "modality": MODALITIES[index],
  267. **finite_correlation_summary(parameter_maps)})
  268. output_summaries.append({"modality_index": index,
  269. "modality": MODALITIES[index],
  270. **finite_correlation_summary(output_maps)})
  271. output_dictionary_maps.append(output_dictionary)
  272. return parameter_summaries, output_summaries, output_dictionary_maps
  273. def run(args) -> None:
  274. output = Path(args.output)
  275. if output.exists():
  276. raise FileExistsError(f"Refusing to reuse {output}")
  277. output.mkdir(parents=True)
  278. try:
  279. train_target_path = Path(args.target_train)
  280. validation_target_path = Path(args.target_validation)
  281. train_target = load_target(train_target_path, EXPECTED_N["train"])
  282. configuration = {
  283. "status": "running",
  284. "started_utc": utc_now(),
  285. "round": args.round,
  286. "seed": args.seed,
  287. "workflow": "fresh raw imaging -> fresh dictionary -> repaired neural SBF",
  288. "dictionary_learning_rerun": True,
  289. "prior_dictionary_coefficients_used_as_inputs": False,
  290. "input_view": str(Path(args.input_view)),
  291. "held_out_test_directories_visible": False,
  292. "held_out_test_imaging_accessed": False,
  293. "held_out_test_targets_accessed": False,
  294. "validation_target_used_for_model_selection": True,
  295. "validation_target_used_for_gradients": False,
  296. "dictionary": {
  297. "directions": args.dictionary_dim,
  298. "canonical_alpha": args.alpha,
  299. "ridge_policy": "factor * mean(diag(A.T @ A)) each outer iteration",
  300. "ridge_factor": args.ridge_factor,
  301. "fista_restart": "corrected O'Donoghue-Candes gradient restart",
  302. "projection_max_iter": args.projection_max_iter,
  303. "projection_tol": args.projection_tol,
  304. "n_jobs": 1,
  305. },
  306. "neural_repair": {
  307. "components": 50,
  308. "initialization": "exact released mMIGP",
  309. "uncertainty_weights": "fixed for all four loss groups",
  310. "uncertainty_optimizer": None,
  311. "uncertainty_learning_rate": None,
  312. "loss_weights": [1, 1, 1, 1],
  313. "optimizer": "RMSprop",
  314. "learning_rate": args.lr,
  315. "momentum": 0.9,
  316. "schedule": "cosine over 121 passes",
  317. "epochs_evaluated_for_selection": [10, args.epochs],
  318. "validation_checkpoint_selection": True,
  319. "selection_rule": (
  320. "among gate-passing epochs, maximize validation conventional "
  321. "R2; break ties by lower RMSE then earlier epoch"),
  322. "selection_gate": {
  323. "validation_r": ">0",
  324. "validation_conventional_r2": ">0",
  325. "training_conventional_r2": ">0",
  326. "finite_predictions": True,
  327. "validation_prediction_range": (
  328. "within train min-range to train max+range"),
  329. "validation_prediction_sd_ratio": [0.25, 2.0],
  330. "validation_calibration_slope_y_on_prediction": [0.25, 2.0],
  331. },
  332. "all_epoch_model_states_saved": True,
  333. "external_projection_bundle_saved": True,
  334. },
  335. "target_train": {"path": str(train_target_path),
  336. "sha256": sha256(train_target_path)},
  337. "target_validation": {"path": str(validation_target_path),
  338. "role": "checkpoint selection only; no gradients"},
  339. "software": {"python": platform.python_version(),
  340. "numpy": np.__version__, "torch": torch.__version__,
  341. "nibabel": nib.__version__,
  342. "upstream_commit": UPSTREAM_COMMIT},
  343. "scripts": {name: sha256(Path(__file__).parent / name) for name in
  344. ("run_end_to_end.py", "sbf_utils.py", "run_nested_cv.py",
  345. "run_loss_ablation.py")},
  346. "slurm": {key: os.environ.get(key) for key in
  347. ("SLURM_JOB_ID", "SLURM_ARRAY_JOB_ID",
  348. "SLURM_ARRAY_TASK_ID", "SLURM_CPUS_PER_TASK")},
  349. }
  350. write_json(output / "configuration.json", configuration)
  351. opts, img_info, raw_train, raw_validation = prepare_dictionary_data(
  352. args, output, train_target)
  353. dictionaries, x_train, x_validation = fresh_dictionary_stage(
  354. args, output, raw_train, raw_validation)
  355. y_mean = train_target.mean(axis=0)
  356. y_sd = train_target.std(axis=0)
  357. y_sd[y_sd == 0] = 1.0
  358. y_train_z = ((train_target - y_mean) / y_sd).astype(np.float32)
  359. validation_target = load_target(validation_target_path,
  360. EXPECTED_N["validation"])
  361. validation_target_sha = sha256(validation_target_path)
  362. y_validation_z = ((validation_target - y_mean) / y_sd).astype(np.float32)
  363. target_min = np.min(train_target, axis=0)
  364. target_max = np.max(train_target, axis=0)
  365. target_range = np.maximum(target_max - target_min, y_sd)
  366. allowed_min = target_min - target_range
  367. allowed_max = target_max + target_range
  368. device = torch.device(args.device)
  369. model, initialization = common.build_model(
  370. x_train, y_train_z, args.seed, args.dropout, device)
  371. loss_fun = sbf.loss_SuperBigFLICA_regression(
  372. 1, len(x_train), len(train_target), device=device,
  373. auto_weight=[0, 0, 0, 0], lambdas=[1, 1, 1, 1]).to(device)
  374. optimizer = torch.optim.RMSprop(model.parameters(), lr=args.lr,
  375. momentum=0.9)
  376. generator = torch.Generator().manual_seed(args.seed + 900)
  377. loader = DataLoader(sbf.load_Multimodal_data(x_train, y_train_z),
  378. batch_size=args.batch_size, shuffle=True,
  379. generator=generator)
  380. scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
  381. optimizer, T_max=(args.epochs + 1) * len(loader))
  382. configuration["initialization_diagnostics"] = initialization
  383. write_json(output / "configuration.json", configuration)
  384. history, states = [], {}
  385. selected = None
  386. for epoch in range(args.epochs + 1):
  387. torch.manual_seed(args.seed + epoch)
  388. model.train()
  389. sums = np.zeros(5, dtype=float)
  390. for batch, labels in loader:
  391. batch = [item.to(device) for item in batch]
  392. labels = labels.to(device)
  393. optimizer.zero_grad(set_to_none=True)
  394. outputs = model(batch, device)
  395. losses = loss_fun(outputs[0], batch, outputs[1], outputs[3],
  396. labels, outputs[4], outputs[2])
  397. losses[0].backward()
  398. optimizer.step()
  399. scheduler.step()
  400. sums += np.asarray([float(value.detach().cpu()) for value in losses])
  401. train_eval = common.evaluate(model, x_train, y_train_z,
  402. y_mean, y_sd, device)
  403. validation_eval = common.evaluate(
  404. model, x_validation, y_validation_z, y_mean, y_sd, device)
  405. gate, gate_audit = prediction_selection_gate(
  406. train_eval["prediction"], validation_eval["prediction"],
  407. validation_eval["predicted_values"], allowed_min, allowed_max)
  408. sigma_values = {
  409. name: getattr(loss_fun, name).detach().cpu().numpy().tolist()
  410. for name in ("sigma1", "sigma2", "sigma3", "sigma4", "sigma5")
  411. }
  412. row = {"epoch": epoch, "selection_gate_pass": gate}
  413. row.update({f"loss_{name}": float(sums[index] / len(loader))
  414. for index, name in enumerate(("total", "reconstruction",
  415. "spatial", "target",
  416. "prediction_penalty"))})
  417. row.update({f"train_{key}": value
  418. for key, value in train_eval["prediction"].items()})
  419. row.update({f"validation_{key}": value
  420. for key, value in validation_eval["prediction"].items()})
  421. row.update({f"gate_{key}": value for key, value in gate_audit.items()})
  422. history.append(row)
  423. states[epoch] = copy.deepcopy(model.state_dict())
  424. if gate and epoch >= 10:
  425. candidate_key = (
  426. float(validation_eval["prediction"]["r2_conventional"]),
  427. -float(validation_eval["prediction"]["rmse"]),
  428. -int(epoch),
  429. )
  430. if selected is None or candidate_key > selected["key"]:
  431. selected = {
  432. "key": candidate_key,
  433. "epoch": epoch,
  434. "model_state": copy.deepcopy(model.state_dict()),
  435. "uncertainty_state": copy.deepcopy(loss_fun.state_dict()),
  436. "train_prediction": train_eval["prediction"],
  437. "validation_prediction": validation_eval["prediction"],
  438. "gate_audit": gate_audit,
  439. "sigma_values": sigma_values,
  440. }
  441. print(json.dumps({"round": args.round, "epoch": epoch,
  442. "loss_total": row["loss_total"],
  443. "gate": gate,
  444. "validation_r": row["validation_r"],
  445. "validation_r2": row["validation_r2_conventional"]}),
  446. flush=True)
  447. if len(states) != args.epochs + 1:
  448. raise RuntimeError("Not all epoch states were retained")
  449. if selected is None:
  450. raise RuntimeError("No epoch passed the prespecified selection gate")
  451. write_csv(output / "training_loss_history.csv", history)
  452. torch.save(states, output / "all_epoch_model_states.pth")
  453. model.load_state_dict(selected["model_state"])
  454. loss_fun.load_state_dict(selected["uncertainty_state"])
  455. train_eval = common.evaluate(model, x_train, y_train_z,
  456. y_mean, y_sd, device)
  457. validation_eval = common.evaluate(model, x_validation,
  458. y_validation_z, y_mean, y_sd, device)
  459. parameter_spatial, output_spatial, output_dictionary_maps = (
  460. map_diagnostics(model, train_eval["latent"], x_train, dictionaries))
  461. loading_target = bh_significant_loading_correlations(
  462. train_eval["latent"], train_target)
  463. torch.save(selected["model_state"], output / "selected_model_state.pth")
  464. torch.save(selected["uncertainty_state"],
  465. output / "selected_uncertainty_state.pth")
  466. np.savez_compressed(
  467. output / "selected_results.npz",
  468. selected_epoch=np.asarray([selected["epoch"]], dtype=np.int64),
  469. latent_train=train_eval["latent"],
  470. latent_validation=validation_eval["latent"],
  471. prediction_train=train_eval["predicted_values"],
  472. prediction_validation=validation_eval["predicted_values"],
  473. modality_weights=torch.softmax(
  474. model.mod_weight.detach().cpu(), dim=1).numpy(),
  475. prediction_weights=model.weight_pred.detach().cpu().numpy())
  476. np.savez_compressed(
  477. output / "target_normalization.npz",
  478. mean=y_mean.astype(np.float64), sd=y_sd.astype(np.float64),
  479. training_min=target_min.astype(np.float64),
  480. training_max=target_max.astype(np.float64),
  481. allowed_min=allowed_min.astype(np.float64),
  482. allowed_max=allowed_max.astype(np.float64))
  483. architecture = {
  484. "model_class": "SupervisedFLICAmodel",
  485. "modalities": MODALITIES,
  486. "standardized_coefficient_dimensions": [
  487. int(matrix.shape[1]) for matrix in x_train],
  488. "components": 50,
  489. "targets": 1,
  490. "dropout": args.dropout,
  491. "target_standardization": "training mean and population SD",
  492. }
  493. write_json(output / "model_architecture.json", architecture)
  494. projection_artifacts = [
  495. output / "selected_model_state.pth",
  496. output / "target_normalization.npz",
  497. output / "model_architecture.json",
  498. ]
  499. for index in range(len(MODALITIES)):
  500. projection_artifacts.extend([
  501. output / "dictionary_artifacts" /
  502. f"modality_{index}_dictionary.npy",
  503. output / "dictionary_artifacts" /
  504. f"modality_{index}_input_transform.npz",
  505. output / "dictionary_artifacts" /
  506. f"modality_{index}_coefficient_normalization.npz",
  507. ])
  508. projection_manifest = {
  509. "schema_version": 1,
  510. "purpose": (
  511. "Locked external-cohort projection without dictionary learning, "
  512. "neural retraining, or checkpoint reselection"),
  513. "round": args.round,
  514. "seed": args.seed,
  515. "selected_epoch": selected["epoch"],
  516. "modality_order": MODALITIES,
  517. "raw_feature_counts": [int(matrix.shape[1]) for matrix in raw_train],
  518. "standardized_coefficient_dimensions": [
  519. int(matrix.shape[1]) for matrix in x_train],
  520. "input_contract": (
  521. "Each external matrix must be participant x feature, use the "
  522. "same modality-specific vertex/voxel order and support as ADNI, "
  523. "and receive no cohort-specific refitting."),
  524. "dictionary_projection": {
  525. "alpha": args.alpha,
  526. "max_iter": args.projection_max_iter,
  527. "tol": args.projection_tol,
  528. "fista_restart": "corrected O'Donoghue-Candes gradient restart",
  529. },
  530. "artifacts": [{
  531. "relative_path": str(path.relative_to(output)),
  532. "bytes": path.stat().st_size,
  533. "sha256": sha256(path),
  534. } for path in projection_artifacts],
  535. "held_out_test_used_to_fit_or_select": False,
  536. }
  537. write_json(output / "external_projection_bundle_manifest.json",
  538. projection_manifest)
  539. map_dir = output / f"spatial_maps_selected_epoch{selected['epoch']}_raw_pre_gmm"
  540. map_dir.mkdir()
  541. sbf.SBF_save_everything(str(map_dir), output_dictionary_maps,
  542. img_info, {**opts,
  543. "modalities_order_filetypes": FILETYPES,
  544. "modalities_order": MODALITIES}, dictionaries)
  545. map_files = sorted(path for path in map_dir.iterdir() if path.is_file())
  546. map_manifest = [{"path": str(path), "bytes": path.stat().st_size,
  547. "sha256": sha256(path)} for path in map_files]
  548. # CT and PSA each produce LH/RH MGH files; TAU, GM, and AMY each
  549. # produce one NIfTI, for seven files covering five modalities.
  550. if len(map_manifest) != 7:
  551. raise RuntimeError(f"Expected seven selected output images, got {len(map_manifest)}")
  552. result = {
  553. "status": "success",
  554. "round": args.round,
  555. "seed": args.seed,
  556. "dictionary_learning_rerun": True,
  557. "prior_dictionary_coefficients_used_as_inputs": False,
  558. "selected_epoch": selected["epoch"],
  559. "selection_rule": configuration["neural_repair"]["selection_rule"],
  560. "selection_gate_audit": selected["gate_audit"],
  561. "selected_uncertainty_values": selected["sigma_values"],
  562. "selected_result": {
  563. "training_prediction": train_eval["prediction"],
  564. "validation_prediction": validation_eval["prediction"],
  565. "training_coefficient_reconstruction_r2_by_modality":
  566. train_eval["reconstruction_r2"],
  567. "validation_coefficient_reconstruction_r2_by_modality":
  568. validation_eval["reconstruction_r2"],
  569. "training_loading_target_correlations": loading_target,
  570. "raw_parameter_map_collinearity": parameter_spatial,
  571. "raw_skpcr_output_map_collinearity": output_spatial,
  572. },
  573. "selected_raw_pre_gmm_map_manifest": map_manifest,
  574. "external_projection_bundle_manifest": {
  575. "path": str(output / "external_projection_bundle_manifest.json"),
  576. "sha256": sha256(
  577. output / "external_projection_bundle_manifest.json"),
  578. },
  579. "validation_checkpoint_selection": True,
  580. "held_out_test_evaluated": False,
  581. }
  582. write_json(output / "results.json", result)
  583. configuration.update({
  584. "status": "success",
  585. "completed_utc": utc_now(),
  586. "validation_target_used_for_model_selection": True,
  587. "validation_target_used_for_gradients": False,
  588. "target_validation": {"path": str(validation_target_path),
  589. "sha256": validation_target_sha},
  590. "held_out_test_imaging_accessed": False,
  591. "held_out_test_targets_accessed": False,
  592. "held_out_test_evaluated": False,
  593. })
  594. write_json(output / "configuration.json", configuration)
  595. (output / "_SUCCESS").write_text(
  596. "fresh dictionaries + fixed uncertainty + validation-R2-selected SBF; test absent\n")
  597. except Exception as error:
  598. if output.exists():
  599. write_json(output / "_FAILURE.json", {
  600. "status": "failed", "failed_utc": utc_now(),
  601. "error_type": type(error).__name__, "error": str(error)})
  602. raise
  603. def main() -> None:
  604. parser = argparse.ArgumentParser()
  605. parser.add_argument("--round", type=int, required=True)
  606. parser.add_argument("--seed", type=int, required=True)
  607. parser.add_argument("--output", required=True)
  608. parser.add_argument("--input-view", required=True)
  609. parser.add_argument("--target-train", required=True)
  610. parser.add_argument("--target-validation", required=True)
  611. parser.add_argument("--dictionary-dim", type=int, default=250)
  612. parser.add_argument("--alpha", type=float, default=0.1)
  613. parser.add_argument("--ridge-factor", type=float, default=1e-4)
  614. parser.add_argument("--inactive-sd-ratio", type=float, default=1e-3)
  615. parser.add_argument("--projection-max-iter", type=int, default=5000)
  616. parser.add_argument("--projection-tol", type=float, default=1e-5)
  617. parser.add_argument("--epochs", type=int, default=120)
  618. parser.add_argument("--lr", type=float, default=0.01)
  619. parser.add_argument("--batch-size", type=int, default=32)
  620. parser.add_argument("--dropout", type=float, default=0.2)
  621. parser.add_argument("--device", default="cpu")
  622. args = parser.parse_args()
  623. if args.epochs != 120 or args.dictionary_dim != 250:
  624. raise ValueError("This confirmatory workflow requires epochs=120 and dictionary_dim=250")
  625. run(args)
  626. if __name__ == "__main__":
  627. try:
  628. main()
  629. except Exception as error:
  630. print(f"FATAL: {type(error).__name__}: {error}", file=sys.stderr,
  631. flush=True)
  632. raise

run_end_to_end.py at commit 61a12c5, under MIT · at the source

Overview

Authors: You Cheng1,2,3, Adrián Medina1,2, Cole Korponay1,2,3, Christian F Beckmann4,5, David Harper1,2,3, Lisa Nickerson1,2,3, for the Alzheimer's Disease Neuroimaging Initiative
ORCID iDs: You Cheng
  1. McLean Hospital, Belmont, Massachusetts, USA
  2. Mass General Brigham, Boston, Massachusetts, USA
  3. Department of Psychiatry, Harvard Medical School, Boston, Massachusetts, USA
  4. Donders Institute for Brain, Cognition and Behaviour, Department of Medical Neuroscience, Radboud University Medical Centre, Nijmegen, the Netherlands
  5. Centre for Functional MRI of the Brain (FMRIB), Nuffield Department of Clinical Neurosciences, Wellcome Centre for Integrative Neuroimaging, University of Oxford, Oxford, UK
Journal: Alzheimer's & dementia (Amsterdam, Netherlands), volume 18, issue 2, article e70360
Dates: received 4 December 2025; accepted 19 April 2026; published online 21 May 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1002/dad2.70360 · PMID 42255959 · PMCID PMC13239803 · OpenAlex W7161954574
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: other condition (population), Alzheimer's / dementia (population)
Methods: Smoothing, state filtering, decompositions, Machine learning, Statistics, Preprocessing
Keywords: Alzheimer's disease, amyloid–tau–neurodegeneration framework, latent components, multimodal data fusion, multimodal neuroimaging, semi‐supervised learning
Topic: Dementia and Cognitive Impairment Research (Psychiatry and Mental health, Medicine), according to OpenAlex
Funding: Wellcome Trust (215573/Z/19/Z); Dutch Research Council (NWO) (17854); NIA NIH HHS (RF1 AG078304, U01 AG024904)
Citations: not cited yet (Europe PMC); 42 references in the paper

Abstract

INTRODUCTION: Alzheimer's disease (AD) heterogeneity complicates diagnosis and prognosis. Uncovering amyloid–tau–neurodegeneration (A–T–N) patterns may improve diagnostic prediction.

METHODS: We applied SuperBigFLICA (SBF), a semi‐supervised multimodal fusion method, to gray matter density, cortical thickness (CT), pial surface area, amyloid and tau positron emission tomography maps from 274 Alzheimer's Disease Neuroimaging Initiative 3 participants to derive 50 latent components predictive of cognitive decline. Subject loadings were then used to predict diagnosis (cognitively normal, mild cognitive impairment, dementia) and apolipoprotein E (APOE) ε4 status via least absolute shrinkage and selection operator logistic regression, compared to demographic, single‐modality, and naïve fusion comparator models.

RESULTS: SBF modestly predicted out‐of‐sample concurrent clinical severity (Clinical Dementia Rating Sum of Boxes; r = 0.21), yet models using SBF‐derived loadings were among the strongest comparator models (area under the receiver operating characteristic curve; = 0.80 for diagnosis; 0.83 for APOE ε4). Amyloid alterations in sensory areas best separated dementia, while a tri‐modal tau–neurodegeneration pattern related to disease progression. Loadings were validated through cerebrospinal fluid correlations.

DISCUSSION: SBF improves prediction and reveals interpretable patterns that better classify clinical diagnoses and APOE ε4 than traditional approaches.

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

Repository

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

ANSR-laboratory/SuperBigFLICA_McL

License: MIT
State: the link answers, verified on 29 October 2026
Evidence: files inventoried
Commit: 61a12c5085b8d762d71bd42353f6b6ee38d498fa, 12 October 2026
Languages: Python (10), Shell (1)
Size: 29 files, 11 scripts
Software Heritage: not archived
Found in: “CODE AVAILABILITY”
Holds: README, license file, environment (requirements.macos.txt, requirements.txt)
Not found: CITATION.cff, tests, continuous integration, documentation
Tools: FreeSurfer (2 files), FSL (2 files), NiBabel (2 files), NumPy (2 files), pandas (2 files), PyTorch (2 files), SciPy (1 file)
Availability: 2 checks, the latest on 29 October 2026: the link answers
  • 29 October 2026: the link answers
  • 28 September 2026: the link answers
13 files

Code availability

All code for multimodal data fusion and model training, along with the corresponding model cards, is publicly available on GitHub https://github.com/ANSR‐laboratory/SuperBigFLICA_McL.

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

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;
  • 11 scripts, each with its path and the digest of its content;
  • 1 match 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

Neuroimaging and clinical data were obtained from the Alzheimer's Disease Neuroimaging Initiative (ADNI; http://adni.loni.usc.edu) and can be accessed upon approval of a data use application.

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, 28 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 7 authors, 6 keywords, 3 funders, 39 references.

Cite

This paper

Cheng, Y., Medina, A., Korponay, C., Beckmann, C. F., Harper, D., Nickerson, L., & for the Alzheimer's Disease Neuroimaging Initiative. (2026). Investigating the amyloid-tau-neurodegeneration framework in Alzheimer's disease using semi-supervised multimodal imaging data fusion. Alzheimer's & dementia (Amsterdam, Netherlands), 18(2), e70360. https://doi.org/10.1002/dad2.70360

BibTeX

@article{cheng2026investigating,
author = {Cheng, You and Medina, Adrián and Korponay, Cole and Beckmann, Christian F and Harper, David and Nickerson, Lisa and {for the Alzheimer's Disease Neuroimaging Initiative}},
title = {{Investigating the amyloid-tau-neurodegeneration framework in Alzheimer's disease using semi-supervised multimodal imaging data fusion}},
journal = {Alzheimer's \& dementia (Amsterdam, Netherlands)},
year = {2026},
month = apr,
volume = {18},
number = {2},
pages = {e70360},
publisher = {Wiley},
issn = {2352-8729},
doi = {10.1002/dad2.70360},
url = {https://doi.org/10.1002/dad2.70360},
pmid = {42255959},
pmcid = {PMC13239803}
}

RIS

TY - JOUR
AU - Cheng, You
AU - Medina, Adrián
AU - Korponay, Cole
AU - Beckmann, Christian F
AU - Harper, David
AU - Nickerson, Lisa
AU - for the Alzheimer's Disease Neuroimaging Initiative
TI - Investigating the amyloid-tau-neurodegeneration framework in Alzheimer's disease using semi-supervised multimodal imaging data fusion
T2 - Alzheimer's & dementia (Amsterdam, Netherlands)
J2 - Alzheimers Dement (Amst)
PY - 2026
DA - 2026/04/01
VL - 18
IS - 2
SP - e70360
SN - 2352-8729
PB - Wiley
DO - 10.1002/dad2.70360
UR - https://doi.org/10.1002/dad2.70360
LA - en
ER -

CSL-JSON

{
"id": "10.1002/dad2.70360",
"type": "article-journal",
"title": "Investigating the amyloid-tau-neurodegeneration framework in Alzheimer's disease using semi-supervised multimodal imaging data fusion",
"container-title": "Alzheimer's & dementia (Amsterdam, Netherlands)",
"author": [
{
"family": "Cheng",
"given": "You"
},
{
"family": "Medina",
"given": "Adrián"
},
{
"family": "Korponay",
"given": "Cole"
},
{
"family": "Beckmann",
"given": "Christian F"
},
{
"family": "Harper",
"given": "David"
},
{
"family": "Nickerson",
"given": "Lisa"
},
{
"literal": "for the Alzheimer's Disease Neuroimaging Initiative"
}
],
"container-title-short": "Alzheimers Dement (Amst)",
"volume": "18",
"issue": "2",
"page": "e70360",
"DOI": "10.1002/dad2.70360",
"PMID": "42255959",
"PMCID": "PMC13239803",
"ISSN": "2352-8729",
"publisher": "Wiley",
"URL": "https://doi.org/10.1002/dad2.70360",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
1
]
]
}
}

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.1093/psyrad/kkad026 [code]
Data-driven multimodal fusion: approaches and applications in psychiatric research.
Journal: Psychoradiology
In common: PyTorch, pandas, SciPy, 1 other tool, 5 references
[2] doi:10.3389/fnins.2023.1225606 [code]
Harmonization of multi-site functional MRI data with dual-projection based ICA model.
Journal: Frontiers in neuroscience
In common: FreeSurfer, FSL, NiBabel, 3 other tools, 4 references
[3] doi:10.1162/imag_a_00388 [code]
DPABI harmonization: A toolbox for harmonizing multi-site brain imaging for big-data era.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: FreeSurfer, FSL, NiBabel, 3 other tools, 4 references
[4] doi:10.1073/pnas.2216399120 [code]
Robust machine learning segmentation for large-scale analysis of heterogeneous clinical brain MRI datasets.
Journal: Proceedings of the National Academy of Sciences of the United States of America
In common: FreeSurfer, NiBabel, SciPy, 1 other tool, author You Cheng
[5] doi:10.1162/imag.a.1031 [code]
Multiscale modes of functional brain connectivity.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: FreeSurfer, FSL, NiBabel, 3 other tools, 2 references
[6] 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: FreeSurfer, FSL, NiBabel, 3 other tools, 3 references
[7] doi:10.1038/s41597-023-02421-7 [code]
Efficacy of MRI data harmonization in the age of machine learning: a multicenter study across 36 datasets.
Journal: Scientific data
In common: FreeSurfer, FSL, NiBabel, 3 other tools, 3 references
[8] doi:10.1038/s43587-026-01121-2 [code]
Predicting categorical and continuous Alzheimer's disease outcomes from a single MRI scan.
Journal: Nature aging
In common: NiBabel, PyTorch, SciPy, 1 other tool, Alzheimer's / dementia, 3 references
[9] doi:10.1162/imag.a.1140 [code]
Cross-site quantitative MRI harmonization: The impact on age modeling in health and disease.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: FreeSurfer, NiBabel, PyTorch, 3 other tools, 3 references
[10] doi:10.1162/imag.a.1099 [code]
Multi-site harmonization for magnetoencephalography spectral power data.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: FreeSurfer, NiBabel, PyTorch, 3 other tools, 3 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.1002/dad2.70360.svg)](https://openscicode.org/badge/doi/10.1002/dad2.70360)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1002/dad2.70360.svg
   :target: https://openscicode.org/badge/doi/10.1002/dad2.70360
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1002/dad2.70360"><img src="https://openscicode.org/badge/doi/10.1002/dad2.70360.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.