create_figure_1.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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,
  12. resultpath, excludeInconsistencies, **kwargs):
  13. mr_results_pre = pd.read_pickle(pkl_file_pre)
  14. mr_results_inter = pd.read_pickle(pkl_file_inter)
  15. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  16. ignore_index=True)
  17. mr_results = mr_results[(mr_results['fit_method'] == 'offset')]
  18. conditions = list()
  19. for key in kwargs.keys():
  20. conditions.append(mr_results[key] == kwargs[key])
  21. if len(conditions) > 0:
  22. mr_results = mr_results[mr_utilities.conjunction(*conditions)]
  23. if excludeInconsistencies:
  24. rejected_inconsistencies = ['H_nonzero', 'H_linear']
  25. for incon in rejected_inconsistencies:
  26. mr_results = mr_results[[incon not in mr_results[
  27. 'inconsistencies'].tolist()[i] for i in range(
  28. len(mr_results['inconsistencies'].tolist()))]]
  29. mr_results['logtau'] = mr_results.apply(lambda row: np.log(row['tau']),
  30. axis=1)
  31. mr_results['logepsilon'] = mr_results.apply(lambda row: abs(np.log(1-row[
  32. 'm'])), axis=1)
  33. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  34. quantity = 'epsilon'
  35. # ================================================================== #
  36. # compute pvalue (paired, just uses data with pair)
  37. # ================================================================== #
  38. truediff = []
  39. paired_recordings = []
  40. for rec in mr_results.recording.unique():
  41. recframe = mr_results[mr_results['recording']==rec]
  42. if not len(recframe['m'].tolist()) == 2:
  43. continue
  44. focalval = recframe[recframe['binning_focus']=='focal'][quantity].item()
  45. contraval = recframe[recframe['binning_focus'] == 'contra-lateral'][
  46. quantity].item()
  47. truediff.append(focalval - contraval)
  48. paired_recordings.append(rec)
  49. mr_results_paired = mr_results[mr_results['recording'].isin(paired_recordings)]
  50. p_hierarchical = hierarchical_model.hierarchical_model_hemispheres(
  51. mr_results_paired)
  52. # ================================================================== #
  53. # Plotting
  54. # ================================================================== #
  55. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(4), cm2inch(3)))
  56. gb = sns.boxplot(ax=ax, x="binning_focus", y=quantity,
  57. data=mr_results_paired, order=['focal', 'contra-lateral'],
  58. dodge=True, palette=['darkblue', 'slategray'])
  59. for patch in ax.artists:
  60. r, g, b, a = patch.get_facecolor()
  61. patch.set_facecolor((r, g, b, .4))
  62. patch.set_edgecolor('gray')
  63. sns.stripplot(ax=ax, x="binning_focus", y=quantity,
  64. data=mr_results_paired, alpha=0.9, order=['focal',
  65. 'contra-lateral'], size=2, dodge=True, palette=[
  66. 'darkblue', 'slategray'], jitter=False)
  67. gb.set_yscale("log")
  68. plt.grid(axis='x', b=False)
  69. n_SOZ = len(mr_results_paired[mr_results_paired['binning_focus']=='focal']['m'].tolist())
  70. n_nSOZ = len(
  71. mr_results_paired[mr_results_paired['binning_focus'] == 'contra-lateral'][
  72. 'm'].tolist())
  73. ax.set_xticklabels(['ipsi\n({})'.format(n_SOZ), 'contra\n({})'.format(
  74. n_nSOZ)])
  75. ax.set_xlabel('')
  76. quantity_label = r'$\hat{m}$'
  77. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  78. ymax = 0.6*np.min(mr_results[quantity].tolist())
  79. ax.set_ylim(ymin, ymax)
  80. T = [1, 1e-1, 1e-2, 1e-3]
  81. ax.set_yticks(T)
  82. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  83. plt.ylabel(quantity_label)
  84. sns.despine()
  85. # ================================================================== #
  86. # Annotate pvalues
  87. # ================================================================== #
  88. x1, x2 = 0, 1
  89. y, h = ymax * (1.1), -0.1 * ymax
  90. ax.plot([x1, x1, x2, x2], [y, y + h, y + h, y], lw=1.5, c='black')
  91. ax.text((x1 + x2) * .5, y + 4*h, r"$p$"+"={:.3f}".format(
  92. p_hierarchical), ha='center', va='bottom', color='black', fontsize=10)
  93. # ================================================================== #
  94. # Final figure adjustments + saving
  95. # ================================================================== #
  96. sns.despine(fig)
  97. fig.subplots_adjust(bottom=None, right=None,
  98. wspace=0.8, hspace=0.5, left=0.15, top=1.2)
  99. kmin = mr_results["kmin"].unique()[0]
  100. kmax = mr_results["kmax"].unique()[0]
  101. resultfile = '{}Fig1_boxplot_{}_kmin{}_kmax{}_onlypaired.pdf'.format(
  102. resultpath,quantity, kmin, kmax)
  103. plt.savefig(resultfile, bbox_inches='tight')
  104. plt.show()
  105. plt.close()
  106. def boxplot_focal_contra_Engel(pkl_file_pre, pkl_file_inter,
  107. resultpath, excludeInconsistencies, **kwargs):
  108. mr_results_pre = pd.read_pickle(pkl_file_pre)
  109. mr_results_inter = pd.read_pickle(pkl_file_inter)
  110. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  111. ignore_index=True)
  112. patients1a = [1, 6, 8, 9, 10, 11, 16, 17, 18, 19]
  113. mr_results = mr_results[(mr_results['patient'].isin(patients1a))]
  114. mr_results = mr_results[(mr_results['fit_method'] == 'offset')]
  115. conditions = list()
  116. for key in kwargs.keys():
  117. conditions.append(mr_results[key] == kwargs[key])
  118. if len(conditions) > 0:
  119. mr_results = mr_results[mr_utilities.conjunction(*conditions)]
  120. if excludeInconsistencies:
  121. rejected_inconsistencies = ['H_nonzero', 'H_linear']
  122. for incon in rejected_inconsistencies:
  123. mr_results = mr_results[[incon not in mr_results[
  124. 'inconsistencies'].tolist()[i] for i in range(
  125. len(mr_results['inconsistencies'].tolist()))]]
  126. mr_results['logtau'] = mr_results.apply(lambda row: np.log(row['tau']),
  127. axis=1)
  128. mr_results['logepsilon'] = mr_results.apply(lambda row: abs(np.log(1-row[
  129. 'm'])), axis=1)
  130. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row[
  131. 'm'], axis=1)
  132. quantity = 'epsilon'
  133. # ================================================================== #
  134. # compute pvalue (unpaired, all data)
  135. # ================================================================== #
  136. p_hierarchical = hierarchical_model.hierarchical_model_hemispheres(
  137. mr_results)
  138. # ================================================================== #
  139. # Plotting
  140. # ================================================================== #
  141. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(4), cm2inch(3)))
  142. gb = sns.boxplot(ax=ax, x="binning_focus", y=quantity,
  143. data=mr_results, order=['focal', 'contra-lateral'],
  144. dodge=True, palette=['darkblue', 'slategray'])
  145. for patch in ax.artists:
  146. r, g, b, a = patch.get_facecolor()
  147. patch.set_facecolor((r, g, b, .4))
  148. patch.set_edgecolor('gray')
  149. sns.stripplot(ax=ax, x="binning_focus", y=quantity,
  150. data=mr_results, alpha=0.9, order=['focal',
  151. 'contra-lateral'],
  152. size=2, dodge=True, palette=['darkblue', 'slategray'], jitter=False)
  153. gb.set_yscale("log")
  154. plt.grid(axis='x', b=False)
  155. n_SOZ = len(mr_results[mr_results['binning_focus']=='focal']['m'].tolist())
  156. n_nSOZ = len(mr_results[mr_results['binning_focus'] == 'contra-lateral'][
  157. 'm'].tolist())
  158. ax.set_xticklabels(['ipsi\n({})'.format(n_SOZ), 'contra\n({})'.format(
  159. n_nSOZ)])
  160. ax.set_xlabel('')
  161. quantity_label = r'$\hat{m}$'
  162. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  163. ymax = 0.6*np.min(mr_results[quantity].tolist())
  164. ax.set_ylim(ymin, ymax)
  165. T = [1, 1e-1, 1e-2, 1e-3]
  166. ax.set_yticks(T)
  167. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  168. plt.ylabel(quantity_label)
  169. sns.despine()
  170. # ================================================================== #
  171. # Annotate pvalues
  172. # ================================================================== #
  173. x1, x2 = 0, 1
  174. y, h = ymax * (1.1), -0.1 * ymax
  175. ax.plot([x1, x1, x2, x2], [y, y + h, y + h, y], lw=1.5, c='black')
  176. ax.text((x1 + x2) * .5, y + 4*h, r"$p$"+"={:.3f}".format(p_hierarchical),
  177. ha='center', va='bottom', color='black', fontsize=10)
  178. # ================================================================== #
  179. # Final figure adjustments + saving
  180. # ================================================================== #
  181. sns.despine(fig)
  182. fig.subplots_adjust(bottom=None, right=None,
  183. wspace=0.8, hspace=0.5, left=0.15, top=1.2)
  184. kmin = mr_results["kmin"].unique()[0]
  185. kmax = mr_results["kmax"].unique()[0]
  186. resultfile = '{}Fig1_boxplot_{}_kmin{}_kmax{}1aEngel.pdf'.format(
  187. resultpath,quantity, kmin, kmax)
  188. plt.savefig(resultfile, bbox_inches='tight')
  189. plt.show()
  190. plt.close()
  191. def boxplot_focal_contra(pkl_file_pre, pkl_file_inter, resultpath,
  192. excludeInconsistencies, **kwargs):
  193. mr_results_pre = pd.read_pickle(pkl_file_pre)
  194. mr_results_inter = pd.read_pickle(pkl_file_inter)
  195. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  196. ignore_index=True)
  197. mr_results = mr_results[(mr_results['fit_method'] == 'offset')]
  198. conditions = list()
  199. for key in kwargs.keys():
  200. conditions.append(mr_results[key] == kwargs[key])
  201. if len(conditions) > 0:
  202. mr_results = mr_results[mr_utilities.conjunction(*conditions)]
  203. if excludeInconsistencies:
  204. rejected_inconsistencies = ['H_nonzero', 'H_linear']
  205. for incon in rejected_inconsistencies:
  206. mr_results = mr_results[[incon not in mr_results[
  207. 'inconsistencies'].tolist()[i] for i in range(
  208. len(mr_results['inconsistencies'].tolist()))]]
  209. mr_results['logtau'] = mr_results.apply(lambda row: np.log(row['tau']),
  210. axis=1)
  211. mr_results['logepsilon'] = mr_results.apply(lambda row: abs(np.log(1-row[
  212. 'm'])), axis=1)
  213. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  214. quantity = 'epsilon'
  215. # ================================================================== #
  216. # compute p-value (unpaired, all data)
  217. # ================================================================== #
  218. p_hierarchical = hierarchical_model.hierarchical_model_hemispheres(mr_results)
  219. # ================================================================== #
  220. # Plotting
  221. # ================================================================== #
  222. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(4), cm2inch(3)))
  223. gb = sns.boxplot(ax=ax, x="binning_focus", y=quantity,
  224. data=mr_results, order=['focal', 'contra-lateral'],
  225. dodge=True, palette=['darkblue', 'slategray'])
  226. for patch in ax.artists:
  227. r, g, b, a = patch.get_facecolor()
  228. patch.set_facecolor((r, g, b, .4))
  229. patch.set_edgecolor('gray')
  230. sns.stripplot(ax=ax, x="binning_focus", y=quantity,
  231. data=mr_results, alpha=0.9, order=['focal',
  232. 'contra-lateral'],
  233. size=2, dodge=True, palette=['darkblue', 'slategray'],
  234. jitter=False)
  235. gb.set_yscale("log")
  236. plt.grid(axis='x', b=False)
  237. n_SOZ = len(mr_results[mr_results['binning_focus'] == 'focal'][
  238. 'm'].tolist())
  239. n_nSOZ = len(mr_results[mr_results['binning_focus'] == 'contra-lateral'][
  240. 'm'].tolist())
  241. ax.set_xticklabels(['ipsi\n({})'.format(n_SOZ), 'contra\n({})'.format(
  242. n_nSOZ)])
  243. ax.set_xlabel('')
  244. quantity_label = r'$\hat{m}$'
  245. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  246. ymax = 0.6*np.min(mr_results[quantity].tolist())
  247. ax.set_ylim(ymin, ymax)
  248. T = [1, 1e-1, 1e-2, 1e-3]
  249. ax.set_yticks(T)
  250. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  251. plt.ylabel(quantity_label)
  252. sns.despine()
  253. # ================================================================== #
  254. # Annotate pvalues
  255. # ================================================================== #
  256. x1, x2 = 0, 1
  257. y, h = ymax * (1.1), -0.1 * ymax
  258. ax.plot([x1, x1, x2, x2], [y, y + h, y + h, y], lw=1.5, c='black')
  259. ax.text((x1 + x2) * .5, y + 4*h, r"$p$"+"={:.3f}".format(p_hierarchical),
  260. ha='center', va='bottom', color='black', fontsize=10)
  261. # ================================================================== #
  262. # Final figure adjustments + saving
  263. # ================================================================== #
  264. sns.despine(fig)
  265. fig.subplots_adjust(bottom=None, right=None,
  266. wspace=0.8, hspace=0.5, left=0.15, top=1.2)
  267. kmin = mr_results["kmin"].unique()[0]
  268. kmax = mr_results["kmax"].unique()[0]
  269. resultfile = '{}Fig1_boxplot_{}_kmin{}_kmax{}.pdf'.format(
  270. resultpath,quantity, kmin, kmax)
  271. plt.savefig(resultfile, bbox_inches='tight')
  272. plt.show()
  273. plt.close()
  274. def patientwise_pointplots(pkl_file_pre, pkl_file_inter,
  275. result_path, excludeInconsistencies, **kwargs):
  276. # -----------------------------------------------------------------#
  277. # Read data
  278. # -----------------------------------------------------------------#
  279. mr_results_inter = pd.read_pickle(pkl_file_inter)
  280. mr_results_inter['rec_type'] = mr_results_inter.apply(lambda row: 'inter',
  281. axis=1)
  282. mr_results_pre = pd.read_pickle(pkl_file_pre)
  283. mr_results_pre['rec_type'] = mr_results_pre.apply(lambda row: 'pre',
  284. axis=1)
  285. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  286. ignore_index=True)
  287. mr_results = mr_results[(mr_results['fit_method'] == 'offset')]
  288. conditions = list()
  289. for key in kwargs.keys():
  290. conditions.append(mr_results[key] == kwargs[key])
  291. if len(conditions) > 0:
  292. mr_results = mr_results[mr_utilities.conjunction(*conditions)]
  293. if excludeInconsistencies:
  294. rejected_inconsistencies = ['H_nonzero', 'H_linear']
  295. for incon in rejected_inconsistencies:
  296. mr_results = mr_results[[incon not in mr_results[
  297. 'inconsistencies'].tolist()[i] for i in range(
  298. len(mr_results['inconsistencies'].tolist()))]]
  299. mr_results['logepsilon'] = mr_results.apply(lambda row: abs(
  300. np.log(1-row['m'])), axis=1)
  301. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  302. quantity = 'epsilon'
  303. # -----------------------------------------------------------------#
  304. # Run through all patients that also have preictal data
  305. # get their interictal and preictal results plot them as a pointplot
  306. # -----------------------------------------------------------------#
  307. patients = mr_results['patient'].unique()
  308. patients_sorted = np.sort(patients)
  309. fig, ax = plt.subplots(5, 4, figsize=(12, 1.5 * 5))
  310. v = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]
  311. h = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
  312. for ip, patient in enumerate(patients_sorted):
  313. mr_patient = mr_results[mr_results['patient'] == patient]
  314. recordings = mr_patient.recording.unique()
  315. all_SOZ = mr_patient[mr_patient['binning_focus'] == 'focal'][
  316. quantity].tolist()
  317. all_nSOZ = mr_patient[mr_patient['binning_focus'] == 'contra-lateral'][
  318. quantity].tolist()
  319. stat, p_unpaired = stats.mannwhitneyu(all_SOZ, all_nSOZ, alternative='two-sided')
  320. for rec in recordings:
  321. mr_rec = mr_patient[mr_patient['recording'] == rec]
  322. if len(mr_rec[quantity].tolist()) == 2:
  323. q_SOZ = mr_rec[mr_rec['binning_focus'] == 'focal'][
  324. quantity].item()
  325. q_nSOZ = mr_rec[mr_rec['binning_focus'] == 'contra-lateral'][
  326. quantity].item()
  327. color = 'darkorange'
  328. if mr_rec['rec_type'].tolist()[0] == 'pre':
  329. color = 'indianred'
  330. ax[h[ip], v[ip]].plot([1, 2], [q_SOZ, q_nSOZ], c=color,
  331. marker='.', markersize=6)
  332. elif len(mr_rec[mr_rec['binning_focus']=='focal'].index) == 1:
  333. q_SOZ = mr_rec[mr_rec['binning_focus']=='focal'][
  334. quantity].item()
  335. color = 'darkorange'
  336. if mr_rec['rec_type'].tolist()[0] == 'pre':
  337. color = 'indianred'
  338. ax[h[ip], v[ip]].plot([1], [q_SOZ], c=color,
  339. marker='.', markersize=6)
  340. elif len(mr_rec[mr_rec['binning_focus']=='contra-lateral'].index) \
  341. == 1:
  342. q_nSOZ = mr_rec[mr_rec['binning_focus']=='contra-lateral'][
  343. quantity].item()
  344. color = 'darkorange'
  345. if mr_rec['rec_type'].tolist()[0] == 'pre':
  346. color = 'indianred'
  347. ax[h[ip], v[ip]].plot([2], [q_nSOZ], c=color,
  348. marker='.', markersize=6)
  349. if len(all_SOZ)+len(all_nSOZ) >= 8:
  350. ax[h[ip], v[ip]].text(0.5, 0.9,'p={:.3f}'.format(p_unpaired),
  351. horizontalalignment='center', verticalalignment='center',
  352. transform=ax[h[ip], v[ip]].transAxes, color='black',
  353. fontsize=10)
  354. ax[h[ip], v[ip]].set_title('Patient {}'.format(patient))
  355. ax[h[ip], v[ip]].set_yscale("log")
  356. quantity_label = r'$\hat{m}$'
  357. ax[h[ip], v[ip]].set_ylabel(quantity_label)
  358. ymin = 1.1
  359. ymax = 1e-3
  360. ax[h[ip], v[ip]].set_ylim(ymin, ymax)
  361. ax[h[ip], v[ip]].set_xlim(0.7, 2.3)
  362. T = [1, 2]
  363. ax[h[ip], v[ip]].set_xticks(T)
  364. ax[h[ip], v[ip]].set_xticklabels(['ipsi', 'contra'])
  365. T = [1, 1e-1, 1e-2, 1e-3]
  366. ax[h[ip], v[ip]].set_yticks(T)
  367. ax[h[ip], v[ip]].set_yticklabels([0, 0.9, 0.99, 0.999])
  368. ax[h[ip], v[ip]].set_xlabel(' ')
  369. ax[h[ip], v[ip]].set_xticklabels(['ipsi', 'contra'])
  370. sns.despine(fig)
  371. fig.subplots_adjust(bottom=None, right=None,
  372. wspace=0.7, hspace=0.7, left=0.15, top=1.2)
  373. kmin = mr_results_pre['kmin'].unique()[0]
  374. kmax = mr_results_pre['kmax'].unique()[0]
  375. plotfile_mx = '{}S2_{}_patients_kmin{}_kmax{}.pdf'.format(
  376. result_path, quantity, kmin, kmax)
  377. fig.savefig(plotfile_mx, bbox_inches='tight')
  378. plt.show()
  379. def boxplot_brainregions_focus_onlypaired(pkl_file_pre, pkl_file_inter,
  380. result_path,
  381. excludeInconsistencies, **kwargs):
  382. regions = ['H', 'A', 'PHC', 'EC']
  383. mr_results_pre = pd.read_pickle(pkl_file_pre)
  384. mr_results_inter = pd.read_pickle(pkl_file_inter)
  385. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  386. ignore_index=True)
  387. mr_results = mr_results[(mr_results['fit_method'] == 'offset')]
  388. conditions = list()
  389. for key in kwargs.keys():
  390. conditions.append(mr_results[key] == kwargs[key])
  391. if len(conditions) > 0:
  392. mr_results = mr_results[mr_utilities.conjunction(*conditions)]
  393. if excludeInconsistencies:
  394. rejected_inconsistencies = ['H_nonzero', 'H_linear']
  395. for incon in rejected_inconsistencies:
  396. mr_results = mr_results[[incon not in mr_results[
  397. 'inconsistencies'].tolist()[i] for i in range(
  398. len(mr_results['inconsistencies'].tolist()))]]
  399. # -----------------------------------------------------------------#
  400. # Write the brainregion, independent of hemisphere, into frame
  401. # -----------------------------------------------------------------#
  402. def give_region(row):
  403. return row['binning'][1:]
  404. # -----------------------------------------------------------------#
  405. # Write the brainregion and focus into frame
  406. # -----------------------------------------------------------------#
  407. def give_region_and_focus(row):
  408. regionname = row['binning'][1:]
  409. focus = row['binning_focus'][0] # f for focal and c for contralateral
  410. return '{}{}'.format(focus, regionname)
  411. mr_results['region'] = mr_results.apply(lambda row: give_region(row), axis=1)
  412. mr_results['regionfocus'] = mr_results.apply(lambda row: give_region_and_focus(row), axis=1)
  413. mr_results['logtau'] = mr_results.apply(lambda row: np.log(row['tau']),
  414. axis=1)
  415. mr_results['logepsilon'] = mr_results.apply(lambda row: abs(np.log(
  416. 1-row['m'])), axis=1)
  417. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  418. quantity = 'epsilon'
  419. # -----------------------------------------------------------------#
  420. # Filter to recordings and regions for which paired data exists
  421. # -----------------------------------------------------------------#
  422. mr_results_paired = pd.DataFrame(columns=mr_results.columns)
  423. differences = dict({'A':[], 'H':[], 'PHC':[], 'EC':[]})
  424. for rec in mr_results.recording.unique():
  425. recframe = mr_results[mr_results['recording']==rec]
  426. for area in recframe['region'].unique():
  427. area_frame = recframe[recframe['region'] == area]
  428. if not len(area_frame['m'].tolist()) == 2:
  429. continue
  430. focalval = area_frame[area_frame['binning_focus'] == 'focal'][
  431. quantity].item()
  432. contraval = \
  433. area_frame[area_frame['binning_focus'] == 'contra-lateral'][
  434. quantity].item()
  435. differences[area].append(focalval - contraval)
  436. mr_results_paired = mr_results_paired.append(area_frame,
  437. ignore_index=True)
  438. mr_results = mr_results_paired
  439. # -----------------------------------------------------------------#
  440. # Compute p-values of pairwise comparison
  441. # -----------------------------------------------------------------#
  442. pvals = dict()
  443. medians = dict()
  444. for area in mr_results['region'].unique():
  445. region_differences = differences[area]
  446. stat, p_paired = stats.wilcoxon(region_differences) # wilcoxon is by
  447. # default two-sided
  448. pvals[area] = p_paired
  449. medians['f{}'.format(area)] = np.median(focalval)
  450. medians['c{}'.format(area)] = np.median(contraval)
  451. global_pvals, pvals_regions = hierarchical_model.hierarchical_model_regions(
  452. mr_results)
  453. pvals = pvals_regions
  454. # -----------------------------------------------------------------#
  455. # Boxplot of regions
  456. # -----------------------------------------------------------------#
  457. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(10*1.2), cm2inch(3*1.2)))
  458. gb = sns.boxplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  459. data=mr_results, order=regions, hue_order=['focal',
  460. 'contra-lateral'],
  461. dodge=True, palette=['darkblue', 'slategray'], linewidth=1)
  462. for patch in ax.artists:
  463. r, g, b, a = patch.get_facecolor()
  464. patch.set_facecolor((r, g, b, .4))
  465. patch.set_edgecolor('gray')
  466. sns.stripplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  467. data=mr_results, alpha=0.9, order=regions,
  468. hue_order=['focal', 'contra-lateral'], jitter=False,
  469. size=2, palette=['darkblue', 'slategray'], dodge=True)
  470. ax.get_legend().set_visible(False)
  471. plt.grid(axis='x', b=False)
  472. gb.set_yscale("log")
  473. labels = []
  474. for ireg, reg in enumerate(regions):
  475. mr_results_r = mr_results[mr_results['region']==reg]
  476. n_reg_f = len(mr_results_r[mr_results_r['binning_focus']=='focal'][
  477. 'm'].tolist())
  478. n_reg_c = len(mr_results_r[mr_results_r[
  479. 'binning_focus']=='contra-lateral'][
  480. 'm'].tolist())
  481. labels.append('{}\n({}, {})'.format(reg, n_reg_f, n_reg_c))
  482. ax.set_xticklabels(labels)
  483. quantity_label = r'$\hat{m}$'
  484. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  485. ymax = 0.4 * np.min(mr_results[quantity].tolist())
  486. ax.set_ylim(ymin, ymax)
  487. T = [1, 1e-1, 1e-2, 1e-3]
  488. ax.set_yticks(T)
  489. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  490. plt.ylabel(quantity_label)
  491. sns.despine()
  492. # -----------------------------------------------------------------#
  493. # Annotate p-values of pairwise comparison
  494. # -----------------------------------------------------------------#
  495. y_max = 1.3*ymax
  496. y_min = ymin
  497. for ir, region in enumerate(regions):
  498. ax.annotate("", xy=(-0.2+ir*1.0, 1.5*y_max), xycoords='data',
  499. xytext=(0.2+ir*1.0, 1.5*y_max), textcoords='data',
  500. arrowprops=dict(arrowstyle="-", ec='black',
  501. connectionstyle="bar,fraction=0.3"))
  502. ax.text(-0.35+ir*1.0, y_max* 0.9- abs(y_max - y_min) * 0.0,
  503. 'p'+'={:.3f}'.format(pvals[region]), fontsize=8.5)
  504. # -----------------------------------------------------------------#
  505. # Adjust some plot settings and save figures
  506. # -----------------------------------------------------------------#
  507. ax.set_xlabel('brain area')
  508. ax.set_ylim((ymin, ymax))
  509. ax.set_title('overall model: ' + str(global_pvals), fontsize=4)
  510. fig.subplots_adjust(bottom=None, right=None,
  511. wspace=0.2, hspace=0.5, left=0.15, top=1.2)
  512. kmin = mr_results['kmin'].unique()[0]
  513. kmax = mr_results['kmax'].unique()[0]
  514. plotfile_mx = '{}Fig1_regions_{}_kmin{}_kmax{}_exclude_{}_onlypaired.pdf'.format(
  515. result_path, quantity, kmin, kmax, excludeInconsistencies)
  516. fig.savefig(plotfile_mx, bbox_inches='tight')
  517. plt.show()
  518. plt.close('all')
  519. def boxplot_brainregions_focus(pkl_file_pre, pkl_file_inter, result_path,
  520. excludeInconsistencies, **kwargs):
  521. regions = ['H', 'A', 'PHC', 'EC']
  522. mr_results_pre = pd.read_pickle(pkl_file_pre)
  523. mr_results_inter = pd.read_pickle(pkl_file_inter)
  524. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  525. ignore_index=True)
  526. mr_results = mr_results[(mr_results['fit_method'] == 'offset')]
  527. conditions = list()
  528. for key in kwargs.keys():
  529. conditions.append(mr_results[key] == kwargs[key])
  530. if len(conditions) > 0:
  531. mr_results = mr_results[mr_utilities.conjunction(*conditions)]
  532. if excludeInconsistencies:
  533. rejected_inconsistencies = ['H_nonzero', 'H_linear']
  534. for incon in rejected_inconsistencies:
  535. mr_results = mr_results[[incon not in mr_results[
  536. 'inconsistencies'].tolist()[i] for i in range(
  537. len(mr_results['inconsistencies'].tolist()))]]
  538. # -----------------------------------------------------------------#
  539. # Write the brainregion, independent of hemisphere, into frame
  540. # -----------------------------------------------------------------#
  541. def give_region(row):
  542. return row['binning'][1:]
  543. # -----------------------------------------------------------------#
  544. # Write the brainregion and focus into frame
  545. # -----------------------------------------------------------------#
  546. def give_region_and_focus(row):
  547. regionname = row['binning'][1:]
  548. focus = row['binning_focus'][0] # f for focal and c for contralateral
  549. return '{}{}'.format(focus, regionname)
  550. mr_results['region'] = mr_results.apply(lambda row: give_region(row), axis=1)
  551. mr_results['regionfocus'] = mr_results.apply(lambda row: give_region_and_focus(row), axis=1)
  552. mr_results['logtau'] = mr_results.apply(lambda row: np.log(row['tau']),axis=1)
  553. mr_results['logepsilon'] = mr_results.apply(lambda row: -np.log(1-row['m']), axis=1)
  554. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  555. quantity = 'epsilon'
  556. # -----------------------------------------------------------------#
  557. # Compute p-values of pairwise comparison
  558. # -----------------------------------------------------------------#
  559. pvals = dict()
  560. medians = dict()
  561. for area in mr_results['region'].unique():
  562. area_frame = mr_results[mr_results['region'] == area]
  563. f_area_frame = area_frame[area_frame['binning_focus'] == 'focal']
  564. c_area_frame = area_frame[area_frame['binning_focus'] ==
  565. 'contra-lateral']
  566. focalval = f_area_frame[quantity].tolist()
  567. contraval = c_area_frame[quantity].tolist()
  568. stat, p = stats.mannwhitneyu(focalval, contraval,
  569. alternative='two-sided')
  570. pvals[area] = p
  571. medians['f{}'.format(area)] = np.median(focalval)
  572. medians['c{}'.format(area)] = np.median(contraval)
  573. global_pvals, pvals_regions = hierarchical_model.hierarchical_model_regions(
  574. mr_results)
  575. pvals = pvals_regions
  576. # -----------------------------------------------------------------#
  577. # Boxplot of regions
  578. # -----------------------------------------------------------------#
  579. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(10*1.2), cm2inch(3*1.2)))
  580. gb = sns.boxplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  581. data=mr_results, order=regions, hue_order=['focal',
  582. 'contra-lateral'],
  583. dodge=True, palette=['darkblue', 'slategray'], linewidth=1)
  584. gb.set_yscale("log")
  585. for patch in ax.artists:
  586. r, g, b, a = patch.get_facecolor()
  587. patch.set_facecolor((r, g, b, .4))
  588. patch.set_edgecolor('gray')
  589. sns.stripplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  590. data=mr_results, alpha=0.9, order=regions,
  591. hue_order=['focal', 'contra-lateral'], jitter=False,
  592. size=2, palette=['darkblue', 'slategray'], dodge=True)
  593. ax.get_legend().set_visible(False)
  594. plt.grid(axis='x', b=False)
  595. labels = []
  596. for ireg, reg in enumerate(regions):
  597. mr_results_r = mr_results[mr_results['region']==reg]
  598. n_reg_f = len(mr_results_r[mr_results_r['binning_focus']=='focal'][
  599. 'm'].tolist())
  600. n_reg_c = len(mr_results_r[mr_results_r[
  601. 'binning_focus']=='contra-lateral'][
  602. 'm'].tolist())
  603. labels.append('{}\n({}, {})'.format(reg, n_reg_f, n_reg_c))
  604. ax.set_xticklabels(labels)
  605. quantity_label = r'$\hat{m}$'
  606. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  607. ymax = 0.4 * np.min(mr_results[quantity].tolist())
  608. ax.set_ylim(ymin, ymax)
  609. T = [1, 1e-1, 1e-2, 1e-3]
  610. ax.set_yticks(T)
  611. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  612. plt.ylabel(quantity_label)
  613. sns.despine()
  614. # -----------------------------------------------------------------#
  615. # Annotate p-values of pairwise comparison
  616. # -----------------------------------------------------------------#
  617. y_max = 1.3*ymax
  618. y_min = ymin
  619. for ir, region in enumerate(regions):
  620. ax.annotate("", xy=(-0.2+ir*1.0, 1.5*y_max), xycoords='data',
  621. xytext=(0.2+ir*1.0, 1.5*y_max), textcoords='data',
  622. arrowprops=dict(arrowstyle="-", ec='black',
  623. connectionstyle="bar,fraction=0.3"))
  624. ax.text(-0.35+ir*1.0, y_max* 0.9- abs(y_max - y_min) * 0.0,
  625. 'p'+'={:.3f}'.format(pvals[region]), fontsize=8.5)
  626. # -----------------------------------------------------------------#
  627. # Adjust some plot settings and save figures
  628. # -----------------------------------------------------------------#
  629. ax.set_xlabel('brain area')
  630. ax.set_ylim((ymin, ymax))
  631. ax.set_title('overall model: ' + str(global_pvals), fontsize=4)
  632. fig.subplots_adjust(bottom=None, right=None,
  633. wspace=0.2, hspace=0.5, left=0.15, top=1.2)
  634. kmin = mr_results['kmin'].unique()[0]
  635. kmax = mr_results['kmax'].unique()[0]
  636. plotfile_mx = '{}Fig1_regions_{}_kmin{}_kmax{}_exclude_{}.pdf'.format(
  637. result_path, quantity, kmin, kmax, excludeInconsistencies)
  638. fig.savefig(plotfile_mx, bbox_inches='tight')
  639. plt.show()
  640. plt.close('all')
  641. def boxplot_brainregions_focus_Engel(pkl_file_pre,pkl_file_inter,result_path,
  642. excludeInconsistencies, **kwargs):
  643. regions = ['H', 'A', 'PHC', 'EC']
  644. mr_results_pre = pd.read_pickle(pkl_file_pre)
  645. mr_results_inter = pd.read_pickle(pkl_file_inter)
  646. mr_results = pd.concat([mr_results_pre, mr_results_inter],
  647. ignore_index=True)
  648. patients1a = [1, 6, 8, 9, 10, 11, 16, 17, 18, 19]
  649. mr_results = mr_results[(mr_results['patient'].isin(patients1a))]
  650. mr_results = mr_results[(mr_results['fit_method'] == 'offset')]
  651. conditions = list()
  652. for key in kwargs.keys():
  653. conditions.append(mr_results[key] == kwargs[key])
  654. if len(conditions) > 0:
  655. mr_results = mr_results[mr_utilities.conjunction(*conditions)]
  656. if excludeInconsistencies:
  657. rejected_inconsistencies = ['H_nonzero', 'H_linear']
  658. for incon in rejected_inconsistencies:
  659. mr_results = mr_results[[incon not in mr_results[
  660. 'inconsistencies'].tolist()[i] for i in range(
  661. len(mr_results['inconsistencies'].tolist()))]]
  662. # -----------------------------------------------------------------#
  663. # Write the brainregion, independent of hemisphere, into frame
  664. # -----------------------------------------------------------------#
  665. def give_region(row):
  666. return row['binning'][1:]
  667. # -----------------------------------------------------------------#
  668. # Write the brainregion and focus into frame
  669. # -----------------------------------------------------------------#
  670. def give_region_and_focus(row):
  671. regionname = row['binning'][1:]
  672. focus = row['binning_focus'][0] # f for focal and c for contralateral
  673. return '{}{}'.format(focus, regionname)
  674. mr_results['region'] = mr_results.apply(lambda row: give_region(row), axis=1)
  675. mr_results['regionfocus'] = mr_results.apply(lambda row: give_region_and_focus(row), axis=1)
  676. mr_results['logtau'] = mr_results.apply(lambda row: np.log(row['tau']),axis=1)
  677. mr_results['logepsilon'] = mr_results.apply(lambda row: abs(np.log(1-row['m'])), axis=1)
  678. mr_results['epsilon'] = mr_results.apply(lambda row: 1-row['m'], axis=1)
  679. quantity = 'epsilon'
  680. # -----------------------------------------------------------------#
  681. # Compute p-values of pairwise comparison
  682. # -----------------------------------------------------------------#
  683. pvals = dict()
  684. medians = dict()
  685. for area in mr_results['region'].unique():
  686. area_frame = mr_results[mr_results['region'] == area]
  687. f_area_frame = area_frame[area_frame['binning_focus'] == 'focal']
  688. c_area_frame = area_frame[area_frame['binning_focus'] ==
  689. 'contra-lateral']
  690. focalval = f_area_frame[quantity].tolist()
  691. contraval = c_area_frame[quantity].tolist()
  692. stat, p = stats.mannwhitneyu(focalval, contraval,
  693. alternative='two-sided')
  694. pvals[area] = p
  695. medians['f{}'.format(area)] = np.median(focalval)
  696. medians['c{}'.format(area)] = np.median(contraval)
  697. global_pvals, pvals_regions = hierarchical_model.hierarchical_model_regions(
  698. mr_results)
  699. pvals = pvals_regions
  700. # -----------------------------------------------------------------#
  701. # Boxplot of regions
  702. # -----------------------------------------------------------------#
  703. fig, ax = plt.subplots(1, 1, figsize=(cm2inch(10*1.2), cm2inch(3*1.2)))
  704. gb = sns.boxplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  705. data=mr_results, order=regions, hue_order=['focal',
  706. 'contra-lateral'],
  707. dodge=True, palette=['darkblue', 'slategray'], linewidth=1)
  708. for patch in ax.artists:
  709. r, g, b, a = patch.get_facecolor()
  710. patch.set_facecolor((r, g, b, .4))
  711. patch.set_edgecolor('gray')
  712. sns.stripplot(ax=ax, x="region", y=quantity, hue='binning_focus',
  713. data=mr_results, alpha=0.9, order=regions,
  714. hue_order=['focal', 'contra-lateral'], jitter=False,
  715. size=2, palette=['darkblue', 'slategray'], dodge=True)
  716. ax.get_legend().set_visible(False)
  717. plt.grid(axis='x', b=False)
  718. gb.set_yscale("log")
  719. labels = []
  720. for ireg, reg in enumerate(regions):
  721. mr_results_r = mr_results[mr_results['region']==reg]
  722. n_reg_f = len(mr_results_r[mr_results_r['binning_focus']=='focal'][
  723. 'm'].tolist())
  724. n_reg_c = len(mr_results_r[mr_results_r['binning_focus']==
  725. 'contra-lateral']['m'].tolist())
  726. labels.append('{}\n({}, {})'.format(reg, n_reg_f, n_reg_c))
  727. ax.set_xticklabels(labels)
  728. quantity_label = r'$\hat{m}$'
  729. ymin = 1.4 * np.max(mr_results[quantity].tolist())
  730. ymax = 0.4 * np.min(mr_results[quantity].tolist())
  731. ax.set_ylim(ymin, ymax)
  732. T = [1, 1e-1, 1e-2, 1e-3]
  733. ax.set_yticks(T)
  734. ax.set_yticklabels([0, 0.9, 0.99, 0.999])
  735. plt.ylabel(quantity_label)
  736. sns.despine()
  737. # -----------------------------------------------------------------#
  738. # Annotate p-values of pairwise comparison
  739. # -----------------------------------------------------------------#
  740. y_max = 0.85*ymax
  741. if quantity == 'epsilon':
  742. y_max = 1.3*ymax
  743. y_min = ymin
  744. for ir, region in enumerate(regions):
  745. ax.annotate("", xy=(-0.2+ir*1.0, 1.5*y_max), xycoords='data',
  746. xytext=(0.2+ir*1.0, 1.5*y_max), textcoords='data',
  747. arrowprops=dict(arrowstyle="-", ec='black',
  748. connectionstyle="bar,fraction=0.3"))
  749. ax.text(-0.35+ir*1.0, y_max* 0.9- abs(y_max - y_min) * 0.0,
  750. 'p'+'={:.3f}'.format(pvals[region]), fontsize=8.5)
  751. # -----------------------------------------------------------------#
  752. # Adjust some plot settings and save figures
  753. # -----------------------------------------------------------------#
  754. ax.set_xlabel('brain area')
  755. ax.set_ylim((ymin, ymax))
  756. ax.set_title('overall model: ' + str(global_pvals), fontsize=4)
  757. fig.subplots_adjust(bottom=None, right=None,
  758. wspace=0.2, hspace=0.5, left=0.15, top=1.2)
  759. kmin = mr_results['kmin'].unique()[0]
  760. kmax = mr_results['kmax'].unique()[0]
  761. plotfile_mx = '{}Fig1_regions_{}_kmin{}_kmax{}_exclude_{}_Engel1a.pdf'.format(
  762. result_path, quantity, kmin, kmax, excludeInconsistencies)
  763. fig.savefig(plotfile_mx, bbox_inches='tight')
  764. plt.show()
  765. plt.close('all')
  766. def boxplot_hemispheres():
  767. result_path = '../Results/preictal/singleunits/'
  768. pkl_file = result_path + 'mr_results.pkl'
  769. ksteps = (1, 400)
  770. pkl_file_pre = pkl_file
  771. result_path_inter = '../Results/interictal/singleunits/'
  772. pkl_file_inter = result_path_inter + 'mr_results.pkl'
  773. boxplot_focal_contra(pkl_file_pre, pkl_file_inter,
  774. result_path, excludeInconsistencies=True,
  775. kmin=ksteps[0], kmax=ksteps[1])
  776. boxplot_focal_contra_Engel(pkl_file_pre, pkl_file_inter,
  777. result_path, excludeInconsistencies=True,
  778. kmin=ksteps[0], kmax=ksteps[1])
  779. boxplot_focal_contra_onlypaired(pkl_file_pre, pkl_file_inter,
  780. result_path, excludeInconsistencies=True,
  781. kmin=ksteps[0], kmax=ksteps[1])
  782. def pointplot_patients_hemispheres():
  783. pkl_file_pre = '../Results/preictal/singleunits/mr_results.pkl'
  784. pkl_file_inter = '../Results/interictal/singleunits/mr_results.pkl'
  785. result_path_pointplot = '../Results/preictal/singleunits/'
  786. patientwise_pointplots(pkl_file_pre, pkl_file_inter,
  787. result_path_pointplot,
  788. excludeInconsistencies=True,
  789. kmin=1, kmax=400,
  790. fit_method='offset')
  791. def boxplot_regions():
  792. result_path = '../Results/preictal/singleunits_regions/'
  793. pkl_file = result_path + 'mr_results.pkl'
  794. result_path_inter = '../Results/interictal/singleunits_regions/'
  795. pkl_file_inter = result_path_inter + 'mr_results.pkl'
  796. ksteps = (1, 400)
  797. boxplot_brainregions_focus(pkl_file, pkl_file_inter,
  798. result_path,
  799. kmin=ksteps[0],
  800. kmax=ksteps[1],
  801. excludeInconsistencies=True,
  802. fit_method='offset')
  803. boxplot_brainregions_focus_Engel(pkl_file, pkl_file_inter,
  804. result_path,
  805. kmin=ksteps[0],
  806. kmax=ksteps[1],
  807. excludeInconsistencies=True,
  808. fit_method='offset')
  809. boxplot_brainregions_focus_onlypaired(pkl_file,
  810. pkl_file_inter,
  811. result_path,
  812. kmin=ksteps[0],
  813. kmax=ksteps[1],
  814. excludeInconsistencies=True,
  815. fit_method='offset')
  816. def main():
  817. boxplot_hemispheres()
  818. pointplot_patients_hemispheres()
  819. boxplot_regions()
  820. if __name__ == '__main__':
  821. main()