OSCR

Brain MRI Dataset Featuring a Full Clinical Protocol With and Without Intentional Motion.

Code ↔ Paper

5 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 5 matches
  1. [1] § Technical Validation › Registration and Analysis ↔ MotionCorrectedClinicalMRProtocol/analysis_img_quality.py, lines 15–74 · score 0.71 · FreeSurfer, uncorrected scan, ground truth, T1 MPR, motion correction, prospective
  2. [2] § Technical Validation › Observer scores ↔ MotionCorrectedClinicalMRProtocol/generate_plots_manuscript.py, lines 582–650 · score 0.63 · T1 STIR, T2 TSE, T2 FLAIR, 1–5, T1 MPR, motion
  3. [3] § Methods › Clinical MRI protocol ↔ MotionCorrectedClinicalMRProtocol/generate_plots_manuscript.py, lines 582–650 · score 0.61 · T1 STIR, T2 TSE, T2 FLAIR, T1 MPR, DWI, MR
  4. [4] § Data Records ↔ MotionCorrectedClinicalMRProtocol/recon_register.py, lines 8–88 · score 0.58 · T1 TIRM, T2 TSE, FreeSurfer, MPRAGE, FLAIR, motion correction
  5. [5] § Background & Summary ↔ MotionCorrectedClinicalMRProtocol/generate_plots_manuscript.py, lines 527–580 · score 0.55 · image quality metrics, observer scores, retrospective, PMC, prospective, motion correction

Paper

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

The paper is loaded when this pane is shown.

The authors' code

Python · 1,187 lines · 47 KB · MIT · 3 matches

  1. import numpy as np
  2. import matplotlib
  3. import matplotlib.pyplot as plt
  4. import glob
  5. import os
  6. import string
  7. import nibabel as nib
  8. from statsmodels.stats.multitest import multipletests
  9. from utils import Show_Stars, SortFiles, MakeBoxplot, DrawLines2, DrawLines
  10. from statistical_tests import PerformWilcoxonMotion, PerformWilcoxonAllImg
  11. plt.style.use('seaborn-whitegrid')
  12. matplotlib.rc('axes', edgecolor='black')
  13. from matplotlib.ticker import ScalarFormatter
  14. out_dir = '../Results/Plots/'
  15. in_dir_mot = '../Results/Motion_Estimates/'
  16. in_dir_met = '../Results/Metrics_Results/'
  17. in_dir_qs = '../ObserverQualityScores/'
  18. out_dir_metrics = '../Results/Metrics_Results/Comparison/'
  19. subdir = []
  20. for i in range(1,10):
  21. subdir.append('Subject_0'+str(i)+'/')
  22. for i in range(10,20):
  23. subdir.append('Subject_'+str(i)+'/')
  24. for i in range(20,23):
  25. subdir.append('Subject_'+str(i)+'/')
  26. sequs = ['T1_MPR', 'T2_FLAIR', 'T2_TSE', 'T1_TIRM', 'T2STAR', 'DIFF']
  27. save = '_2022_05_27'
  28. plot_motion = True
  29. plot_still = True
  30. plot_nod = True
  31. plot_DWI = True
  32. calc_ADC_hist = True
  33. ''' (1) Plot motion data: '''
  34. if plot_motion:
  35. # calculate p-values - first STILL, then NOD, then SHAKE, in each
  36. # cathegory: RMS, then median, then maximum
  37. p_values = []
  38. effect_size = []
  39. for mot in ['STILL', 'NOD', 'SHAKE']:
  40. RMS, median, maxim, descr = [], [], [], []
  41. for sequ in sequs:
  42. if mot == 'SHAKE' and sequ != 'T1_MPR':
  43. continue
  44. # find the most recent data:
  45. file = glob.glob(in_dir_mot+'MotionMetrics_'+mot+'/'+sequ+'*.txt')
  46. file = [f for f in file if 'mid' not in f] #sort out 'mid'
  47. if len(file)>0:
  48. file = SortFiles(file)
  49. metrics = np.loadtxt(file[0], unpack=True, skiprows=1)
  50. RMS.append(metrics[0])
  51. RMS.append(metrics[3])
  52. median.append(metrics[1])
  53. median.append(metrics[4])
  54. maxim.append(metrics[2])
  55. maxim.append(metrics[5])
  56. descr.append(sequ)
  57. descr.append(sequ)
  58. p_val, ind, alt, ES = PerformWilcoxonMotion(['RMS', 'Med', 'Max'], mot,
  59. [RMS, median, maxim],
  60. in_dir_mot, save,)
  61. p_values.append(p_val)
  62. effect_size.append(ES)
  63. #correct for multiple comparisons:
  64. p_values = np.concatenate(p_values)
  65. rej, p_values_cor, _, __ = multipletests(p_values, alpha=0.05,
  66. method='fdr_bh', is_sorted=False,
  67. returnsorted=False)
  68. p_values_cor_still = p_values_cor[0:18]
  69. p_values_cor_nod = p_values_cor[18:36]
  70. p_values_cor_shake = p_values_cor[36:]
  71. ind_p = np.array([[0,1], [2,3], [4,5], [6,7], [8,9], [10,11]])
  72. ind_sh = np.array([[0,1]])
  73. # plot:
  74. num = 0
  75. plt.figure(figsize=(13,10))
  76. for mot in ['STILL', 'NOD']:
  77. RMS, median, maxim, descr = [], [], [], []
  78. for sequ in sequs:
  79. # find the most recent data:
  80. file = glob.glob(in_dir_mot+'MotionMetrics_'+mot+'/'+sequ+'*.txt')
  81. file = [f for f in file if 'mid' not in f] # sort out mid
  82. if len(file)>0:
  83. file = SortFiles(file)
  84. # load the most recent file:
  85. metrics = np.loadtxt(file[0], unpack=True, skiprows=1)
  86. RMS.append(metrics[0])
  87. RMS.append(metrics[3])
  88. median.append(metrics[1])
  89. median.append(metrics[4])
  90. maxim.append(metrics[2])
  91. maxim.append(metrics[5])
  92. descr.append(sequ)
  93. descr.append(sequ)
  94. if mot == 'NOD':
  95. mot_s = 'SHAKE'
  96. RMS_s, median_s, maxim_s, descr_s = [], [], [], []
  97. sequ = 'T1_MPR'
  98. # find the most recent data:
  99. file = glob.glob(in_dir_mot+'MotionMetrics_'+mot_s+'/'+sequ+'*.txt')
  100. file = [f for f in file if 'mid' not in f] # sort out mid
  101. if len(file)>0:
  102. file = SortFiles(file)
  103. # load the most recent file
  104. metrics = np.loadtxt(file[0], unpack=True, skiprows=1)
  105. RMS_s.append(metrics[0])
  106. RMS_s.append(metrics[3])
  107. median_s.append(metrics[1])
  108. median_s.append(metrics[4])
  109. maxim_s.append(metrics[2])
  110. maxim_s.append(metrics[5])
  111. descr_s.append(sequ)
  112. descr_s.append(sequ)
  113. mean_RMS_s, mean_med_s, mean_max_s = [], [], []
  114. for i in range(len(RMS_s)):
  115. mean_RMS_s.append(np.mean(RMS_s[i]))
  116. mean_med_s.append(np.mean(median_s[i]))
  117. mean_max_s.append(np.mean(maxim_s[i]))
  118. # calculate mean values and define colors
  119. mean_RMS, mean_med, mean_max = [], [], []
  120. for i in range(len(RMS)):
  121. mean_RMS.append(np.mean(RMS[i]))
  122. mean_med.append(np.mean(median[i]))
  123. mean_max.append(np.mean(maxim[i]))
  124. colors = []
  125. labels = []
  126. for i in range(int(len(RMS)/2)):
  127. colors.append('tab:orange')
  128. colors.append('tab:blue')
  129. labels.append('without PMC')
  130. labels.append('with PMC')
  131. small = dict(markersize=3)
  132. # change 'TIRM' into STIR for descr:
  133. # and change 'TRACEW_B0' to 'DWI'
  134. for i in range(len(descr)):
  135. if descr[i]=='TRACEW_B0':
  136. descr[i]='DWI'
  137. if descr[i]=='T1_TIRM':
  138. descr[i]='T1_STIR'
  139. if descr[i]=='T2STAR':
  140. descr[i]='T2*'
  141. # plot the data:
  142. if mot=='STILL':
  143. ax0=plt.subplot2grid((4,5), (0,0), colspan=4)
  144. ax = ax0
  145. else:
  146. ax1=plt.subplot2grid((4,5), (2,0), colspan=4)
  147. ax = ax1
  148. MakeBoxplot(RMS, colors)
  149. for i in range(len(mean_RMS)):
  150. plt.plot(i+1, mean_RMS[i], '.', c=colors[i], ls='')
  151. if mot=='STILL':
  152. for y1, y2 in zip(RMS[4], RMS[5]):
  153. plt.plot([5,6], [y1, y2], 'darkslategray', lw=0.7)
  154. for y1, y2 in zip(RMS[8], RMS[9]):
  155. plt.plot([9,10], [y1, y2], 'darkslategray', lw=0.7)
  156. plt.title(mot+' scans', fontsize=17)
  157. plt.ylabel('RMS displ [mm]')
  158. plt.xticks(ticks=np.arange(1, len(RMS)+1), labels=descr)
  159. lim = plt.gca().get_ylim()
  160. plt.ylim(lim[0],(lim[1]-lim[0])*1.2+lim[0])
  161. ax.text(-0.1, .95, string.ascii_lowercase[num], transform=ax.transAxes,
  162. size=20, weight='bold')
  163. num += 1
  164. if mot=='STILL':
  165. use = 0
  166. low = -1
  167. if mot == 'NOD':
  168. use = 1
  169. low = -4
  170. max_RMS = [np.amax(RMS[i]) for i in range(len(RMS))]
  171. if mot=='STILL':
  172. Show_Stars(p_values_cor_still[0:6], ind_p, np.arange(1, len(RMS)+1),
  173. max_RMS, dh=0.05, col='black')
  174. ax01=plt.subplot2grid((4,5), (1,0), colspan=4)
  175. ax = ax01
  176. else:
  177. Show_Stars(p_values_cor_nod[0:6], ind_p, np.arange(1, len(RMS)+1),
  178. max_RMS, col='black')
  179. ax2=plt.subplot2grid((4,5), (3,0), colspan=4)
  180. ax = ax2
  181. MakeBoxplot(maxim, colors)
  182. for i in range(0,2):
  183. plt.plot(i+1, mean_max[i], '.', c=colors[i], ls='',
  184. label=labels[i])
  185. for i in range(2,len(mean_RMS)):
  186. plt.plot(i+1, mean_max[i], '.', c=colors[i], ls='')
  187. if mot=='STILL':
  188. for y1, y2 in zip(maxim[4], maxim[5]):
  189. plt.plot([5,6], [y1, y2], 'darkslategray', lw=0.7)
  190. for y1, y2 in zip(maxim[8], maxim[9]):
  191. plt.plot([9,10], [y1, y2], 'darkslategray', lw=0.7)
  192. plt.ylabel('Maximum displ [mm]')
  193. plt.xticks(ticks=np.arange(1, len(RMS)+1), labels=descr)
  194. lim = plt.gca().get_ylim()
  195. plt.ylim(lim[0],(lim[1]-lim[0])*1.1+lim[0])
  196. ax.text(-0.1, .95, string.ascii_lowercase[num], transform=ax.transAxes,
  197. size=20, weight='bold')
  198. num += 1
  199. if mot=='STILL':
  200. use = 0
  201. low = -3
  202. max_max = [np.amax(maxim[i]) for i in range(len(RMS))]
  203. if mot=='STILL':
  204. Show_Stars(p_values_cor_still[12:], ind_p, np.arange(1, len(RMS)+1),
  205. max_max, col='black')
  206. legend = plt.legend(loc='upper center', bbox_to_anchor=(1.16, 1.3),
  207. fontsize=13, frameon=True)
  208. else:
  209. Show_Stars(p_values_cor_nod[12:], ind_p, np.arange(1, len(RMS)+1),
  210. max_max, col='black')
  211. if mot == 'NOD':
  212. ax4=plt.subplot2grid((4,5), (2,4))
  213. ax = ax4
  214. ax1.get_shared_y_axes().join(ax1, ax4)
  215. MakeBoxplot(RMS_s, colors)
  216. for i in range(len(mean_RMS_s)):
  217. plt.plot(i+1, mean_RMS_s[i], '.', c=colors[i], ls='')
  218. plt.title(mot_s+' scans', fontsize=17)
  219. plt.xticks(ticks=np.arange(1, len(RMS_s)+1), labels=descr_s)
  220. lim = plt.gca().get_ylim()
  221. plt.ylim(lim[0],(lim[1]-lim[0])*1.1+lim[0])
  222. ax.text(-0.3, .95, string.ascii_lowercase[num],
  223. transform=ax.transAxes, size=20, weight='bold')
  224. num += 1
  225. max_RMS = [np.amax(RMS_s[i]) for i in range(len(RMS_s))]
  226. Show_Stars(np.array([p_values_cor_shake[0]]), ind_sh,
  227. np.arange(1, len(RMS)+1), max_RMS, col='black')
  228. ax5=plt.subplot2grid((4,5), (3,4))
  229. ax = ax5
  230. ax2.get_shared_y_axes().join(ax2, ax5)
  231. MakeBoxplot(maxim_s, colors)
  232. for i in range(0,2):
  233. plt.plot(i+1, mean_max_s[i], '.', c=colors[i], ls='',
  234. label=labels[i])
  235. for i in range(2,len(mean_RMS_s)):
  236. plt.plot(i+1, mean_max_s[i], '.', c=colors[i], ls='')
  237. plt.xticks(ticks=np.arange(1, len(RMS_s)+1), labels=descr_s)
  238. lim = plt.gca().get_ylim()
  239. plt.ylim(lim[0],(lim[1]-lim[0])*1.1+lim[0])
  240. ax.text(-0.3, .95, string.ascii_lowercase[num],
  241. transform=ax.transAxes, size=20, weight='bold')
  242. num += 1
  243. max_max = [np.amax(maxim[i]) for i in range(len(RMS_s))]
  244. Show_Stars(np.array([p_values_cor_shake[2]]), ind_sh,
  245. np.arange(1, len(RMS)+1), max_max, col='black')
  246. legend.get_frame().set_linewidth(2)
  247. plt.subplots_adjust(hspace=0.4, wspace=0.4)
  248. plt.savefig(out_dir+'Boxplot_motion_'+save+'.tiff', format='tiff',
  249. bbox_inches='tight', dpi=200)
  250. plt.savefig(out_dir+'Boxplot_motion_'+save+'.png', format='png',
  251. bbox_inches='tight', dpi=200)
  252. plt.show()
  253. ''' (2) Import image quality metrics: '''
  254. withRR = True
  255. onlyRR = False
  256. quality_scores = True
  257. show_stat_test = True
  258. sequs = ['T1_MPR', 'T2_FLAIR', 'T2_TSE', 'T1_TIRM', 'T2STAR', 'TRACEW_B1000']
  259. ssims, psnrs, tgs, qss, names_tes = [], [], [], [], []
  260. p_ssims, p_psnrs, p_tgs, p_qss, ind_ps = [], [], [], [], []
  261. for sequ in sequs:
  262. n = len(subdir)
  263. if sequ == 'T1_MPR':
  264. m = 10
  265. names = np.array(['MOCO_ON_STILL', 'MOCO_ON_SHAKE_RR', 'MOCO_ON_SHAKE',
  266. 'MOCO_ON_NOD_RR', 'MOCO_ON_NOD', 'MOCO_OFF_STILL',
  267. 'MOCO_OFF_SHAKE_RR', 'MOCO_OFF_SHAKE',
  268. 'MOCO_OFF_NOD_RR', 'MOCO_OFF_NOD'])
  269. else:
  270. m = 6
  271. names = np.array(['MOCO_ON_STILL', 'MOCO_ON_NOD_RR', 'MOCO_ON_NOD',
  272. 'MOCO_OFF_STILL', 'MOCO_OFF_NOD_RR', 'MOCO_OFF_NOD'])
  273. ssim, psnr, tg_, qs = np.zeros((n,m)), np.zeros((n,m)), np.zeros((n,m)), np.zeros((n,m))
  274. i=0
  275. print('Files used for calculation:')
  276. for sub in subdir:
  277. # skip all volunteers where the following sequences were not acquired
  278. if sequ in ['ADC', 'TRACEW_B0', 'TRACEW_B1000', 'T2_FLAIR', 'T2STAR']:
  279. tmp = os.listdir(in_dir_met+sub)
  280. tmp_ = ''
  281. if sequ not in tmp_.join(tmp):
  282. continue
  283. folder = in_dir_met+sub
  284. file_ = glob.glob(folder+'Values_*'+sequ+'*')
  285. file = [f for f in file_ if f.find('Retro')==-1]
  286. if len(file)>0:
  287. # get the most recent file:
  288. file = SortFiles(file, True)
  289. print(file[0])
  290. tmp1 = np.loadtxt(file[0], unpack=True, dtype=str, usecols=0,
  291. skiprows=1)
  292. tmp2, tmp3, tmp4 = np.loadtxt(file[0], unpack=True,
  293. usecols=(1,2,3), skiprows=1)
  294. if sequ == 'T2STAR' and np.size(tmp1) == 1:
  295. # A few subject only contain a MOCO OFF STILL T2STAR scan.
  296. # Those were only acquired for comparison with susceptibility
  297. # weighted scans and are not included in analysis of image
  298. # quality metrics.
  299. continue
  300. incl = []
  301. for na,s,p,t in zip(tmp1, tmp2, tmp3, tmp4):
  302. if sequ in ['T2STAR', 'ADC', 'TRACEW_B0', 'TRACEW_B1000']:
  303. if 'NOD' in na:
  304. na = na+'_RR'
  305. ind = np.where(names==na)[0][0]
  306. ssim[i,ind], psnr[i,ind], tg_[i,ind] = s, p, t
  307. incl.append(ind)
  308. # 0 entires represent non-existing scans
  309. # do the same for quality scores:
  310. if sequ not in ['T2STAR', 'ADC', 'TRACEW_B0', 'TRACEW_B1000']:
  311. file = glob.glob(in_dir_qs+sequ+' Score.txt')
  312. if len(file)>0:
  313. # get the most recent file:
  314. file = SortFiles(file)
  315. print(file[0])
  316. subj_names = np.loadtxt(file[0], unpack=True, dtype=str, usecols=0,
  317. skiprows=1)
  318. tmp1 = np.loadtxt(file[0], unpack=True, dtype=str, usecols=1,
  319. skiprows=1)
  320. tmp2, tmp3, tmp4 = np.loadtxt(file[0], unpack=True, usecols=(2,3,4),
  321. skiprows=1)
  322. tmp1 = tmp1[subj_names==sub[:-1]]
  323. tmp2 = tmp2[subj_names==sub[:-1]]
  324. tmp3 = tmp3[subj_names==sub[:-1]]
  325. tmp4 = tmp4[subj_names==sub[:-1]]
  326. incl = []
  327. for na,q1,q2,q3 in zip(tmp1, tmp2, tmp3, tmp4):
  328. if 'RETRO' not in na:
  329. ind = np.where(names==na[:-1])[0][0]
  330. # average the scores of the three raters with double weight for the radiologist
  331. qs[i,ind] = (q1+q2+2*q3)/4
  332. incl.append(ind)
  333. # for DWI quality ranks instead of quality scores:
  334. elif sequ == 'TRACEW_B1000':
  335. file = glob.glob(in_dir_qs+'DWI Rank.txt')
  336. if len(file)>0:
  337. # get the most recent file:
  338. file = SortFiles(file)
  339. print(file[0])
  340. subj_names = np.loadtxt(file[0], unpack=True, dtype=str, usecols=0,
  341. skiprows=1)
  342. tmp1 = np.loadtxt(file[0], unpack=True, dtype=str, usecols=1,
  343. skiprows=1)
  344. tmp2 = np.loadtxt(file[0], unpack=True, usecols=(2),
  345. skiprows=1)
  346. tmp1 = tmp1[subj_names==sub[:-1]]
  347. tmp2 = tmp2[subj_names==sub[:-1]]
  348. incl = []
  349. for na,q in zip(tmp1, tmp2):
  350. if 'NOD' in na:
  351. na = na+'_RR'
  352. if 'RETRO' not in na:
  353. ind = np.where(names==na)[0][0]
  354. qs[i,ind] = q
  355. incl.append(ind)
  356. else:
  357. qs = np.zeros_like(ssim)
  358. i+=1
  359. names = np.tile(names, (n,1))
  360. # check that names are the same for all volunteers:
  361. for i in range(1, len(subdir)):
  362. if np.all(names[0]==names[i], axis=0)==False:
  363. print('ERROR: Names of 0 and '+str(i)+' are not the same!')
  364. names = names[0]
  365. ''' sort out values == 0 (corresponding to missing scans) '''
  366. ssim[ssim==0] = np.nan
  367. psnr[psnr==0] = np.nan
  368. tg_[tg_==0] = np.nan
  369. qs[qs==0] = np.nan
  370. ''' perform parametric tests:'''
  371. # resort names and data (only for test), final resorting will be performed
  372. # after RR scans are potentially sorted out:
  373. names_ch = []
  374. for n in names:
  375. ind=n.find('_', 5)
  376. if 'OFF' in n:
  377. tmp = 'C'
  378. elif 'ON' in n:
  379. tmp = 'A'
  380. elif 'RETRO' in n:
  381. tmp = 'B'
  382. names_ch.append(n[ind+1:]+'_'+tmp)
  383. names_ch = np.array(names_ch)
  384. ind = np.argsort(names_ch)[::-1]
  385. ssim_p, psnr_p, tg_p, qs_p = ssim[:,ind], psnr[:,ind], tg_[:,ind], qs[:,ind]
  386. names_p = names_ch[ind]
  387. p_ssim, rej_ssim, ind_p, alt = PerformWilcoxonAllImg('SSIM', ssim_p, sequ,
  388. out_dir_metrics, save)
  389. p_psnr, rej_psnr, ind_p, alt = PerformWilcoxonAllImg('PSNR', psnr_p, sequ,
  390. out_dir_metrics, save)
  391. p_tg, rej_tg, ind_p, alt = PerformWilcoxonAllImg('TG', tg_p, sequ,
  392. out_dir_metrics, save)
  393. p_qs, rej_qs, ind_p, alt = PerformWilcoxonAllImg('QS', qs_p, sequ,
  394. out_dir_metrics, save)
  395. # sort out the relevant tests:
  396. if onlyRR == True:
  397. if sequ == 'T1_MPR':
  398. rel_tests = [0,1,4]
  399. p_ssim, p_psnr = p_ssim[rel_tests], p_psnr[rel_tests]
  400. p_tg, p_qs = p_tg[rel_tests], p_qs[rel_tests]
  401. ind_p = np.array([[0,1], [2,3], [4,5]])
  402. else:
  403. rel_tests = [0,1]
  404. p_ssim, p_psnr = p_ssim[rel_tests], p_psnr[rel_tests]
  405. p_tg, p_qs = p_tg[rel_tests], p_qs[rel_tests]
  406. ind_p = np.array([[0,1], [2,3]])
  407. if withRR == False:
  408. findRRs = np.char.find(names, 'RR')
  409. findRRs = (findRRs<0)
  410. names = names[findRRs]
  411. ssim, psnr, tg_ = ssim[findRRs], psnr[findRRs], tg_[findRRs]
  412. ssim = np.reshape(ssim, (len(subdir), int(len(ssim)/len(subdir))))
  413. psnr = np.reshape(psnr, (len(subdir), int(len(psnr)/len(subdir))))
  414. tg_ = np.reshape(tg_, (len(subdir), int(len(tg_)/len(subdir))))
  415. qs = np.reshape(qs, (len(subdir), int(len(qs)/len(subdir))))
  416. names = np.reshape(names, (len(subdir), int(len(names)/len(subdir))))
  417. if onlyRR == True:
  418. findRRs = np.char.find(names, 'RR')
  419. findstills = np.char.find(names, 'STILL')
  420. both = findRRs*findstills
  421. both = (both<0)
  422. names = names[both]
  423. ssim, psnr, tg_, qs = ssim[:,both], psnr[:,both], tg_[:,both], qs[:,both]
  424. std_ssim, std_psnr = np.nanstd(ssim, axis=0), np.nanstd(psnr, axis=0)
  425. std_tg_, std_qs = np.nanstd(tg_, axis=0), np.nanstd(qs, axis=0)
  426. mean_ssim, mean_psnr = np.nanmean(ssim, axis=0), np.nanmean(psnr, axis=0)
  427. mean_tg_, mean_qs = np.nanmean(tg_, axis=0), np.nanmean(qs, axis=0)
  428. # Final resorting:
  429. names_ch = []
  430. for n in names:
  431. ind=n.find('_', 5)
  432. if 'OFF' in n:
  433. tmp = 'C'
  434. elif 'ON' in n:
  435. tmp = 'A'
  436. elif 'RETRO' in n:
  437. tmp = 'B'
  438. names_ch.append(n[ind+1:]+'_'+tmp)
  439. names_ch = np.array(names_ch)
  440. ind = np.argsort(names_ch)[::-1]
  441. ssim, psnr, tg_, qs = ssim[:,ind], psnr[:,ind], tg_[:,ind], qs[:,ind]
  442. names = names[ind]
  443. mean_ssim, mean_psnr = mean_ssim[ind], mean_psnr[ind]
  444. mean_tg_, mean_qs = mean_tg_[ind], mean_qs[ind]
  445. names_te = []
  446. for i in range(int(len(names))):
  447. tmp = names[i]
  448. if 'RETRO' in tmp:
  449. app = 'retrospective MoCo'
  450. elif 'ON' in tmp:
  451. app = 'prospective MoCo'
  452. elif 'OFF' in tmp:
  453. app = 'no MoCo'
  454. if onlyRR == False:
  455. if 'RR' in tmp or 'STILL' in tmp:
  456. app = app + ' no REAC'
  457. else:
  458. app = app + ' with REAC'
  459. names_te.append(app)
  460. # sort out nans (whole rows for subjects wihtout that sequence)
  461. mask = np.where(np.isnan(ssim[:,0])==False)[0]
  462. ssim = ssim[mask]
  463. mask = np.where(np.isnan(psnr[:,0])==False)[0]
  464. psnr = psnr[mask]
  465. mask = np.where(np.isnan(tg_[:,0])==False)[0]
  466. tg_ = tg_[mask]
  467. mask = np.where(np.isnan(qs[:,0])==False)[0]
  468. qs = qs[mask]
  469. # normalise tg values by dividing with mean value of off still
  470. val = np.mean(tg_[:,0])
  471. tg_ = tg_/val
  472. # new color code:
  473. color_dict = {'retrospective MoCo': 'tab:green',
  474. 'prospective MoCo': 'tab:blue', 'no MoCo':'tab:orange'}
  475. if onlyRR == False:
  476. color_dict = {'retrospective MoCo no REAC': 'tab:green',
  477. 'prospective MoCo no REAC': 'tab:blue',
  478. 'no MoCo no REAC':'tab:orange',
  479. 'retrospective MoCo with REAC': 'tab:gray',
  480. 'prospective MoCo with REAC': 'tab:olive',
  481. 'no MoCo with REAC':'tab:cyan'}
  482. ssims.append(ssim)
  483. psnrs.append(psnr)
  484. tgs.append(tg_)
  485. qss.append(qs)
  486. names_tes.append(names_te)
  487. p_ssims.append(p_ssim)
  488. p_psnrs.append(p_psnr)
  489. p_tgs.append(p_tg)
  490. p_qss.append(p_qs)
  491. ind_ps.append(ind_p)
  492. ''' (3) Plot image quality metrics for still scans: '''
  493. if plot_still:
  494. metrics = [tgs, qss, np.array([qss[-1]])]
  495. p_values = [p_tgs, p_qss[0:4], np.array([p_qss[-1]])]
  496. labels = ['Tenengrad', 'Observer Scores', 'Quality Rank']
  497. colors = ['tab:orange', 'tab:blue', 'tab:orange', 'tab:blue', 'tab:orange',
  498. 'tab:blue', 'tab:orange', 'tab:blue', 'tab:orange', 'tab:blue',
  499. 'tab:orange', 'tab:blue']
  500. fig_labels = ['without PMC', 'with PMC']
  501. small = dict(markersize=3)
  502. x = np.arange(1,13)
  503. a = [0,2,4,6,8,10]
  504. b = [1,3,5,7,9,11]
  505. c = [1,3,5,7,9,11]
  506. d = [2,4,6,8,10,12]
  507. num = 0
  508. plt.figure(figsize=(10,9))
  509. for i, metric, p, lab in zip(range(0,3), metrics, p_values, labels):
  510. m_still = []
  511. means = []
  512. for m in metric:
  513. if len(m)>0:
  514. m_still.append(m[:,0])
  515. m_still.append(m[:,1])
  516. means.append(np.nanmean(m[:,0]))
  517. means.append(np.nanmean(m[:,1]))
  518. p_still = []
  519. for pval in p:
  520. p_still.append(pval[0])
  521. if i == 0:
  522. ax = plt.subplot2grid((2,6), (0,0), colspan=6)
  523. box1 = plt.boxplot(m_still, flierprops=small)
  524. for j in range(len(means)):
  525. plt.errorbar(x[j], means[j], yerr=None, color=colors[j], fmt='.', capsize=3)
  526. ticklabels = ['T1_MPR', 'T2_FLAIR', 'T2_TSE', 'T1_STIR', 'T2*', 'TRACEW']
  527. ticks = [1.5, 3.5, 5.5, 7.5, 9.5, 11.5]
  528. plt.xticks(labels=ticklabels, ticks=ticks, fontsize=14)
  529. elif i == 1:
  530. ax = plt.subplot2grid((2,6), (1,0), colspan=4)
  531. box1 = plt.boxplot(m_still[0:8], flierprops=small)
  532. for j in range(len(means)-2):
  533. plt.errorbar(x[j], means[j], yerr=None, color=colors[j], fmt='.', capsize=3)
  534. for j in range(0,2):
  535. plt.errorbar(x[j], means[j], yerr=None, color=colors[j], fmt='.',
  536. capsize=3, label=fig_labels[j])
  537. ticklabels = ['T1_MPR', 'T2_FLAIR', 'T2_TSE', 'T1_STIR']
  538. ticks = [1.5, 3.5, 5.5, 7.5]
  539. plt.xticks(labels=ticklabels, ticks=ticks, fontsize=14)
  540. else:
  541. ax = plt.subplot2grid((2,6), (1,5), colspan=1)
  542. box1 = plt.boxplot(m_still, flierprops=small)
  543. for j in range(len(means)):
  544. plt.errorbar(x[j], means[j], yerr=None, color=colors[j], fmt='.', capsize=3)
  545. ticklabels = ['DWI']
  546. ticks = [1.5]
  547. plt.xticks(labels=ticklabels, ticks=ticks, fontsize=14)
  548. plt.yticks([2,3,4])
  549. for patch, patch2, color in zip(box1['boxes'], box1['medians'], colors):
  550. patch.set(color=color, lw=1.7)
  551. patch2.set(color='k', lw=1.7)
  552. plt.ylabel(lab, fontsize=15)
  553. if show_stat_test == True:
  554. maxi = []
  555. for v in m_still:
  556. maxi.append(np.amax(v))
  557. if i == 0:
  558. indices = [[0,1], [2,3], [4,5], [6,7], [8,9], [10,11]]
  559. Show_Stars(np.array(p_still), indices[0:len(p_still)], x, maxi,
  560. col='black')
  561. elif i ==1:
  562. indices = [[0,1], [2,3], [4,5], [6,7]]
  563. Show_Stars(np.array(p_still), indices[0:len(p_still)], x[0:8], maxi[0:8],
  564. col='black')
  565. else:
  566. indices = [[0,1]]
  567. Show_Stars(np.array(p_still), indices[0:len(p_still)], x, maxi,
  568. col='black')
  569. lim = plt.gca().get_ylim()
  570. plt.ylim(lim[0],(lim[1]-lim[0])*1.05+lim[0])
  571. DrawLines2(a[0:len(p_still)],b[0:len(p_still)],c[0:len(p_still)],
  572. d[0:len(p_still)],m_still, lw=0.7, col='darkslategray')
  573. if i == 2:
  574. ax.text(-0.6, 0.95, string.ascii_lowercase[num],
  575. transform=ax.transAxes, size=24, weight='bold')
  576. else:
  577. ax.text(-0.1, 0.95, string.ascii_lowercase[num],
  578. transform=ax.transAxes, size=24, weight='bold')
  579. num += 1
  580. plt.yticks(fontsize=13)
  581. plt.tick_params('both', length=0)
  582. plt.gca().yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
  583. if i == 0:
  584. xlim = plt.gca().get_xlim()
  585. if i == 1:
  586. legend = plt.legend( loc='lower left', ncol=2,
  587. bbox_to_anchor=(0.4, -0.3), fontsize=14,
  588. frameon=True)
  589. plt.yticks(ticks=[2.5, 3, 3.5, 4, 4.5, 5])
  590. legend.get_frame().set_linewidth(2)
  591. plt.subplots_adjust(hspace=0.2, wspace=0.3)
  592. plt.savefig(out_dir+'Metrics_still'+save+'.tiff', format='tiff',
  593. bbox_inches='tight', dpi=200)
  594. plt.savefig(out_dir+'Metrics_still'+save+'.png', format='png',
  595. bbox_inches='tight', dpi=200)
  596. plt.show()
  597. ''' (4) Plot image quality metrics for nodding scans: '''
  598. if plot_nod:
  599. # first MPRAGE and FLAIR
  600. metrics = [ssims, psnrs, tgs, qss]
  601. p_values = [p_ssims, p_psnrs, p_tgs, p_qss[0:4]]
  602. labels = ['SSIM', 'PSNR', 'Tenengrad', 'Observer Scores']
  603. color_dict = {'prospective MoCo no REAC': 'tab:blue',
  604. 'no MoCo no REAC':'tab:orange',
  605. 'prospective MoCo with REAC': 'tab:green',
  606. 'no MoCo with REAC':'tab:cyan'}
  607. name_dict = {'prospective MoCo no REAC': 'with PMC without REAC',
  608. 'no MoCo no REAC':'without PMC without REAC',
  609. 'prospective MoCo with REAC': 'with PMC with REAC',
  610. 'no MoCo with REAC':'without PMC with REAC'}
  611. small = dict(markersize=3)
  612. x = np.concatenate((np.arange(1,9), np.arange(10,14)), axis=None)
  613. a = [0,2,4,6]
  614. b = [1,3,5,7]
  615. c = [1,3,5,7]
  616. d = [2,4,6,8]
  617. a_ = [0,2]
  618. b_ = [1,3]
  619. c_ = [10,12]
  620. d_ = [11,13]
  621. num = 0
  622. plt.figure(figsize=(11,8))
  623. for i, metric, p, lab in zip(range(0,4), metrics, p_values, labels):
  624. means = []
  625. names = []
  626. # first MPR
  627. tmp = metric[0]
  628. m_mpr = tmp[:,2:]
  629. names = names_tes[0][2:]
  630. # then FLAIR
  631. tmp = metric[1]
  632. m_fl = tmp[:,2:]
  633. names = np.concatenate((names, names_tes[1][2:]), axis=None)
  634. p_mot = []
  635. indices = []
  636. for pval, ind in zip(p[0:2], ind_ps[0:2]):
  637. p_mot.append(pval[1:])
  638. indices.append(ind[1:])
  639. means = np.concatenate((np.nanmean(m_mpr, axis=0),
  640. np.nanmean(m_fl, axis=0)), axis=None)
  641. colors = []
  642. leg_labels = []
  643. for n in names:
  644. colors.append(color_dict[n])
  645. leg_labels.append(name_dict[n])
  646. ax = plt.subplot(2,2,i+1)
  647. box1 = plt.boxplot(m_mpr, flierprops=small, widths=0.5)
  648. for patch, patch2, color in zip(box1['boxes'], box1['medians'], colors):
  649. patch.set(color=color, lw=1.5)
  650. patch2.set(color='k', lw=1.5)
  651. box2 = plt.boxplot(m_fl, positions=range(10,14), flierprops=small,
  652. widths=0.5)
  653. for patch, patch2, color in zip(box2['boxes'], box2['medians'], colors):
  654. patch.set(color=color, lw=1.5)
  655. patch2.set(color='k', lw=1.5)
  656. for j in range(len(means)):
  657. plt.errorbar(x[j], means[j], yerr=None, color=colors[j], fmt='.',
  658. capsize=3)
  659. if i == 2:
  660. for j in range(0,4):
  661. plt.errorbar(x[j], means[j], yerr=None, color=colors[j],
  662. fmt='.', capsize=3, label=leg_labels[j])
  663. legend = plt.legend( loc='lower left', ncol=2,
  664. bbox_to_anchor=(0.25, -0.4), fontsize=12,
  665. frameon=True)
  666. plt.ylabel(lab, fontsize=15)
  667. if show_stat_test == True:
  668. maxi = []
  669. for v in m_mpr.T:
  670. maxi.append(np.amax(v))
  671. Show_Stars(np.array(p_mot[0]), indices[0]-2, x, maxi,
  672. arange_dh='PAPER', col='black')
  673. for v in m_fl.T:
  674. maxi.append(np.amax(v))
  675. Show_Stars(np.array(p_mot[1]), indices[1]-2, x[8:], maxi,
  676. arange_dh='PAPER', col='black')
  677. lim = plt.gca().get_ylim()
  678. plt.ylim(lim[0],(lim[1]-lim[0])*1.01+lim[0])
  679. DrawLines(a,b,c,d,m_mpr, col='darkslategray')
  680. DrawLines(a_,b_,c_,d_,m_fl, col='darkslategray')
  681. ticklabels = ['T1_MPR\nSHAKE', 'T1_MPR\nNOD', 'T2_FLAIR\nNOD']
  682. ticks = [2.5, 6.5, 11.5]
  683. plt.xticks(labels=ticklabels, ticks=ticks, fontsize=12)
  684. ax.text(-0.18, 0.9, string.ascii_lowercase[num], transform=ax.transAxes,
  685. size=21, weight='bold')
  686. num += 1
  687. plt.yticks(fontsize=13)
  688. plt.tick_params('both', length=0)
  689. plt.gca().yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
  690. if i == 3:
  691. plt.yticks(ticks=[1, 2, 3, 4, 5])
  692. legend.get_frame().set_linewidth(2)
  693. plt.subplots_adjust(hspace=0.2, wspace=0.3)
  694. plt.savefig(out_dir+'Metrics_3D'+save+'.tiff', format='tiff',
  695. bbox_inches='tight', dpi=200)
  696. plt.savefig(out_dir+'Metrics_3D'+save+'.png', format='png',
  697. bbox_inches='tight', dpi=200)
  698. plt.show()
  699. # now TSE, STIR, T2* and TRACEW
  700. metrics = [ssims, psnrs, tgs, qss, np.array(qss[-1])]
  701. p_values = [p_ssims, p_psnrs, p_tgs, p_qss[0:4], np.array([p_qss[-1]])]
  702. labels = ['SSIM', 'PSNR', 'Tenengrad', 'Observer Scores', 'Quality Rank']
  703. color_dict = {'prospective MoCo no REAC': 'tab:blue',
  704. 'no MoCo no REAC':'tab:orange',
  705. 'prospective MoCo with REAC': 'tab:green',
  706. 'no MoCo with REAC':'tab:cyan'}
  707. name_dict = {'prospective MoCo no REAC': 'with PMC without REAC',
  708. 'no MoCo no REAC':'without PMC without REAC',
  709. 'prospective MoCo with REAC': 'with PMC with REAC',
  710. 'no MoCo with REAC':'without PMC with REAC'}
  711. small = dict(markersize=3)
  712. num = 0
  713. plt.figure(figsize=(13,8))
  714. for i, metric, p, lab in zip(range(0,5), metrics, p_values, labels):
  715. means = []
  716. names = []
  717. m_nod = []
  718. if i == 4:
  719. tmp = metric
  720. m_nod= [tmp[:,2:4]]
  721. means = [np.nanmean(tmp[:,2:4], axis=0)]
  722. names = [names_tes[j][2:4]]
  723. p_mot = [p[0,1]]
  724. indices = [ind_ps[-1][1]]
  725. elif i in [0,1,2,3]:
  726. for j in range(2, 6):
  727. end = 6
  728. if j in [4,5]:
  729. end = 4
  730. tmp = metric[j]
  731. m_nod.append(tmp[:,2:end])
  732. means.append(np.nanmean(tmp[:,2:end], axis=0))
  733. names.append(names_tes[j][2:end])
  734. p_mot = []
  735. indices = []
  736. for pval, ind in zip(p[2:6], ind_ps[2:6]):
  737. p_mot.append(pval[1:])
  738. indices.append(ind[1:])
  739. if i in [0,1,2]:
  740. ax = plt.subplot2grid((2,4), (i//2,i%2*2), colspan=2)
  741. if i == 3:
  742. ax = plt.subplot2grid((2,6), (1,3), colspan=2)
  743. if i == 4:
  744. ax = plt.subplot2grid((2,6), (1,5), colspan=1)
  745. N = 1
  746. lims = []
  747. for m, mean, p, index, name in zip(m_nod, means, p_mot, indices, names):
  748. colors = []
  749. leg_labels = []
  750. for n in name:
  751. colors.append(color_dict[n])
  752. leg_labels.append(name_dict[n])
  753. if i in [0,1,2]:
  754. positions = np.arange(N, N+len(m.T))
  755. box1 = plt.boxplot(m, positions=positions, flierprops=small,
  756. widths=0.5)
  757. for j in range(len(mean)):
  758. plt.errorbar(positions[j], mean[j], yerr=None, color=colors[j],
  759. fmt='.', capsize=3)
  760. if i == 2 and N == 1:
  761. for j in range(0,4):
  762. plt.errorbar(positions[j], mean[j], yerr=None,
  763. color=colors[j], fmt='.',
  764. capsize=3, label=leg_labels[j])
  765. legend = plt.legend( loc='lower left', ncol=2,
  766. bbox_to_anchor=(0.45, -0.4), fontsize=12,
  767. frameon=True)
  768. ticklabels = ['T2_TSE', 'T1_STIR', 'T2*', 'TRACEW']
  769. ticks = [2.5, 7.5, 11.5, 14.5]
  770. plt.xticks(labels=ticklabels, ticks=ticks, fontsize=12)
  771. if i == 3:
  772. positions = np.arange(N, N+len(m.T))
  773. box1 = plt.boxplot(m[0:8], positions=positions[0:8], flierprops=small,
  774. widths=0.5)
  775. for j in range(len(mean)):
  776. plt.errorbar(positions[j], mean[j], yerr=None, color=colors[j],
  777. fmt='.', capsize=3)
  778. ticklabels = ['T2_TSE', 'T1_STIR']
  779. ticks = [2.5, 7.5]
  780. plt.xticks(labels=ticklabels, ticks=ticks, fontsize=12)
  781. if i == 4:
  782. positions = np.arange(N, N+len(m.T))
  783. box1 = plt.boxplot(m, positions=positions, flierprops=small,
  784. widths=0.5)
  785. for j in range(len(mean)):
  786. plt.errorbar(positions[j], mean[j], yerr=None, color=colors[j],
  787. fmt='.', capsize=3)
  788. ticklabels = ['DWI']
  789. ticks = [1.5]
  790. plt.xticks(labels=ticklabels, ticks=ticks, fontsize=12)
  791. for patch, patch2, color in zip(box1['boxes'], box1['medians'], colors):
  792. patch.set(color=color, lw=1.5)
  793. patch2.set(color='k', lw=1.5)
  794. if show_stat_test == True:
  795. maxi = []
  796. for v in m.T:
  797. maxi.append(np.amax(v))
  798. if i in [0,1,2]:
  799. Show_Stars(np.array(p), index-2, positions, maxi,
  800. flexible_dh=True, col='black')
  801. if i == 3:
  802. Show_Stars(np.array(p), index-2, positions[0:8], maxi[0:8],
  803. flexible_dh=True, col='black')
  804. if i == 4:
  805. Show_Stars(np.array([p]), [index-2], positions, maxi,
  806. flexible_dh=True, col='black')
  807. lims.append(plt.gca().get_ylim())
  808. a = [0,2]
  809. b = [1,3]
  810. if N > 10 or i == 4:
  811. a = [0]
  812. b = [1]
  813. c = [positions[p] for p in a]
  814. d = [positions[p] for p in b]
  815. DrawLines(a,b,c,d,m, col='darkslategray')
  816. N = N+len(m.T)+1
  817. if show_stat_test:
  818. lims = np.array(lims)
  819. lim_min = np.amin(lims[:,0])
  820. lim_max = np.amax(lims[:,1])
  821. plt.ylim(lim_min,(lim_max-lim_min)*1.01+lim_min)
  822. plt.ylabel(lab, fontsize=15)
  823. plt.yticks(fontsize=13)
  824. plt.tick_params('both', length=0)
  825. plt.gca().yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
  826. if i == 4:
  827. ax.text(-0.51, 0.9, string.ascii_lowercase[num], transform=ax.transAxes,
  828. size=21, weight='bold')
  829. else:
  830. ax.text(-0.18, 0.9, string.ascii_lowercase[num], transform=ax.transAxes,
  831. size=21, weight='bold')
  832. num += 1
  833. if i == 3:
  834. plt.yticks(ticks=[1, 2, 3, 4, 5])
  835. if i == 4:
  836. plt.yticks(ticks=[1, 2, 3, 4])
  837. legend.get_frame().set_linewidth(2)
  838. plt.subplots_adjust(hspace=0.2, wspace=0.6)
  839. plt.savefig(out_dir+'Metrics_2D'+save+'.tiff', format='tiff',
  840. bbox_inches='tight', dpi=200)
  841. plt.savefig(out_dir+'Metrics_2D'+save+'.png', format='png',
  842. bbox_inches='tight', dpi=200)
  843. plt.show()
  844. ''' (5) Plot DWI analysis: '''
  845. if plot_DWI:
  846. # calculate histograms of ACS difference images:
  847. sub_out_dir = '../Results/Metrics_Results/'
  848. im_dir = '../BIDSdata_defaced/'
  849. in_dir = '../RegistrationTransforms/'
  850. bm_dir = '../Brainmasks/'
  851. subdir = []
  852. for i in range(1,10):
  853. subdir.append('Subject_0'+str(i)+'/')
  854. for i in range(10,20):
  855. subdir.append('Subject_'+str(i)+'/')
  856. for i in range(20,23):
  857. subdir.append('Subject_'+str(i)+'/')
  858. if calc_ADC_hist:
  859. all_mean, all_std, all_sum = [], [], []
  860. for sub in subdir:
  861. #print('Subject of interest is '+sub)
  862. # sort out subjects for which no DWI scans available:
  863. tmp = os.listdir(sub_out_dir+sub)
  864. tmp_ = ''
  865. if 'ADC' not in tmp_.join(tmp):
  866. continue
  867. differences = []
  868. descr = []
  869. still_off = glob.glob(im_dir+sub+'/TCLMOCO_OFF_STILL_EP2D_DIFF_EXTTRACKING_ADC*.nii')[0]
  870. still = nib.load(still_off).get_fdata().astype(np.uint16)
  871. bm = glob.glob(bm_dir+sub+'bm_mov_*ADC*.nii')[0]
  872. #glob.glob(in_dir+sub+'bm_mov_*ADC*.nii')[0]
  873. bm = nib.load(bm).get_fdata().astype(np.uint16)
  874. still = still*bm
  875. all_imgs = [x for x in glob.glob(im_dir+sub+'/*ADC*.nii') if x not in still_off]
  876. for im in all_imgs:
  877. img = nib.load(im).get_fdata().astype(np.uint16)
  878. img = img*bm
  879. diff = still.astype(np.float) - img.astype(np.float)
  880. differences.append(diff)
  881. descr.append(os.path.basename(im))
  882. differences, descr = np.array(differences), np.array(descr)
  883. ind = np.argsort(descr)
  884. differences = differences[ind]
  885. descr = descr[ind]
  886. sums, means, stds = [], [], []
  887. for i in range(0, len(descr)):
  888. diff = differences[i][bm!=0] # only look at voxels inside the brain!
  889. n, bins, tmp = plt.hist(diff, bins = 2000)
  890. plt.title(descr[i][12:25])
  891. sums.append(np.sum(np.abs(diff))/len(diff))
  892. mids = 0.5*(bins[1:]+bins[:-1])
  893. mean = np.average(mids, weights=n)
  894. std = np.sqrt(np.average((mids-mean)**2, weights=n))
  895. means.append(mean)
  896. stds.append(std)
  897. all_mean.append(means)
  898. all_std.append(stds)
  899. all_sum.append(sums)
  900. # look at results for all subjects:
  901. All_mean, All_std, All_sum = np.array(all_mean)[:,::-1], np.array(all_std)[:,::-1], np.array(all_sum)[:,::-1]
  902. save_arr = np.array([All_mean, All_std, All_sum])
  903. np.save(out_dir_metrics+'ADC_all_values_'+save, save_arr)
  904. # load the values for the ADC histograms and plot them:
  905. file = glob.glob(out_dir_metrics+'ADC_all_values_**.npy')
  906. if len(file)>0:
  907. # get the most recent file:
  908. #file = SortFiles(file)
  909. print(file[0])
  910. All_mean, All_std, All_sum = np.load(file[0])
  911. All_mean = np.array([All_mean[:,0], All_mean[:,2], All_mean[:,1]]).T
  912. All_std = np.array([All_std[:,0], All_std[:,2], All_std[:,1]]).T
  913. All_sum = np.array([All_sum[:,0], All_sum[:,2], All_sum[:,1]]).T
  914. names_diff = ['prospective MoCo', 'no MoCo', 'prospective MoCo']
  915. p_mean, rej_mean, ind, altern = PerformWilcoxonAllImg('Mean', All_mean, 'ADC',
  916. out_dir_metrics,
  917. save, option='diff')
  918. p_std, rej_std, ind, altern = PerformWilcoxonAllImg('Std', All_std, 'ADC',
  919. out_dir_metrics,
  920. save, option='diff')
  921. p_sum, rej_sum, ind, altern = PerformWilcoxonAllImg('Sum', All_sum, 'ADC',
  922. out_dir_metrics,
  923. save, option='diff')
  924. mean_mean = np.mean(All_mean, axis=0)
  925. mean_std = np.mean(All_std, axis=0)
  926. mean_sum = np.mean(All_sum, axis=0)
  927. color_dict = { 'prospective MoCo': 'tab:blue', 'no MoCo': 'tab:orange'}
  928. names = ['with PMC', 'without PMC', 'with PMC']
  929. colors_te = []
  930. for n in names_diff:
  931. colors_te.append(color_dict[n])
  932. x = np.arange(1,len(mean_mean)+1)
  933. plt.figure(figsize=(10,3))
  934. ax=plt.subplot(1,2,1)
  935. for i in range(len(x)):
  936. plt.errorbar(x[i], mean_mean[i], yerr=None, color=colors_te[i], fmt='.',
  937. capsize=3)
  938. small = dict(markersize=3)
  939. box1 = plt.boxplot(All_mean, flierprops=small)
  940. for patch, patch2, color in zip(box1['boxes'], box1['medians'], colors_te):
  941. patch.set(color=color, lw=1.7)
  942. patch2.set(color='k', lw=1.7)
  943. plt.xticks(labels=[], ticks=[])
  944. plt.gca().yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
  945. for y1, y2 in zip(All_mean[:,1], All_mean[:,2]):
  946. plt.plot([2,3], [y1, y2], 'darkslategray', lw=1)
  947. plt.annotate('Still', xy=(0.17, -0.1), xytext=(0.17, -0.18),
  948. xycoords='axes fraction', fontsize=12, ha='center', va='bottom',
  949. bbox=dict(boxstyle='square', fc='white', ec='grey', lw=1.5),
  950. arrowprops=dict(arrowstyle='-[, widthB=1.4, lengthB=0.7',
  951. lw=1.5, color='grey'))
  952. plt.annotate('Nod', xy=(0.67, -0.1), xytext=(0.67, -0.18),
  953. xycoords='axes fraction', fontsize=12, ha='center', va='bottom',
  954. bbox=dict(boxstyle='square', fc='white', ec='grey', lw=1.5),
  955. arrowprops=dict(arrowstyle='-[, widthB=3.0, lengthB=0.7',
  956. lw=1.5, color='grey'))
  957. Show_Stars(p_mean, ind, x, np.amax(All_mean, axis=0), arange_dh='diff',
  958. col='black')
  959. lim = plt.gca().get_ylim()
  960. plt.ylim(lim[0],(lim[1]-lim[0])*1.1+lim[0])
  961. plt.ylabel('Mean of histogram [$\\frac{\mu m^2}{s}$]')
  962. ax.text(-0.22, 0.9, string.ascii_lowercase[0], transform=ax.transAxes,
  963. size=21, weight='bold')
  964. ax=plt.subplot(1,2,2)
  965. for i in range(1):
  966. plt.errorbar(x[i], mean_std[i], yerr=None, color=colors_te[i], fmt='.',
  967. capsize=3)
  968. for i in range(1,len(x)):
  969. plt.errorbar(x[i], mean_std[i], yerr=None, label=names[i],
  970. color=colors_te[i], fmt='.', capsize=3)
  971. small = dict(markersize=3)
  972. box1 = plt.boxplot(All_std, flierprops=small)
  973. for patch, patch2, color in zip(box1['boxes'], box1['medians'], colors_te):
  974. patch.set(color=color, lw=1.7)
  975. patch2.set(color='k', lw=1.7)
  976. plt.xticks(labels=[], ticks=[])
  977. plt.gca().yaxis.set_major_formatter(ScalarFormatter(useOffset=False))
  978. for y1, y2 in zip(All_std[:,1], All_std[:,2]):
  979. plt.plot([2,3], [y1, y2], 'darkslategray', lw=1)
  980. plt.annotate('Still', xy=(0.17, -0.1), xytext=(0.17, -0.18),
  981. xycoords='axes fraction', fontsize=12, ha='center', va='bottom',
  982. bbox=dict(boxstyle='square', fc='white', ec='grey', lw=1.5),
  983. arrowprops=dict(arrowstyle='-[, widthB=1.4, lengthB=0.7',
  984. lw=1.5, color='grey'))
  985. plt.annotate('Nod', xy=(0.67, -0.1), xytext=(0.67, -0.18),
  986. xycoords='axes fraction', fontsize=12, ha='center', va='bottom',
  987. bbox=dict(boxstyle='square', fc='white', ec='grey', lw=1.5),
  988. arrowprops=dict(arrowstyle='-[, widthB=3.0, lengthB=0.7',
  989. lw=1.5, color='grey'))
  990. Show_Stars(p_std, ind, x, np.amax(All_std, axis=0), arange_dh='diff',
  991. col='black')
  992. lim = plt.gca().get_ylim()
  993. plt.ylim(lim[0],(lim[1]-lim[0])*1.1+lim[0])
  994. plt.ylabel('Std of histogram [$\\frac{\mu m^2}{s}$]')
  995. legend = plt.legend(loc='upper center', ncol = 2,
  996. bbox_to_anchor=(-0.2, -0.25), frameon=True)
  997. ax.text(-0.22, 0.9, string.ascii_lowercase[1], transform=ax.transAxes,
  998. size=21, weight='bold')
  999. legend.get_frame().set_linewidth(2)
  1000. plt.subplots_adjust(hspace=0.2, wspace=0.3)
  1001. plt.savefig(out_dir+'ADC'+save+'.tiff', format='tiff', bbox_inches='tight',
  1002. dpi=200)
  1003. plt.savefig(out_dir+'ADC'+save+'.png', format='png', bbox_inches='tight',
  1004. dpi=200)
  1005. plt.show()
  1006. # calculate mean value of ground truth scans:
  1007. means = []
  1008. for sub in subdir:
  1009. if sub in ['HC_0'+str(i)+'/' for i in range(1,10)]:
  1010. continue
  1011. if sub in ['HC_'+str(i)+'/' for i in range(10,13)]:
  1012. continue
  1013. # sort out subjects for which no DWI scans available:
  1014. tmp = os.listdir(sub_out_dir+sub)
  1015. tmp_ = ''
  1016. if 'ADC' not in tmp_.join(tmp):
  1017. continue
  1018. file = glob.glob(im_dir+sub+'/TCLMOCO_OFF_STILL_EP2D_DIFF_EXTTRACKING_ADC*.nii')[0]
  1019. #glob.glob(im_dir+sub+'/*ADC*.nii')[0]
  1020. img = nib.load(file).get_fdata().astype(np.uint16)
  1021. bm_file = glob.glob(bm_dir+sub+'bm_mov_*ADC*.nii')[0]
  1022. bm = nib.load(bm_file).get_fdata().astype(np.uint16)
  1023. bm_fl = bm.flatten()
  1024. dat = img.flatten()
  1025. img_fl = dat[bm_fl>0]
  1026. means.append(np.mean(img_fl))
  1027. print('Mean Values of ground truth scans:', means)
  1028. print('Overall mean value:', np.mean(means))

generate_plots_manuscript.py at commit ffd7086, under MIT · at the source

Overview

Authors: Kathrine Skak Madsen1, Tim Ruschke2,3, Hannah Eichhorn4,5, Puk Rising2, Melanie Ganz2,3
ORCID iDs: Melanie Ganz
  1. Danish Research Centre for Magnetic Resonance, Department of Radiology and Nuclear Medicine, Copenhagen University Hospital - Amager and Hvidovre,Hvidovre, Denmark
  2. Neurobiology Research Unit, Copenhagen University Hospital - Rigshospitalet,Copenhagen, Denmark
  3. Department of Computer Science, University of Copenhagen,Copenhagen, Denmark
  4. Institute of Machine Learning in Biomedical Imaging, Helmholtz Munich, Neuherberg, Germany
  5. School of Computation, Information and Technology, Technical University of Munich,Munich, Germany
Journal: Scientific data, volume 13, issue 1, article 943
Dates: received 16 July 2025; accepted 26 March 2026; published online 23 April 2026
Type: Data paper · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s41597-026-07144-z · PMID 42026101 · PMCID PMC13315939 · OpenAlex W7155394641
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: structural MRI / diffusion (modality), human (organism), methods / tools (subfield)
Methods: fMRI & imaging
Keywords: Neurology, Mathematics and computing, Scientific data
MeSH: Brain*, Magnetic Resonance Imaging*, Motion*, Artifacts, Humans, Image Processing, Computer-Assisted (* major topic)
Journal subjects: Data Descriptor
Topic: Advanced MRI Techniques and Applications (Radiology, Nuclear Medicine and Imaging, Medicine), according to OpenAlex
Funding: Elsass Fonden (18-3-0147)
Citations: not cited yet (Europe PMC); 34 references in the paper

Abstract

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

Repositories

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

melanieganz/mocoproject

License: MIT
State: the link answers, verified on 29 September 2026
Evidence: files inventoried
Commit: ffd708616a24b5abe0531605e0e7a30bdb2df6cc, 10 May 2026
Languages: Python (28), Jupyter (2), Shell (1)
Size: 53 files, 31 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, license file, environment (docker/dockerfile), 2 notebooks
Not found: CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (30 files), SciPy (14 files), Matplotlib (11 files), NiBabel (9 files), scikit-image (8 files), FreeSurfer (7 files), pydicom (4 files), statsmodels (4 files)
Availability: 1 check, the latest on 29 September 2026: the link answers
  • 29 September 2026: the link answers
33 files

OSF vzh4g

License: none: the authors keep all their rights
State: the link answers, verified on 29 September 2026
Evidence: the link answers
Software Heritage: not checked
Found in: the references
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Availability: 1 check, the latest on 29 September 2026: the link answers (HTTP 200)
  • 29 September 2026: the link answers (HTTP 200)
At the source: osf.io/vzh4g

Code availability statement

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

Read it in the paper: doi.org/10.1038/s41597-026-07144-z.

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

Datasets cited

Data availability statement

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

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

Read it in the paper: doi.org/10.1038/s41597-026-07144-z.

Versions

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

Version 1, 29 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 5 authors, 3 keywords, 6 MeSH terms, 1 funder, 31 references.

Cite

This paper

Skak Madsen, K., Ruschke, T., Eichhorn, H., Rising, P., & Ganz, M. (2026). Brain MRI Dataset Featuring a Full Clinical Protocol With and Without Intentional Motion. Scientific data, 13(1), 943. https://doi.org/10.1038/s41597-026-07144-z

BibTeX

@article{skakmadsen2026brain,
author = {Skak Madsen, Kathrine and Ruschke, Tim and Eichhorn, Hannah and Rising, Puk and Ganz, Melanie},
title = {{Brain MRI Dataset Featuring a Full Clinical Protocol With and Without Intentional Motion}},
journal = {Scientific data},
year = {2026},
month = apr,
volume = {13},
number = {1},
pages = {943},
publisher = {Nature Publishing Group},
issn = {2052-4463},
doi = {10.1038/s41597-026-07144-z},
url = {https://doi.org/10.1038/s41597-026-07144-z},
pmid = {42026101},
pmcid = {PMC13315939}
}

RIS

TY - JOUR
AU - Skak Madsen, Kathrine
AU - Ruschke, Tim
AU - Eichhorn, Hannah
AU - Rising, Puk
AU - Ganz, Melanie
TI - Brain MRI Dataset Featuring a Full Clinical Protocol With and Without Intentional Motion
T2 - Scientific data
J2 - Sci Data
PY - 2026
DA - 2026/04/23
VL - 13
IS - 1
SP - 943
SN - 2052-4463
PB - Nature Publishing Group
DO - 10.1038/s41597-026-07144-z
UR - https://doi.org/10.1038/s41597-026-07144-z
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41597-026-07144-z",
"type": "article-journal",
"title": "Brain MRI Dataset Featuring a Full Clinical Protocol With and Without Intentional Motion",
"container-title": "Scientific data",
"author": [
{
"family": "Skak Madsen",
"given": "Kathrine"
},
{
"family": "Ruschke",
"given": "Tim"
},
{
"family": "Eichhorn",
"given": "Hannah"
},
{
"family": "Rising",
"given": "Puk"
},
{
"family": "Ganz",
"given": "Melanie"
}
],
"container-title-short": "Sci Data",
"volume": "13",
"issue": "1",
"page": "943",
"DOI": "10.1038/s41597-026-07144-z",
"PMID": "42026101",
"PMCID": "PMC13315939",
"ISSN": "2052-4463",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41597-026-07144-z",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
23
]
]
}
}

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.1002/nbm.70368 [code]
Intra-MRI Head Motion Tracking and Correction: A Quantitative In Vivo Evaluation Framework.
Journal: NMR in biomedicine
In common: scikit-image, NiBabel, SciPy, 2 other tools, methods / tools, structural MRI / diffusion, 7 references
[2] doi:10.1002/nbm.70286 [code]
DEEP-DISORDER: Motion Correction in 3D MRI via Segment Reconstruction and Registration.
Journal: NMR in biomedicine
In common: structural MRI / diffusion, 8 references
[3] doi:10.1038/s41597-026-07377-y [code]
An open-access multi-site fMRI dataset for investigating conscious visual perception.
Journal: Scientific data
In common: FreeSurfer, scikit-image, NiBabel, 4 other tools, 2 references
[4] doi:10.1162/imag.a.1366 [code]
MICAFlow: Fast and robust MRI preprocessing bridging research neuroimaging and clinical practice.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: FreeSurfer, NiBabel, SciPy, 2 other tools, methods / tools, structural MRI / diffusion, 3 references
[5] doi:10.1162/imag.a.1262 [code]
Frame-wise multi-echo distortion correction for superior functional MRI.
Journal: Imaging neuroscience (Cambridge, Mass.)
In common: pydicom, FreeSurfer, scikit-image, 4 other tools, 1 reference
[6] doi:10.1002/alz.71649 [code]
Postmortem brain MRI reveals differential associations of subcortical and limbic volumes with cortical thinning and neurodegenerative pathologies.
Journal: Alzheimer's & dementia : the journal of the Alzheimer's Association
In common: FreeSurfer, scikit-image, NiBabel, 4 other tools, structural MRI / diffusion, 1 reference
[7] doi:10.7554/elife.108408 [code]
Frequency and laminar profile of feature-specific visual activity revealed by interleaved EEG-fMRI.
Journal: eLife
In common: FreeSurfer, scikit-image, NiBabel, 4 other tools, 1 reference
[8] doi:10.7554/elife.107933 [code]
Modality-agnostic decoding of vision and language from fMRI.
Journal: eLife
In common: FreeSurfer, scikit-image, NiBabel, 4 other tools, 1 reference
[9] doi:10.1038/s41597-026-07350-9 [code]
An open multi-center MEG-EEG dataset for studying conscious visual perception.
Journal: Scientific data
In common: FreeSurfer, scikit-image, NiBabel, 4 other tools, structural MRI / diffusion
[10] doi:10.1038/s41597-026-06869-1 [code]
Individual Brain Charting: fifth release of high-resolution fMRI data for cognitive mapping.
Journal: Scientific data
In common: FreeSurfer, scikit-image, NiBabel, 3 other tools, methods / tools, 1 reference

Contribute

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

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

Request its removal

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

Discussion, reproductions, activity

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

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

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