create_figure_1.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. import mr_utilities
  2. import pandas as pd
  3. import numpy as np
  4. import matplotlib.pylab as plt
  5. import seaborn as sns
  6. from scipy import stats
  7. import hierarchical_model
  8. colors = ['steelblue', 'slategray', 'firebrick', 'darkblue', 'darkgreen']
  9. def cm2inch(value):
  10. return value/2.54
  11. def boxplot_focal_contra_onlypaired(pkl_file_pre, pkl_file_inter, resultpath):
  12. mr_results_pre = pd.read_pickle(pkl_file_pre)
  13. mr_results_inter = pd.read_pickle(pkl_file_inter)
  14. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  15. ignore_index=True)
  16. mr_results = mr_utilities.exclude_inconsistencies(mr_results)
  17. mr_results['logepsilon'] = mr_results.apply(lambda row: np.log(1-row['m']), axis=1)
  18. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  19. quantity = 'epsilon'
  20. # ================================================================== #
  21. # compute pvalue (paired, just uses data with pair)
  22. # ================================================================== #
  23. paired_recordings = []
  24. for rec in mr_results.recording.unique():
  25. recframe = mr_results[mr_results['recording'] == rec]
  26. if not len(recframe['m'].tolist()) == 2:
  27. continue
  28. paired_recordings.append(rec)
  29. mr_results_paired = mr_results[mr_results['recording'].isin(paired_recordings)]
  30. p_hierarchical = hierarchical_model.hierarchical_model_hemispheres(
  31. mr_results_paired)
  32. # ================================================================== #
  33. # Plotting
  34. # ================================================================== #
  35. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(4), cm2inch(3)))
  36. gb = sns.boxplot(ax=ax, x="binning_focus", y=quantity,
  37. data=mr_results_paired, order=['focal', 'contra-lateral'],
  38. dodge=True, palette=['darkblue', 'slategray'])
  39. for patch in ax.artists:
  40. r, g, b, a = patch.get_facecolor()
  41. patch.set_facecolor((r, g, b, .4))
  42. patch.set_edgecolor('gray')
  43. sns.stripplot(ax=ax, x="binning_focus", y=quantity,
  44. data=mr_results_paired, alpha=0.9, order=['focal',
  45. 'contra-lateral'], size=2, dodge=True, palette=[
  46. 'darkblue', 'slategray'], jitter=False)
  47. gb.set_yscale("log")
  48. plt.grid(axis='x', b=False)
  49. n_SOZ = len(mr_results_paired[mr_results_paired['binning_focus']
  50. == 'focal']['m'].tolist())
  51. n_nSOZ = len(mr_results_paired[mr_results_paired['binning_focus'] ==
  52. 'contra-lateral']['m'].tolist())
  53. ax.set_xticklabels(['ipsi\n({})'.format(n_SOZ), 'contra\n({})'.format(n_nSOZ)])
  54. ax.set_xlabel('')
  55. quantity_label = r'$\hat{m}$'
  56. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  57. ymax = 0.6*np.min(mr_results[quantity].tolist())
  58. ax.set_ylim(ymin, ymax)
  59. T = [1, 1e-1, 1e-2, 1e-3]
  60. ax.set_yticks(T)
  61. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  62. plt.ylabel(quantity_label)
  63. sns.despine()
  64. # ================================================================== #
  65. # Annotate pvalues
  66. # ================================================================== #
  67. x1, x2 = 0, 1
  68. y, h = ymax * (1.1), -0.1 * ymax
  69. ax.plot([x1, x1, x2, x2], [y, y + h, y + h, y], lw=1.5, c='black')
  70. ax.text((x1 + x2) * .5, y + 4*h, r"$p$"+"={:.3f}".format(
  71. p_hierarchical), ha='center', va='bottom', color='black', fontsize=10)
  72. # ================================================================== #
  73. # Final figure adjustments + saving
  74. # ================================================================== #
  75. sns.despine(fig)
  76. fig.subplots_adjust(bottom=None, right=None,
  77. wspace=0.8, hspace=0.5, left=0.15, top=1.2)
  78. resultfile = '{}Fig1_boxplot_onlypaired.pdf'.format(resultpath)
  79. plt.savefig(resultfile, bbox_inches='tight')
  80. plt.show()
  81. plt.close()
  82. def boxplot_focal_contra_Engel(pkl_file_pre, pkl_file_inter, resultpath):
  83. mr_results_pre = pd.read_pickle(pkl_file_pre)
  84. mr_results_inter = pd.read_pickle(pkl_file_inter)
  85. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  86. ignore_index=True)
  87. patients1a = [1, 6, 8, 9, 10, 11, 16, 17, 18, 19]
  88. mr_results = mr_results[(mr_results['patient'].isin(patients1a))]
  89. mr_results = mr_utilities.exclude_inconsistencies(mr_results)
  90. mr_results['logepsilon'] = mr_results.apply(lambda row:
  91. np.log(1-row['m']), axis=1)
  92. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  93. quantity = 'epsilon'
  94. # ================================================================== #
  95. # compute pvalue (unpaired, all data)
  96. # ================================================================== #
  97. p_hierarchical = hierarchical_model.hierarchical_model_hemispheres(
  98. mr_results)
  99. # ================================================================== #
  100. # Plotting
  101. # ================================================================== #
  102. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(4), cm2inch(3)))
  103. gb = sns.boxplot(ax=ax, x="binning_focus", y=quantity,
  104. data=mr_results, order=['focal', 'contra-lateral'],
  105. dodge=True, palette=['darkblue', 'slategray'])
  106. for patch in ax.artists:
  107. r, g, b, a = patch.get_facecolor()
  108. patch.set_facecolor((r, g, b, .4))
  109. patch.set_edgecolor('gray')
  110. sns.stripplot(ax=ax, x="binning_focus", y=quantity,
  111. data=mr_results, alpha=0.9, order=['focal',
  112. 'contra-lateral'], size=2, dodge=True, palette=[
  113. 'darkblue', 'slategray'], jitter=False)
  114. gb.set_yscale("log")
  115. plt.grid(axis='x', b=False)
  116. n_SOZ = len(mr_results[mr_results['binning_focus']=='focal']['m'].tolist())
  117. n_nSOZ = len(mr_results[mr_results['binning_focus'] == 'contra-lateral'][
  118. 'm'].tolist())
  119. ax.set_xticklabels(['ipsi\n({})'.format(n_SOZ), 'contra\n({})'.format(
  120. n_nSOZ)])
  121. ax.set_xlabel('')
  122. quantity_label = r'$\hat{m}$'
  123. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  124. ymax = 0.6*np.min(mr_results[quantity].tolist())
  125. ax.set_ylim(ymin, ymax)
  126. T = [1, 1e-1, 1e-2, 1e-3]
  127. ax.set_yticks(T)
  128. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  129. plt.ylabel(quantity_label)
  130. sns.despine()
  131. # ================================================================== #
  132. # Annotate pvalues
  133. # ================================================================== #
  134. x1, x2 = 0, 1
  135. y, h = ymax * (1.1), -0.1 * ymax
  136. ax.plot([x1, x1, x2, x2], [y, y + h, y + h, y], lw=1.5, c='black')
  137. ax.text((x1 + x2) * .5, y + 4*h, r"$p$"+"={:.3f}".format(p_hierarchical),
  138. ha='center', va='bottom', color='black', fontsize=10)
  139. # ================================================================== #
  140. # Final figure adjustments + saving
  141. # ================================================================== #
  142. sns.despine(fig)
  143. fig.subplots_adjust(bottom=None, right=None,
  144. wspace=0.8, hspace=0.5, left=0.15, top=1.2)
  145. resultfile = '{}Fig1_boxplot_1aEngel.pdf'.format(resultpath)
  146. plt.savefig(resultfile, bbox_inches='tight')
  147. plt.show()
  148. plt.close()
  149. def boxplot_focal_contra(pkl_file_pre, pkl_file_inter, resultpath):
  150. mr_results_pre = pd.read_pickle(pkl_file_pre)
  151. mr_results_inter = pd.read_pickle(pkl_file_inter)
  152. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  153. ignore_index=True)
  154. mr_results = mr_utilities.exclude_inconsistencies(mr_results)
  155. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  156. mr_results['logepsilon'] = mr_results.apply(lambda row: np.log(1-row['m']),
  157. axis=1)
  158. quantity = 'epsilon'
  159. # ================================================================== #
  160. # compute p-value (unpaired, all data)
  161. # ================================================================== #
  162. p_hierarchical = hierarchical_model.hierarchical_model_hemispheres(mr_results)
  163. # ================================================================== #
  164. # Plotting
  165. # ================================================================== #
  166. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(4), cm2inch(3)))
  167. gb = sns.boxplot(ax=ax, x="binning_focus", y=quantity,
  168. data=mr_results, order=['focal', 'contra-lateral'],
  169. dodge=True, palette=['darkblue', 'slategray'])
  170. for patch in ax.artists:
  171. r, g, b, a = patch.get_facecolor()
  172. patch.set_facecolor((r, g, b, .4))
  173. patch.set_edgecolor('gray')
  174. sns.stripplot(ax=ax, x="binning_focus", y=quantity,
  175. data=mr_results, alpha=0.9, order=['focal','contra-lateral'],
  176. size=2, dodge=True, palette=['darkblue', 'slategray'],
  177. jitter=False)
  178. gb.set_yscale("log")
  179. plt.grid(axis='x', b=False)
  180. n_SOZ = len(mr_results[mr_results['binning_focus'] == 'focal'][
  181. 'm'].tolist())
  182. n_nSOZ = len(mr_results[mr_results['binning_focus'] == 'contra-lateral'][
  183. 'm'].tolist())
  184. ax.set_xticklabels(['ipsi\n({})'.format(n_SOZ), 'contra\n({})'.format(
  185. n_nSOZ)])
  186. ax.set_xlabel('')
  187. quantity_label = r'$\hat{m}$'
  188. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  189. ymax = 0.6*np.min(mr_results[quantity].tolist())
  190. ax.set_ylim(ymin, ymax)
  191. T = [1, 1e-1, 1e-2, 1e-3]
  192. ax.set_yticks(T)
  193. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  194. plt.ylabel(quantity_label)
  195. sns.despine()
  196. # ================================================================== #
  197. # Annotate pvalues
  198. # ================================================================== #
  199. x1, x2 = 0, 1
  200. y, h = ymax * (1.1), -0.1 * ymax
  201. ax.plot([x1, x1, x2, x2], [y, y + h, y + h, y], lw=1.5, c='black')
  202. ax.text((x1 + x2) * .5, y + 4*h, r"$p$"+"={:.3f}".format(p_hierarchical),
  203. ha='center', va='bottom', color='black', fontsize=10)
  204. # ================================================================== #
  205. # Final figure adjustments + saving
  206. # ================================================================== #
  207. sns.despine(fig)
  208. fig.subplots_adjust(bottom=None, right=None,
  209. wspace=0.8, hspace=0.5, left=0.15, top=1.2)
  210. resultfile = '{}Fig1_boxplot.pdf'.format(resultpath)
  211. plt.savefig(resultfile, bbox_inches='tight')
  212. plt.show()
  213. plt.close()
  214. def patientwise_pointplots(pkl_file_pre, pkl_file_inter, result_path):
  215. # -----------------------------------------------------------------#
  216. # Read data
  217. # -----------------------------------------------------------------#
  218. mr_results_inter = pd.read_pickle(pkl_file_inter)
  219. mr_results_inter['rec_type'] = mr_results_inter.apply(lambda row: 'inter',
  220. axis=1)
  221. mr_results_pre = pd.read_pickle(pkl_file_pre)
  222. mr_results_pre['rec_type'] = mr_results_pre.apply(lambda row: 'pre',
  223. axis=1)
  224. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  225. ignore_index=True)
  226. mr_results = mr_utilities.exclude_inconsistencies(mr_results)
  227. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  228. quantity = 'epsilon'
  229. # -----------------------------------------------------------------#
  230. # Run through all patients that also have preictal data
  231. # get their interictal and preictal results plot them as a pointplot
  232. # -----------------------------------------------------------------#
  233. patients = mr_results['patient'].unique()
  234. patients_sorted = np.sort(patients)
  235. fig, ax = plt.subplots(5, 4, figsize=(12, 1.5 * 5))
  236. v = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
  237. h = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
  238. for ip, patient in enumerate(patients_sorted):
  239. mr_patient = mr_results[mr_results['patient'] == patient]
  240. recordings = mr_patient.recording.unique()
  241. all_SOZ = mr_patient[mr_patient['binning_focus'] == 'focal'][
  242. quantity].tolist()
  243. all_nSOZ = mr_patient[mr_patient['binning_focus'] == 'contra-lateral'][
  244. quantity].tolist()
  245. stat, p_unpaired = stats.mannwhitneyu(all_SOZ, all_nSOZ,
  246. alternative='two-sided')
  247. for rec in recordings:
  248. mr_rec = mr_patient[mr_patient['recording'] == rec]
  249. if len(mr_rec[quantity].tolist()) == 2:
  250. q_SOZ = mr_rec[mr_rec['binning_focus'] == 'focal'][
  251. quantity].item()
  252. q_nSOZ = mr_rec[mr_rec['binning_focus'] == 'contra-lateral'][
  253. quantity].item()
  254. color = 'darkorange'
  255. if mr_rec['rec_type'].tolist()[0] == 'pre':
  256. color = 'indianred'
  257. ax[h[ip], v[ip]].plot([1, 2], [q_SOZ, q_nSOZ], c=color,
  258. marker='.', markersize=6)
  259. elif len(mr_rec[mr_rec['binning_focus'] == 'focal'].index) == 1:
  260. q_SOZ = mr_rec[mr_rec['binning_focus'] == 'focal'][
  261. quantity].item()
  262. color = 'darkorange'
  263. if mr_rec['rec_type'].tolist()[0] == 'pre':
  264. color = 'indianred'
  265. ax[h[ip], v[ip]].plot([1], [q_SOZ], c=color, marker='.',
  266. markersize=6)
  267. elif len(mr_rec[mr_rec['binning_focus'] ==
  268. 'contra-lateral'].index) == 1:
  269. q_nSOZ = mr_rec[mr_rec['binning_focus'] == 'contra-lateral'][
  270. quantity].item()
  271. color = 'darkorange'
  272. if mr_rec['rec_type'].tolist()[0] == 'pre':
  273. color = 'indianred'
  274. ax[h[ip], v[ip]].plot([2], [q_nSOZ], c=color, marker='.',
  275. markersize=6)
  276. # if the number of recordings is sufficiently large, output p-value
  277. if len(all_SOZ)+len(all_nSOZ) >= 8:
  278. ax[h[ip], v[ip]].text(0.5, 0.9, 'p={:.3f}'.format(p_unpaired),
  279. horizontalalignment='center', verticalalignment='center',
  280. transform=ax[h[ip], v[ip]].transAxes, color='black',
  281. fontsize=10)
  282. ax[h[ip], v[ip]].set_title('Patient {}'.format(patient))
  283. ax[h[ip], v[ip]].set_yscale("log")
  284. quantity_label = r'$\hat{m}$'
  285. ax[h[ip], v[ip]].set_ylabel(quantity_label)
  286. ymin = 1.1
  287. ymax = 1e-3
  288. ax[h[ip], v[ip]].set_ylim(ymin, ymax)
  289. ax[h[ip], v[ip]].set_xlim(0.7, 2.3)
  290. T = [1, 2]
  291. ax[h[ip], v[ip]].set_xticks(T)
  292. ax[h[ip], v[ip]].set_xticklabels(['ipsi', 'contra'])
  293. T = [1, 1e-1, 1e-2, 1e-3]
  294. ax[h[ip], v[ip]].set_yticks(T)
  295. ax[h[ip], v[ip]].set_yticklabels([0, 0.9, 0.99, 0.999])
  296. ax[h[ip], v[ip]].set_xlabel(' ')
  297. ax[h[ip], v[ip]].set_xticklabels(['ipsi', 'contra'])
  298. sns.despine(fig)
  299. fig.subplots_adjust(bottom=None, right=None,
  300. wspace=0.7, hspace=0.7, left=0.15, top=1.2)
  301. plotfile_mx = '{}S2_patients.pdf'.format(result_path)
  302. fig.savefig(plotfile_mx, bbox_inches='tight')
  303. plt.show()
  304. def boxplot_brainregions_focus_onlypaired(pkl_file_pre, pkl_file_inter,
  305. result_path):
  306. regions = ['H', 'A', 'PHC', 'EC']
  307. mr_results_pre = pd.read_pickle(pkl_file_pre)
  308. mr_results_inter = pd.read_pickle(pkl_file_inter)
  309. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  310. ignore_index=True)
  311. mr_results = mr_utilities.exclude_inconsistencies(mr_results)
  312. # -----------------------------------------------------------------#
  313. # Write the brainregion, independent of hemisphere, into frame
  314. # -----------------------------------------------------------------#
  315. def give_region(row):
  316. return row['binning'][1:]
  317. # -----------------------------------------------------------------#
  318. # Write the brainregion and focus into frame
  319. # -----------------------------------------------------------------#
  320. def give_region_and_focus(row):
  321. regionname = row['binning'][1:]
  322. focus = row['binning_focus'][0] # f for focal and c for contralateral
  323. return '{}{}'.format(focus, regionname)
  324. mr_results['region'] = mr_results.apply(lambda row: give_region(row),
  325. axis=1)
  326. mr_results['regionfocus'] = mr_results.apply(lambda row:
  327. give_region_and_focus(row), axis=1)
  328. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  329. mr_results['logepsilon'] = mr_results.apply(
  330. lambda row: np.log(1 - row['m']), axis=1)
  331. quantity = 'epsilon'
  332. # -----------------------------------------------------------------#
  333. # Filter to recordings and regions for which paired data exists
  334. # -----------------------------------------------------------------#
  335. mr_results_paired = pd.DataFrame(columns=mr_results.columns)
  336. for rec in mr_results.recording.unique():
  337. recframe = mr_results[mr_results['recording'] == rec]
  338. for area in recframe['region'].unique():
  339. area_frame = recframe[recframe['region'] == area]
  340. if not len(area_frame['m'].tolist()) == 2:
  341. continue
  342. mr_results_paired = mr_results_paired.append(area_frame,
  343. ignore_index=True)
  344. mr_results = mr_results_paired
  345. # -----------------------------------------------------------------#
  346. # Compute p-values
  347. # -----------------------------------------------------------------#
  348. global_pvals, pvals = hierarchical_model.hierarchical_model_regions(
  349. mr_results)
  350. # -----------------------------------------------------------------#
  351. # Boxplot of regions
  352. # -----------------------------------------------------------------#
  353. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(10*1.2), cm2inch(3*1.2)))
  354. gb = sns.boxplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  355. data=mr_results, order=regions, hue_order=['focal',
  356. 'contra-lateral'], dodge=True, palette=['darkblue',
  357. 'slategray'], linewidth=1)
  358. for patch in ax.artists:
  359. r, g, b, a = patch.get_facecolor()
  360. patch.set_facecolor((r, g, b, .4))
  361. patch.set_edgecolor('gray')
  362. sns.stripplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  363. data=mr_results, alpha=0.9, order=regions,
  364. hue_order=['focal', 'contra-lateral'], jitter=False,
  365. size=2, palette=['darkblue', 'slategray'], dodge=True)
  366. ax.get_legend().set_visible(False)
  367. plt.grid(axis='x', b=False)
  368. gb.set_yscale("log")
  369. labels = []
  370. for ireg, reg in enumerate(regions):
  371. mr_results_r = mr_results[mr_results['region'] == reg]
  372. n_reg_f = len(mr_results_r[mr_results_r['binning_focus'] == 'focal'][
  373. 'm'].tolist())
  374. n_reg_c = len(mr_results_r[mr_results_r['binning_focus'] ==
  375. 'contra-lateral']['m'].tolist())
  376. labels.append('{}\n({}, {})'.format(reg, n_reg_f, n_reg_c))
  377. ax.set_xticklabels(labels)
  378. quantity_label = r'$\hat{m}$'
  379. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  380. ymax = 0.4 * np.min(mr_results[quantity].tolist())
  381. ax.set_ylim(ymin, ymax)
  382. T = [1, 1e-1, 1e-2, 1e-3]
  383. ax.set_yticks(T)
  384. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  385. plt.ylabel(quantity_label)
  386. sns.despine()
  387. # -----------------------------------------------------------------#
  388. # Annotate p-values of pairwise comparison
  389. # -----------------------------------------------------------------#
  390. y_max = 1.3*ymax
  391. y_min = ymin
  392. for ir, region in enumerate(regions):
  393. ax.annotate("", xy=(-0.2+ir*1.0, 1.5*y_max), xycoords='data',
  394. xytext=(0.2+ir*1.0, 1.5*y_max), textcoords='data',
  395. arrowprops=dict(arrowstyle="-", ec='black',
  396. connectionstyle="bar,fraction=0.3"))
  397. ax.text(-0.35+ir*1.0, y_max * 0.9 - abs(y_max - y_min) * 0.0,
  398. 'p'+'={:.3f}'.format(pvals[region]), fontsize=8.5)
  399. # -----------------------------------------------------------------#
  400. # Adjust some plot settings and save figures
  401. # -----------------------------------------------------------------#
  402. ax.set_xlabel('brain area')
  403. ax.set_ylim((ymin, ymax))
  404. ax.set_title('overall model: ' + str(global_pvals), fontsize=4)
  405. fig.subplots_adjust(bottom=None, right=None,
  406. wspace=0.2, hspace=0.5, left=0.15, top=1.2)
  407. plotfile_mx = '{}Fig1_regions_onlypaired.pdf'.format(result_path)
  408. fig.savefig(plotfile_mx, bbox_inches='tight')
  409. plt.show()
  410. plt.close('all')
  411. def boxplot_brainregions_focus(pkl_file_pre, pkl_file_inter, result_path):
  412. regions = ['H', 'A', 'PHC', 'EC']
  413. mr_results_pre = pd.read_pickle(pkl_file_pre)
  414. mr_results_inter = pd.read_pickle(pkl_file_inter)
  415. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  416. ignore_index=True)
  417. mr_results = mr_utilities.exclude_inconsistencies(mr_results)
  418. # -----------------------------------------------------------------#
  419. # Write the brainregion, independent of hemisphere, into frame
  420. # -----------------------------------------------------------------#
  421. def give_region(row):
  422. return row['binning'][1:]
  423. # -----------------------------------------------------------------#
  424. # Write the brainregion and focus into frame
  425. # -----------------------------------------------------------------#
  426. def give_region_and_focus(row):
  427. regionname = row['binning'][1:]
  428. focus = row['binning_focus'][0] # f for focal and c for contralateral
  429. return '{}{}'.format(focus, regionname)
  430. mr_results['region'] = mr_results.apply(lambda row: give_region(row),
  431. axis=1)
  432. mr_results['regionfocus'] = mr_results.apply(lambda row:
  433. give_region_and_focus(row), axis=1)
  434. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  435. mr_results['logepsilon'] = mr_results.apply(
  436. lambda row: np.log(1 - row['m']), axis=1)
  437. quantity = 'epsilon'
  438. # -----------------------------------------------------------------#
  439. # Compute p-values
  440. # -----------------------------------------------------------------#
  441. global_pvals, pvals = hierarchical_model.hierarchical_model_regions(
  442. mr_results)
  443. # -----------------------------------------------------------------#
  444. # Boxplot of regions
  445. # -----------------------------------------------------------------#
  446. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(10*1.2), cm2inch(3*1.2)))
  447. gb = sns.boxplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  448. data=mr_results, order=regions, hue_order=['focal',
  449. 'contra-lateral'], dodge=True, palette=['darkblue',
  450. 'slategray'], linewidth=1)
  451. gb.set_yscale("log")
  452. for patch in ax.artists:
  453. r, g, b, a = patch.get_facecolor()
  454. patch.set_facecolor((r, g, b, .4))
  455. patch.set_edgecolor('gray')
  456. sns.stripplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  457. data=mr_results, alpha=0.9, order=regions,
  458. hue_order=['focal', 'contra-lateral'], jitter=False,
  459. size=2, palette=['darkblue', 'slategray'], dodge=True)
  460. ax.get_legend().set_visible(False)
  461. plt.grid(axis='x', b=False)
  462. labels = []
  463. for ireg, reg in enumerate(regions):
  464. mr_results_r = mr_results[mr_results['region'] == reg]
  465. n_reg_f = len(mr_results_r[mr_results_r['binning_focus'] == 'focal'][
  466. 'm'].tolist())
  467. n_reg_c = len(mr_results_r[mr_results_r['binning_focus']
  468. == 'contra-lateral']['m'].tolist())
  469. labels.append('{}\n({}, {})'.format(reg, n_reg_f, n_reg_c))
  470. ax.set_xticklabels(labels)
  471. quantity_label = r'$\hat{m}$'
  472. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  473. ymax = 0.4 * np.min(mr_results[quantity].tolist())
  474. ax.set_ylim(ymin, ymax)
  475. T = [1, 1e-1, 1e-2, 1e-3]
  476. ax.set_yticks(T)
  477. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  478. plt.ylabel(quantity_label)
  479. sns.despine()
  480. # -----------------------------------------------------------------#
  481. # Annotate p-values of pairwise comparison
  482. # -----------------------------------------------------------------#
  483. y_max = 1.3*ymax
  484. y_min = ymin
  485. for ir, region in enumerate(regions):
  486. ax.annotate("", xy=(-0.2+ir*1.0, 1.5*y_max), xycoords='data',
  487. xytext=(0.2+ir*1.0, 1.5*y_max), textcoords='data',
  488. arrowprops=dict(arrowstyle="-", ec='black',
  489. connectionstyle="bar,fraction=0.3"))
  490. ax.text(-0.35+ir*1.0, y_max * 0.9 - abs(y_max - y_min) * 0.0,
  491. 'p'+'={:.3f}'.format(pvals[region]), fontsize=8.5)
  492. # -----------------------------------------------------------------#
  493. # Adjust some plot settings and save figures
  494. # -----------------------------------------------------------------#
  495. ax.set_xlabel('brain area')
  496. ax.set_ylim((ymin, ymax))
  497. ax.set_title('overall model: ' + str(global_pvals), fontsize=4)
  498. fig.subplots_adjust(bottom=None, right=None,
  499. wspace=0.2, hspace=0.5, left=0.15, top=1.2)
  500. plotfile_mx = '{}Fig1_regions.pdf'.format(result_path)
  501. fig.savefig(plotfile_mx, bbox_inches='tight')
  502. plt.show()
  503. plt.close('all')
  504. def boxplot_brainregions_focus_Engel(pkl_file_pre,pkl_file_inter,result_path):
  505. regions = ['H', 'A', 'PHC', 'EC']
  506. mr_results_pre = pd.read_pickle(pkl_file_pre)
  507. mr_results_inter = pd.read_pickle(pkl_file_inter)
  508. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  509. ignore_index=True)
  510. patients1a = [1, 6, 8, 9, 10, 11, 16, 17, 18, 19]
  511. mr_results = mr_results[(mr_results['patient'].isin(patients1a))]
  512. mr_results = mr_utilities.exclude_inconsistencies(mr_results)
  513. # -----------------------------------------------------------------#
  514. # Write the brainregion, independent of hemisphere, into frame
  515. # -----------------------------------------------------------------#
  516. def give_region(row):
  517. return row['binning'][1:]
  518. # -----------------------------------------------------------------#
  519. # Write the brainregion and focus into frame
  520. # -----------------------------------------------------------------#
  521. def give_region_and_focus(row):
  522. regionname = row['binning'][1:]
  523. focus = row['binning_focus'][0] # f for focal and c for contralateral
  524. return '{}{}'.format(focus, regionname)
  525. mr_results['region'] = mr_results.apply(lambda row: give_region(row),
  526. axis=1)
  527. mr_results['regionfocus'] = mr_results.apply(lambda row:
  528. give_region_and_focus(row), axis=1)
  529. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  530. mr_results['logepsilon'] = mr_results.apply(
  531. lambda row: np.log(1 - row['m']), axis=1)
  532. quantity = 'epsilon'
  533. # -----------------------------------------------------------------#
  534. # Compute p-values
  535. # -----------------------------------------------------------------#
  536. global_pvals, pvals = hierarchical_model.hierarchical_model_regions(
  537. mr_results)
  538. # -----------------------------------------------------------------#
  539. # Boxplot of regions
  540. # -----------------------------------------------------------------#
  541. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(10*1.2), cm2inch(3*1.2)))
  542. gb = sns.boxplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  543. data=mr_results, order=regions, hue_order=['focal',
  544. 'contra-lateral'],
  545. dodge=True, palette=['darkblue', 'slategray'], linewidth=1)
  546. for patch in ax.artists:
  547. r, g, b, a = patch.get_facecolor()
  548. patch.set_facecolor((r, g, b, .4))
  549. patch.set_edgecolor('gray')
  550. sns.stripplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  551. data=mr_results, alpha=0.9, order=regions,
  552. hue_order=['focal', 'contra-lateral'], jitter=False,
  553. size=2, palette=['darkblue', 'slategray'], dodge=True)
  554. ax.get_legend().set_visible(False)
  555. plt.grid(axis='x', b=False)
  556. gb.set_yscale("log")
  557. labels = []
  558. for ireg, reg in enumerate(regions):
  559. mr_results_r = mr_results[mr_results['region']==reg]
  560. n_reg_f = len(mr_results_r[mr_results_r['binning_focus']=='focal'][
  561. 'm'].tolist())
  562. n_reg_c = len(mr_results_r[mr_results_r['binning_focus']==
  563. 'contra-lateral']['m'].tolist())
  564. labels.append('{}\n({}, {})'.format(reg, n_reg_f, n_reg_c))
  565. ax.set_xticklabels(labels)
  566. quantity_label = r'$\hat{m}$'
  567. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  568. ymax = 0.4 * np.min(mr_results[quantity].tolist())
  569. ax.set_ylim(ymin, ymax)
  570. T = [1, 1e-1, 1e-2, 1e-3]
  571. ax.set_yticks(T)
  572. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  573. plt.ylabel(quantity_label)
  574. sns.despine()
  575. # -----------------------------------------------------------------#
  576. # Annotate p-values of pairwise comparison
  577. # -----------------------------------------------------------------#
  578. y_max = 0.85*ymax
  579. if quantity == 'epsilon':
  580. y_max = 1.3*ymax
  581. y_min = ymin
  582. for ir, region in enumerate(regions):
  583. ax.annotate("", xy=(-0.2+ir*1.0, 1.5*y_max), xycoords='data',
  584. xytext=(0.2+ir*1.0, 1.5*y_max), textcoords='data',
  585. arrowprops=dict(arrowstyle="-", ec='black',
  586. connectionstyle="bar,fraction=0.3"))
  587. ax.text(-0.35+ir*1.0, y_max * 0.9 - abs(y_max - y_min) * 0.0,
  588. 'p'+'={:.3f}'.format(pvals[region]), fontsize=8.5)
  589. # -----------------------------------------------------------------#
  590. # Adjust some plot settings and save figures
  591. # -----------------------------------------------------------------#
  592. ax.set_xlabel('brain area')
  593. ax.set_ylim((ymin, ymax))
  594. ax.set_title('overall model: ' + str(global_pvals), fontsize=4)
  595. fig.subplots_adjust(bottom=None, right=None,
  596. wspace=0.2, hspace=0.5, left=0.15, top=1.2)
  597. plotfile_mx = '{}Fig1_regions_Engel1a.pdf'.format(result_path)
  598. fig.savefig(plotfile_mx, bbox_inches='tight')
  599. plt.show()
  600. plt.close('all')
  601. def boxplot_hemispheres():
  602. result_path = '../Results/preictal/singleunits/'
  603. pkl_file = result_path + 'mr_results.pkl'
  604. pkl_file_pre = pkl_file
  605. result_path_inter = '../Results/interictal/singleunits/'
  606. pkl_file_inter = result_path_inter + 'mr_results.pkl'
  607. boxplot_focal_contra(pkl_file_pre, pkl_file_inter,
  608. result_path)
  609. boxplot_focal_contra_Engel(pkl_file_pre, pkl_file_inter,
  610. result_path)
  611. boxplot_focal_contra_onlypaired(pkl_file_pre, pkl_file_inter,
  612. result_path)
  613. def pointplot_patients_hemispheres():
  614. pkl_file_pre = '../Results/preictal/singleunits/mr_results.pkl'
  615. pkl_file_inter = '../Results/interictal/singleunits/mr_results.pkl'
  616. result_path_pointplot = '../Results/preictal/singleunits/'
  617. patientwise_pointplots(pkl_file_pre, pkl_file_inter,
  618. result_path_pointplot)
  619. def boxplot_regions():
  620. result_path = '../Results/preictal/singleunits_regions/'
  621. pkl_file = result_path + 'mr_results.pkl'
  622. result_path_inter = '../Results/interictal/singleunits_regions/'
  623. pkl_file_inter = result_path_inter + 'mr_results.pkl'
  624. boxplot_brainregions_focus(pkl_file, pkl_file_inter, result_path)
  625. boxplot_brainregions_focus_Engel(pkl_file, pkl_file_inter, result_path)
  626. boxplot_brainregions_focus_onlypaired(pkl_file, pkl_file_inter,
  627. result_path)
  628. def main():
  629. boxplot_hemispheres()
  630. pointplot_patients_hemispheres()
  631. boxplot_regions()
  632. if __name__ == '__main__':
  633. main()