plot_scaled_up_perlin.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import pandas as pd
  4. from brian2.units import *
  5. from matplotlib import gridspec
  6. from mpl_toolkits.axes_grid1 import make_axes_locatable
  7. from pypet import Trajectory
  8. from pypet.brian2 import Brian2MonitorResult
  9. from scipy.optimize import curve_fit
  10. from matplotlib.patches import Ellipse
  11. from matplotlib.patches import Polygon
  12. import matplotlib.legend as mlegend
  13. from matplotlib.patches import Rectangle
  14. from scripts.interneuron_placement import get_position_mesh, Pickle, get_correct_position_mesh, get_interneuron_entropy
  15. from scripts.spatial_network.figures_spatial_head_direction_network_orientation_map import plot_hdi_in_space
  16. from scripts.spatial_network.edge_effects_orientation_map.run_scaled_up_perlin import DATA_FOLDER, TRAJ_NAME
  17. FIGURE_SAVE_PATH = '../../../figures/scaled_up_perlin/'
  18. save_figs = False
  19. def get_closest_correlation_length(traj, correlation_length):
  20. available_lengths = sorted(list(set(traj.f_get("correlation_length").f_get_range())))
  21. closest_length = available_lengths[np.argmin(np.abs(np.array(available_lengths) - correlation_length))]
  22. if closest_length != correlation_length:
  23. print("Warning: desired correlation length {:.1f} not available. Taking {:.1f} instead".format(
  24. correlation_length, closest_length))
  25. corr_len = closest_length
  26. return corr_len
  27. def colorbar(mappable):
  28. from mpl_toolkits.axes_grid1 import make_axes_locatable
  29. import matplotlib.pyplot as plt
  30. last_axes = plt.gca()
  31. ax = mappable.axes
  32. fig = ax.figure
  33. divider = make_axes_locatable(ax)
  34. cax = divider.append_axes("right", size="5%", pad=0.05)
  35. cbar = fig.colorbar(mappable, cax=cax)
  36. plt.sca(last_axes)
  37. return cbar
  38. def plot_firing_rate_map_excitatory(traj, direction_idx, plot_run_names):
  39. max_val = 0
  40. for run_name in plot_run_names:
  41. fr_array = traj.results.runs[run_name].firing_rate_array
  42. f_rates = fr_array[:, direction_idx]
  43. run_max_val = np.max(f_rates)
  44. if run_max_val > max_val:
  45. # if traj.derived_parameters.runs[run_name].morphology.morph_label == 'ellipsoid':
  46. # n_id_max_rate = np.argmax(f_rates)
  47. max_val = run_max_val
  48. n_id_polar_plot = 5
  49. # Mark the neuron that is shown in Polar plot
  50. ex_positions = traj.results.runs[plot_run_names[0]].ex_positions
  51. polar_plot_x, polar_plot_y = ex_positions[n_id_polar_plot]
  52. # Vertices for the plotted triangle
  53. tr_scale = 13.
  54. tr_x = tr_scale * np.cos(2. * np.pi / 3. + np.pi / 2.)
  55. tr_y = tr_scale * np.sin(2. * np.pi / 3. + np.pi / 2.) + polar_plot_y
  56. tr_vertices = np.array(
  57. [[polar_plot_x, polar_plot_y + tr_scale], [tr_x + polar_plot_x, tr_y], [-tr_x + polar_plot_x, tr_y]])
  58. height = 3.5
  59. # color_bar_size = 0.05 * height + 0.05
  60. # width = 3 * height + color_bar_size
  61. width = 10.5
  62. fig, axes = plt.subplots(1, 3, figsize=(width, height))
  63. for ax, run_name in zip(axes, [plot_run_names[i] for i in [2, 0, 1]]):
  64. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  65. X, Y = get_correct_position_mesh(traj.results.runs[run_name].ex_positions)
  66. firing_rate_array = traj.results[run_name].firing_rate_array
  67. number_of_excitatory_neurons_per_row = int(np.sqrt(traj.N_E))
  68. c = ax.pcolor(X, Y, np.reshape(firing_rate_array[:, direction_idx], (number_of_excitatory_neurons_per_row,
  69. number_of_excitatory_neurons_per_row)),
  70. vmin=0, vmax=max_val, cmap='Reds')
  71. ax.set_title(label)
  72. # ax.add_artist(Ellipse((polar_plot_x, polar_plot_y), 20., 20., color='k', fill=False, lw=2.))
  73. # ax.add_artist(Ellipse((polar_plot_x, polar_plot_y), 20., 20., color='w', fill=False, lw=1.))
  74. ax.add_artist(Polygon(tr_vertices, closed=True, fill=False, lw=2.5, color='k'))
  75. ax.add_artist(Polygon(tr_vertices, closed=True, fill=False, lw=1.5, color='w'))
  76. # fig.suptitle('spatial firing rate map', fontsize=16)
  77. colorbar(c)
  78. fig.tight_layout()
  79. if save_figs:
  80. plt.savefig(FIGURE_SAVE_PATH + 'firing_rate_map.png', dpi=200)
  81. return n_id_polar_plot
  82. def plot_averaged_firing_rate_map_excitatory(traj, plot_run_names):
  83. max_val = 0
  84. for run_name in plot_run_names:
  85. fr_array = traj.results.runs[run_name].firing_rate_array
  86. f_rates = np.mean(fr_array, axis=1)
  87. run_max_val = np.max(f_rates)
  88. if run_max_val > max_val:
  89. # if traj.derived_parameters.runs[run_name].morphology.morph_label == 'ellipsoid':
  90. # n_id_max_rate = np.argmax(f_rates)
  91. max_val = run_max_val
  92. # Mark the neuron that is shown in Polar plot
  93. ex_positions = traj.results.runs[plot_run_names[0]].ex_positions
  94. height = 3.5
  95. # color_bar_size = 0.05 * height + 0.05
  96. # width = 3 * height + color_bar_size
  97. width = 10.5
  98. fig, axes = plt.subplots(1, 3, figsize=(width, height))
  99. for ax, run_name in zip(axes, [plot_run_names[i] for i in [2, 0, 1]]):
  100. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  101. X, Y = get_correct_position_mesh(traj.results.runs[run_name].ex_positions)
  102. firing_rate_array = traj.results[run_name].firing_rate_array
  103. averaged_firing_rate_array = np.mean(firing_rate_array, axis=1)
  104. number_of_excitatory_neurons_per_row = int(np.sqrt(traj.N_E))
  105. c = ax.pcolor(X, Y, np.reshape(averaged_firing_rate_array, (number_of_excitatory_neurons_per_row,
  106. number_of_excitatory_neurons_per_row)),
  107. vmin=0, vmax=max_val, cmap='Reds')
  108. ax.set_title(label)
  109. fig.suptitle('averaged firing rate map', fontsize=16)
  110. colorbar(c)
  111. fig.tight_layout()
  112. if save_figs:
  113. plt.savefig(FIGURE_SAVE_PATH + 'averaged_firing_rate_map.png', dpi=200)
  114. def plot_firing_rate_map_inhibitory(traj, direction_idx, plot_run_names):
  115. max_val = 0
  116. for run_name in plot_run_names:
  117. fr_array = traj.results.runs[run_name].inh_firing_rate_array
  118. f_rates = fr_array[:, direction_idx]
  119. run_max_val = np.max(f_rates)
  120. if run_max_val > max_val:
  121. max_val = run_max_val
  122. n_id_polar_plot = 4
  123. # Mark the neuron that is shown in Polar plot
  124. inhibitory_axonal_cloud_array = traj.results.runs[plot_run_names[1]].inhibitory_axonal_cloud_array
  125. polar_plot_x = inhibitory_axonal_cloud_array[n_id_polar_plot, 0]
  126. polar_plot_y = inhibitory_axonal_cloud_array[n_id_polar_plot, 1]
  127. fig, axes = plt.subplots(1, 2, figsize=(7.0, 3.5))
  128. for ax, run_name in zip(axes, [plot_run_names[i] for i in [0, 1]]):
  129. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  130. inhibitory_axonal_cloud_array = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  131. inh_positions = [[p[0], p[1]] for p in inhibitory_axonal_cloud_array]
  132. X, Y = get_correct_position_mesh(inh_positions)
  133. inh_firing_rate_array = traj.results[run_name].inh_firing_rate_array
  134. number_of_inhibitory_neurons_per_row = int(np.sqrt(traj.N_I))
  135. c = ax.pcolor(X, Y, np.reshape(inh_firing_rate_array[:, direction_idx], (number_of_inhibitory_neurons_per_row,
  136. number_of_inhibitory_neurons_per_row)),
  137. vmin=0, vmax=max_val, cmap='Blues')
  138. ax.set_title(label)
  139. circle_r = 40.
  140. ax.add_artist(Ellipse((polar_plot_x, polar_plot_y), circle_r, circle_r, color='k', fill=False, lw=4.5))
  141. ax.add_artist(Ellipse((polar_plot_x, polar_plot_y), circle_r, circle_r, color='w', fill=False, lw=3))
  142. # fig.colorbar(c, ax=ax, label="f (Hz)")
  143. # fig.suptitle('spatial firing rate map', fontsize=16)
  144. colorbar(c)
  145. fig.tight_layout()
  146. if save_figs:
  147. plt.savefig(FIGURE_SAVE_PATH + 'inh_firing_rate_map.png', dpi=200)
  148. return n_id_polar_plot, max_val
  149. def plot_hdi_over_tuning(traj, plot_run_names):
  150. fig, ax = plt.subplots(1, 1)
  151. for run_idx, run_name in enumerate(plot_run_names):
  152. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  153. ex_tunings = traj.results.runs[run_name].ex_tunings
  154. ex_tunings_plt = np.array(ex_tunings)
  155. sort_ids = ex_tunings_plt.argsort()
  156. ex_tunings_plt = ex_tunings_plt[sort_ids]
  157. head_direction_indices = traj.results[run_name].head_direction_indices
  158. hdi_plt = head_direction_indices
  159. hdi_plt = hdi_plt[sort_ids]
  160. ax.scatter(ex_tunings_plt, hdi_plt, label=label, alpha=0.3)
  161. ax.legend()
  162. ax.set_xlabel("Angles (rad)")
  163. ax.set_ylabel("head direction index")
  164. ax.set_title('hdi over input tuning', fontsize=16)
  165. if save_figs:
  166. plt.savefig(FIGURE_SAVE_PATH + 'hdi_over_tuning.png', dpi=200)
  167. def plot_axonal_clouds(traj, plot_run_names):
  168. n_ex = int(np.sqrt(traj.N_E))
  169. fig, axes = plt.subplots(1, 3, figsize=(10.5, 3.5))
  170. for ax, run_name in zip(axes, [plot_run_names[i] for i in [2, 0, 1]]):
  171. traj.f_set_crun(run_name)
  172. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  173. X, Y = get_correct_position_mesh(traj.results.runs[run_name].ex_positions)
  174. inhibitory_axonal_cloud_array = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  175. axonal_clouds = [Pickle(p[0], p[1], traj.morphology.long_axis, traj.morphology.short_axis, p[2]) for p in
  176. inhibitory_axonal_cloud_array]
  177. head_dir_preference = np.array(traj.results.runs[run_name].ex_tunings).reshape((n_ex, n_ex))
  178. # TODO: Why was this transposed for plotting? (now changed)
  179. c = ax.pcolor(X, Y, head_dir_preference, vmin=-np.pi, vmax=np.pi, cmap='hsv')
  180. ax.set_title(label)
  181. # fig.colorbar(c, ax=ax, label="Tuning")
  182. if label != 'no conn' and axonal_clouds is not None:
  183. for i, p in enumerate(axonal_clouds):
  184. ell = p.get_ellipse()
  185. ax.add_artist(ell)
  186. # fig.suptitle('axonal cloud', fontsize=16)
  187. traj.f_restore_default()
  188. fig.tight_layout()
  189. if save_figs:
  190. plt.savefig(FIGURE_SAVE_PATH + 'axonal_clouds.png', dpi=200)
  191. def plot_orientation_maps_diff_scales(traj):
  192. n_ex = int(np.sqrt(traj.N_E))
  193. scale_run_names = []
  194. plot_scales = [0.0, 100.0, 200.0, 300.0]
  195. for scale in plot_scales:
  196. par_dict = {'seed': 1, 'correlation_length': get_closest_correlation_length(traj, scale), 'long_axis': 100.}
  197. scale_run_names.append(*filter_run_names_by_par_dict(traj, par_dict))
  198. fig, axes = plt.subplots(1, 4, figsize=(18., 4.5))
  199. for ax, run_name, scale in zip(axes, scale_run_names, plot_scales):
  200. traj.f_set_crun(run_name)
  201. X, Y = get_position_mesh(traj.results.runs[run_name].ex_positions)
  202. head_dir_preference = np.array(traj.results.runs[run_name].ex_tunings).reshape((n_ex, n_ex))
  203. # TODO: Why was this transposed for plotting? (now changed)
  204. c = ax.pcolor(X, Y, head_dir_preference, vmin=-np.pi, vmax=np.pi, cmap='twilight')
  205. ax.set_title('Correlation length: {}'.format(scale))
  206. fig.colorbar(c, ax=ax, label="Tuning")
  207. # fig.suptitle('axonal cloud', fontsize=16)
  208. traj.f_restore_default()
  209. if save_figs:
  210. plt.savefig(FIGURE_SAVE_PATH + 'orientation_maps_diff_scales.png', dpi=200)
  211. def plot_orientation_maps_diff_scales_with_ellipse(traj):
  212. n_ex = int(np.sqrt(traj.N_E))
  213. scale_run_names = []
  214. plot_scales = [0.0, 100.0, 200.0, 300.0, 400.0]
  215. for scale in plot_scales:
  216. par_dict = {'seed': 1, 'correlation_length': get_closest_correlation_length(traj, scale), 'long_axis': 100.}
  217. scale_run_names.append(*filter_run_names_by_par_dict(traj, par_dict))
  218. print(scale_run_names)
  219. fig, axes = plt.subplots(1, 5, figsize=(18., 4.5))
  220. for ax, run_name, scale in zip(axes, scale_run_names, plot_scales):
  221. traj.f_set_crun(run_name)
  222. X, Y = get_position_mesh(traj.results.runs[run_name].ex_positions)
  223. inhibitory_axonal_cloud_array = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  224. axonal_clouds = [Pickle(p[0], p[1], traj.morphology.long_axis, traj.morphology.short_axis, p[2]) for p in
  225. inhibitory_axonal_cloud_array]
  226. head_dir_preference = np.array(traj.results.runs[run_name].ex_tunings).reshape((n_ex, n_ex))
  227. # TODO: Why was this transposed for plotting? (now changed)
  228. c = ax.pcolor(X, Y, head_dir_preference, vmin=-np.pi, vmax=np.pi, cmap='hsv')
  229. # ax.set_title('Correlation length: {}'.format(scale))
  230. # fig.colorbar(c, ax=ax, label="Tuning")
  231. ax.set_xticks([])
  232. ax.set_yticks([])
  233. p1 = axonal_clouds[44]
  234. ell = p1.get_ellipse()
  235. ell._linewidth = 5.
  236. ax.add_artist(ell)
  237. p2 = axonal_clouds[77]
  238. circ_r = 2 * np.sqrt(2500.)
  239. circ = Ellipse((p2.x, p2.y), circ_r, circ_r, fill=False, zorder=2, edgecolor='k')
  240. circ._linewidth = 5.
  241. ax.add_artist(circ)
  242. # fig.suptitle('axonal cloud', fontsize=16)
  243. traj.f_restore_default()
  244. fig.tight_layout()
  245. if save_figs:
  246. plt.savefig(FIGURE_SAVE_PATH + 'orientation_maps_diff_scales_with_ellipse.png', dpi=200)
  247. def plot_excitatory_condensed_polar_plot(traj, plot_run_names, polar_plot_id, ex_polar_plot_hdi):
  248. directions = np.linspace(-np.pi, np.pi, traj.input.number_of_directions, endpoint=False)
  249. directions_plt = list(directions)
  250. directions_plt.append(directions[0])
  251. fig, ax = plt.subplots(1, 1, figsize=(3.5, 3.5), subplot_kw=dict(projection='polar'))
  252. # head_direction_indices = traj.results.runs[plot_run_names[0]].head_direction_indices
  253. # sorted_ids = np.argsort(head_direction_indices)
  254. # plot_n_idx = sorted_ids[-75]
  255. plot_n_idx = polar_plot_id
  256. line_styles = ['dotted', 'solid', 'dashed']
  257. colors = ['r', 'lightsalmon', 'grey']
  258. max_rate = 0.0
  259. for run_idx, run_name in enumerate(plot_run_names):
  260. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  261. tuning_vectors = traj.results.runs[run_name].tuning_vectors
  262. rate_plot = [np.linalg.norm(v) for v in tuning_vectors[plot_n_idx]]
  263. run_max_rate = np.max(rate_plot)
  264. if run_max_rate > max_rate:
  265. max_rate = run_max_rate
  266. rate_plot.append(rate_plot[0])
  267. ax.plot(directions_plt, rate_plot, label='{0}, HDI: {1:.2f}'.format(label, ex_polar_plot_hdi[run_idx]),
  268. color=colors[run_idx], linestyle=line_styles[run_idx])
  269. # ax.set_title('Firing Rate')
  270. ax.plot([0.0, 0.0], [0.0, 1.05 * max_rate], color='red', alpha=0.25, linewidth=4.)
  271. # TODO: Set ticks for polar
  272. ticks = [30., 60., 90.]
  273. ax.set_rticks(ticks)
  274. ax.set_rlabel_position(230)
  275. ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15),
  276. fancybox=True, shadow=True)
  277. plt.tight_layout()
  278. if save_figs:
  279. plt.savefig(FIGURE_SAVE_PATH + 'condensed_polar_plot.png', dpi=200)
  280. def plot_inhibitory_condensed_polar_plot(traj, plot_run_names, polar_plot_id, in_polar_plot_hdi):
  281. directions = np.linspace(-np.pi, np.pi, traj.input.number_of_directions, endpoint=False)
  282. directions_plt = list(directions)
  283. directions_plt.append(directions[0])
  284. fig, ax = plt.subplots(1, 1, figsize=(3.5, 3.5), subplot_kw=dict(projection='polar'))
  285. # head_direction_indices = traj.results.runs[plot_run_names[0]].inh_head_direction_indices
  286. # sorted_ids = np.argsort(head_direction_indices)
  287. # plot_n_idx = sorted_ids[-75]
  288. plot_n_idx = polar_plot_id
  289. line_styles = ['dotted', 'solid']
  290. colors = ['b', 'lightblue']
  291. for run_idx, run_name in enumerate(plot_run_names[:2]):
  292. # ax = axes[max_hdi_idx, run_idx]
  293. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  294. tuning_vectors = traj.results.runs[run_name].inh_tuning_vectors
  295. rate_plot = [np.linalg.norm(v) for v in tuning_vectors[plot_n_idx]]
  296. rate_plot.append(rate_plot[0])
  297. ax.plot(directions_plt, rate_plot, label='{0}, HDI: {1:.2f}'.format(label, in_polar_plot_hdi[run_idx]),
  298. color=colors[run_idx], linestyle=line_styles[run_idx])
  299. # ax.set_title('Inh. Firing Rate')
  300. # TODO: Set ticks for polar
  301. # ticks = [np.round(max_rate / 3.), np.round(max_rate * 2. / 3.), np.round(max_rate)]
  302. ticks = [40., 80., 120.]
  303. ax.set_rticks(ticks)
  304. ax.set_rlabel_position(230)
  305. ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15),
  306. fancybox=True, shadow=True)
  307. plt.tight_layout()
  308. if save_figs:
  309. plt.savefig(FIGURE_SAVE_PATH + 'condensed_inhibitory_polar_plot.png', dpi=200)
  310. def plot_hdi_over_corr_len(traj, plot_run_names):
  311. corr_len_expl = traj.f_get('correlation_length').f_get_range()
  312. seed_expl = traj.f_get('seed').f_get_range()
  313. label_expl = [traj.derived_parameters.runs[run_name].morphology.morph_label for run_name in traj.f_get_run_names()]
  314. label_range = set(label_expl)
  315. hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  316. hdi_frame.index.names = ["corr_len", "seed", "label"]
  317. for run_name, corr_len, seed, label in zip(plot_run_names, corr_len_expl, seed_expl, label_expl):
  318. ex_tunings = traj.results.runs[run_name].ex_tunings
  319. head_direction_indices = traj.results[run_name].head_direction_indices
  320. hdi_frame[corr_len, seed, label] = np.mean(head_direction_indices)
  321. # TODO: Standart deviation also for the population
  322. hdi_exc_n_and_seed_mean = hdi_frame.groupby(level=[0, 2]).mean()
  323. hdi_exc_n_and_seed_std_dev = hdi_frame.groupby(level=[0, 2]).std()
  324. # Ellipsoid markers
  325. rx, ry = 5., 12.
  326. # area = rx * ry * np.pi * 2.
  327. area = 1.
  328. theta = np.arange(0, 2 * np.pi + 0.01, 0.1)
  329. verts = np.column_stack([rx / area * np.cos(theta), ry / area * np.sin(theta)])
  330. style_dict = {
  331. 'no conn': ['grey', 'dashed', '', 0],
  332. 'ellipsoid': ['blue', 'solid', verts, 10.],
  333. 'circular': ['lightblue', 'solid', 'o', 8.]
  334. }
  335. # colors = ['blue', 'grey', 'lightblue']
  336. # linestyles = ['solid', 'dashed', 'solid']
  337. # markers = [verts, '', 'o']
  338. fig, ax = plt.subplots(1, 1)
  339. for label in label_range:
  340. hdi_mean = hdi_exc_n_and_seed_mean[:, label]
  341. hdi_std = hdi_exc_n_and_seed_std_dev[:, label]
  342. corr_len_range = hdi_mean.keys().to_numpy()
  343. col, lin, mar, mar_size = style_dict[label]
  344. ax.plot(corr_len_range, hdi_mean, label=label, marker=mar, color=col, linestyle=lin, markersize=mar_size)
  345. plt.fill_between(corr_len_range, hdi_mean - hdi_std,
  346. hdi_mean + hdi_std, alpha=0.4, color=col)
  347. ax.set_xlabel('Correlation length')
  348. ax.set_ylabel('Head Direction Index')
  349. ax.axvline(206.9, color='k', linewidth=0.5)
  350. ax.set_ylim(0.0, 1.0)
  351. ax.set_xlim(0.0, 400.)
  352. ax.legend()
  353. if save_figs:
  354. plt.savefig(FIGURE_SAVE_PATH + 'hdi_over_corr_len_scaled.png', dpi=200)
  355. def plot_hdi_histogram_excitatory(traj, plot_run_names, ex_polar_plot_id):
  356. labels = []
  357. hdis = []
  358. colors = ['black', 'red', 'green']
  359. for run_idx, run_name in enumerate(plot_run_names):
  360. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  361. labels.append(label)
  362. head_direction_indices = traj.results.runs[run_name].head_direction_indices
  363. print('exc {}: {}'.format(label, head_direction_indices[ex_polar_plot_id]))
  364. hdis.append(head_direction_indices)
  365. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  366. ax.hist(hdis, color=colors, label=labels, bins=30)
  367. for hdi, color in zip(hdis, colors):
  368. mean_hdi = np.mean(hdi)
  369. ax.axvline(mean_hdi, 0, 1, color=color, linestyle='--')
  370. ax.set_xlabel("HDI")
  371. ax.legend()
  372. fig.tight_layout()
  373. if save_figs:
  374. plt.savefig(FIGURE_SAVE_PATH + 'hdi_histogram_excitatory.png', dpi=200)
  375. def plot_hdi_violin_excitatory(traj, plot_run_names):
  376. labels = []
  377. hdis = []
  378. colors = ['black', 'red', 'green']
  379. no_conn_hdi = 0.
  380. for run_idx, run_name in enumerate(plot_run_names):
  381. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  382. head_direction_indices = traj.results.runs[run_name].head_direction_indices
  383. if label == 'no conn':
  384. no_conn_hdi = np.mean(head_direction_indices)
  385. else:
  386. labels.append(label)
  387. hdis.append(sorted(head_direction_indices))
  388. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  389. # hdis = np.array(hdis)
  390. viol_plt = ax.violinplot(hdis, showmeans=True, showextrema=False)
  391. viol_plt['cmeans'].set_color('black')
  392. for pc in viol_plt['bodies']:
  393. pc.set_facecolor('red')
  394. pc.set_edgecolor('black')
  395. pc.set_alpha(0.7)
  396. ax.axhline(no_conn_hdi, color='black', linestyle='--')
  397. ax.annotate('no conn', xy=(0.45, 0.48), xycoords='axes fraction')
  398. ax.set_xticks(np.arange(1, len(labels) + 1))
  399. ax.set_xticklabels(labels)
  400. ax.set_ylabel('HDI')
  401. fig.tight_layout()
  402. if save_figs:
  403. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_excitatory.png', dpi=200)
  404. def plot_hdi_violin_inhibitory(traj, plot_run_names):
  405. labels = []
  406. hdis = []
  407. colors = ['black', 'red']
  408. for run_idx, run_name in enumerate(plot_run_names):
  409. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  410. if label != 'no conn':
  411. labels.append(label)
  412. head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  413. hdis.append(sorted(head_direction_indices))
  414. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  415. viol_plt = ax.violinplot(hdis, showmeans=True, showextrema=False)
  416. viol_plt['cmeans'].set_color('black')
  417. for pc in viol_plt['bodies']:
  418. pc.set_facecolor('blue')
  419. pc.set_edgecolor('black')
  420. pc.set_alpha(0.7)
  421. ax.set_xticks(np.arange(1, len(labels) + 1))
  422. ax.set_xticklabels(labels)
  423. ax.set_ylabel('HDI')
  424. fig.tight_layout()
  425. if save_figs:
  426. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_inhibitory.png', dpi=200)
  427. def plot_hdi_violin_combined(traj, plot_run_names):
  428. labels = []
  429. inh_hdis = []
  430. exc_hdis = []
  431. no_conn_hdi = 0.
  432. colors = ['black', 'red']
  433. for run_idx, run_name in enumerate(plot_run_names):
  434. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  435. if label != 'no conn':
  436. labels.append(label)
  437. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  438. inh_hdis.append(sorted(inh_head_direction_indices))
  439. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  440. exc_hdis.append(sorted(exc_head_direction_indices))
  441. else:
  442. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  443. no_conn_hdi = np.mean(exc_head_direction_indices)
  444. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  445. inh_viol_plt = ax.violinplot(inh_hdis, showmeans=True, showextrema=False)
  446. # viol_plt['cmeans'].set_color('black')
  447. #
  448. # for pc in viol_plt['bodies']:
  449. # pc.set_facecolor('blue')
  450. # pc.set_edgecolor('black')
  451. # pc.set_alpha(0.7)
  452. for b in inh_viol_plt['bodies']:
  453. m = np.mean(b.get_paths()[0].vertices[:, 0])
  454. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], m, np.inf)
  455. b.set_color('b')
  456. exc_viol_plt = ax.violinplot(exc_hdis, showmeans=True, showextrema=False)
  457. for b in exc_viol_plt['bodies']:
  458. m = np.mean(b.get_paths()[0].vertices[:, 0])
  459. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], -np.inf, m)
  460. b.set_color('r')
  461. ax.axhline(no_conn_hdi, color='black', linestyle='--')
  462. ax.annotate('no conn', xy=(0.45, 0.48), xycoords='axes fraction')
  463. ax.set_xticks(np.arange(1, len(labels) + 1))
  464. ax.set_xticklabels(labels)
  465. ax.set_ylabel('HDI')
  466. fig.tight_layout()
  467. if save_figs:
  468. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_combined.svg', dpi=200)
  469. def plot_hdi_violin_combined_and_overlayed(traj, plot_run_names, ex_polar_plot_id, in_polar_plot_id):
  470. labels = []
  471. inh_hdis = []
  472. exc_hdis = []
  473. no_conn_hdi = 0.
  474. in_polar_plot_hdi = []
  475. ex_polar_plot_hdi = []
  476. colors = ['black', 'red']
  477. for run_idx, run_name in enumerate(plot_run_names):
  478. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  479. if label != 'no conn':
  480. labels.append(label)
  481. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  482. inh_hdis.append(sorted(inh_head_direction_indices))
  483. in_polar_plot_hdi.append(inh_head_direction_indices[in_polar_plot_id])
  484. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  485. exc_hdis.append(sorted(exc_head_direction_indices))
  486. ex_polar_plot_hdi.append(exc_head_direction_indices[ex_polar_plot_id])
  487. else:
  488. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  489. no_conn_hdi = np.mean(exc_head_direction_indices)
  490. ex_polar_plot_hdi.append(exc_head_direction_indices[ex_polar_plot_id])
  491. fig, ax = plt.subplots(1, 1, figsize=(3.5, 4.5))
  492. inh_ell_viol_plt = ax.violinplot(inh_hdis[0], showmeans=True, showextrema=False)
  493. for b in inh_ell_viol_plt['bodies']:
  494. m = np.mean(b.get_paths()[0].vertices[:, 0])
  495. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], m, np.inf)
  496. b.set_color('b')
  497. mean_line = inh_ell_viol_plt['cmeans']
  498. mean_line.set_color('b')
  499. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], m, np.inf)
  500. exc_ell_viol_plt = ax.violinplot(exc_hdis[0], showmeans=True, showextrema=False)
  501. for b in exc_ell_viol_plt['bodies']:
  502. m = np.mean(b.get_paths()[0].vertices[:, 0])
  503. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], m, np.inf)
  504. b.set_color('r')
  505. mean_line = exc_ell_viol_plt['cmeans']
  506. mean_line.set_color('r')
  507. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], m, np.inf)
  508. inh_cir_viol_plt = ax.violinplot(inh_hdis[1], showmeans=True, showextrema=False)
  509. for b in inh_cir_viol_plt['bodies']:
  510. m = np.mean(b.get_paths()[0].vertices[:, 0])
  511. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], -np.inf, m)
  512. b.set_color('b')
  513. mean_line = inh_cir_viol_plt['cmeans']
  514. mean_line.set_color('b')
  515. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], -np.inf, m)
  516. exc_cir_viol_plt = ax.violinplot(exc_hdis[1], showmeans=True, showextrema=False)
  517. for b in exc_cir_viol_plt['bodies']:
  518. m = np.mean(b.get_paths()[0].vertices[:, 0])
  519. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], -np.inf, m)
  520. b.set_color('r')
  521. mean_line = exc_cir_viol_plt['cmeans']
  522. mean_line.set_color('r')
  523. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], -np.inf, m)
  524. ax.axhline(no_conn_hdi, 0.5, 1., color='black', linestyle='--')
  525. ax.axvline(1.0, color='k')
  526. ax.annotate('no conn', xy=(0.75, 0.415), xycoords='axes fraction')
  527. ax.set_xlim(0.5, 1.5)
  528. ax.set_ylim(0.0, 1.0)
  529. ax.set_xticks([0.75, 1.25])
  530. ax.set_xticklabels(['circular', 'ellipsoid'])
  531. ax.set_ylabel('HDI')
  532. fig.tight_layout()
  533. if save_figs:
  534. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_combined_and_overlayed.svg', dpi=200)
  535. return ex_polar_plot_hdi, in_polar_plot_hdi
  536. def plot_hdi_histogram_combined_and_overlayed(traj, plot_run_names, ex_polar_plot_id, in_polar_plot_id, cut_off_dist):
  537. labels = []
  538. inh_hdis = []
  539. exc_hdis = []
  540. no_conn_hdi = 0.
  541. in_polar_plot_hdi = []
  542. ex_polar_plot_hdi = []
  543. colors = ['black', 'red']
  544. for run_idx, run_name in enumerate(plot_run_names):
  545. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  546. if label != 'no conn':
  547. labels.append(label)
  548. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  549. inh_axonal_cloud = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  550. inh_cut_off_ids = (inh_axonal_cloud[:, 0] >= cut_off_dist) & \
  551. (inh_axonal_cloud[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  552. (inh_axonal_cloud[:, 1] >= cut_off_dist) & \
  553. (inh_axonal_cloud[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  554. # print(inh_positions)
  555. inh_hdis.append(sorted(inh_head_direction_indices[inh_cut_off_ids]))
  556. in_polar_plot_hdi.append(inh_head_direction_indices[in_polar_plot_id])
  557. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  558. ex_positions = traj.results.runs[run_name].ex_positions
  559. # print(ex_positions)
  560. exc_cut_off_ids = (ex_positions[:, 0] >= cut_off_dist) & \
  561. (ex_positions[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  562. (ex_positions[:, 1] >= cut_off_dist) & \
  563. (ex_positions[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  564. exc_hdis.append(sorted(exc_head_direction_indices[exc_cut_off_ids]))
  565. ex_polar_plot_hdi.append(exc_head_direction_indices[ex_polar_plot_id])
  566. else:
  567. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  568. no_conn_hdi = np.mean(exc_head_direction_indices)
  569. ex_polar_plot_hdi.append(exc_head_direction_indices[ex_polar_plot_id])
  570. # # fig = plt.figure(figsize=(3.5, 3.5))
  571. # # gs1 = gridspec.GridSpec(1, 2)
  572. #
  573. # fig = plt.figure(constrained_layout=True)
  574. # gs = gridspec.GridSpec(ncols=1, nrows=2, hspace=0.0, wspace=0.0, figure=fig)
  575. # # gs.update(wspace=0.0, hspace=0.0) # set the spacing between axes.
  576. # # f2_ax1 = fig.add_subplot(gs[0, 0])
  577. # # f2_ax2 = fig.add_subplot(gs[0, 1])
  578. # print(gs.get_subplot_params())
  579. fig, axes = plt.subplots(2, 1, figsize=(3.5, 2.5))
  580. plt.subplots_adjust(wspace=0, hspace=0)
  581. bins = np.linspace(0.0, 1.0, 21, endpoint=True)
  582. for i in range(2):
  583. # i = i + 1 # grid spec indexes from 0
  584. # ax = fig.add_subplot(gs[i])
  585. ax = axes[i]
  586. ax.hist(exc_hdis[i], color='r', edgecolor='r', alpha=0.3, bins=bins, density=True)
  587. ax.hist(inh_hdis[i], color='b', edgecolor='b', alpha=0.3, bins=bins, density=True)
  588. ax.axvline(np.mean(exc_hdis[i]), color='r')
  589. ax.axvline(np.mean(inh_hdis[i]), color='b')
  590. ax.axvline(no_conn_hdi, color='dimgrey', linestyle='--', linewidth=2.5)
  591. ax.set_ylabel(labels[i], rotation='vertical')
  592. # plt.axis('on')
  593. if i == 0:
  594. ax.set_xticklabels([])
  595. ax.spines['top'].set_visible(False)
  596. else:
  597. ax.set_xlabel('head direction index')
  598. ax.spines['right'].set_visible(False)
  599. plt.gcf().subplots_adjust(bottom=0.15)
  600. plt.gcf().subplots_adjust(left=0.15)
  601. plt.annotate('density', (-0.2,1.15), xycoords='axes fraction', rotation=90, fontsize=18)
  602. # plt.annotate('probability density', (-0.2,1.5), xycoords='axes fraction', rotation=90, fontsize=18)
  603. # fig.tight_layout()
  604. if save_figs:
  605. plt.savefig(FIGURE_SAVE_PATH + 'hdi_histogram_combined_and_overlayed_{}.png'.format(cut_off_dist), dpi=200)
  606. return ex_polar_plot_hdi, in_polar_plot_hdi
  607. def plot_hdi_histogram_inhibitory(traj, plot_run_names, in_polar_plot_id):
  608. labels = []
  609. hdis = []
  610. colors = ['black', 'red']
  611. for run_idx, run_name in enumerate(plot_run_names):
  612. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  613. if label != 'no conn':
  614. labels.append(label)
  615. head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  616. print('inh {}: {}'.format(label, head_direction_indices[in_polar_plot_id]))
  617. hdis.append(head_direction_indices)
  618. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  619. ax.hist(hdis, color=colors, label=labels, bins=30)
  620. for hdi, color in zip(hdis, colors):
  621. mean_hdi = np.mean(hdi)
  622. ax.axvline(mean_hdi, 0, 1, color=color, linestyle='--')
  623. ax.set_xlabel("HDI")
  624. ax.legend()
  625. fig.tight_layout()
  626. if save_figs:
  627. plt.savefig(FIGURE_SAVE_PATH + 'hdi_histogram_inhibitory.png', dpi=200)
  628. def filter_run_names_by_par_dict(traj, par_dict):
  629. run_name_list = []
  630. for run_idx, run_name in enumerate(traj.f_get_run_names()):
  631. traj.f_set_crun(run_name)
  632. paramters_equal = True
  633. for key, val in par_dict.items():
  634. if (traj.par[key] != val):
  635. paramters_equal = False
  636. if paramters_equal:
  637. run_name_list.append(run_name)
  638. traj.f_restore_default()
  639. return run_name_list
  640. def plot_exc_and_inh_hdi_over_corr_len(traj, plot_run_names):
  641. corr_len_expl = traj.f_get('correlation_length').f_get_range()
  642. seed_expl = traj.f_get('seed').f_get_range()
  643. label_expl = [traj.derived_parameters.runs[run_name].morphology.morph_label for run_name in traj.f_get_run_names()]
  644. label_range = set(label_expl)
  645. exc_hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  646. exc_hdi_frame.index.names = ["corr_len", "seed", "label"]
  647. inh_hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  648. inh_hdi_frame.index.names = ["corr_len", "seed", "label"]
  649. for run_name, corr_len, seed, label in zip(plot_run_names, corr_len_expl, seed_expl, label_expl):
  650. ex_tunings = traj.results.runs[run_name].ex_tunings
  651. head_direction_indices = traj.results[run_name].head_direction_indices
  652. # TODO: Actual correlation lengths
  653. # actual_corr_len = get_correlation_length(ex_tunings.reshape((30,30)), 450, 30)
  654. exc_hdi_frame[corr_len, seed, label] = np.mean(head_direction_indices)
  655. inh_head_direction_indices = traj.results[run_name].inh_head_direction_indices
  656. inh_hdi_frame[corr_len, seed, label] = np.mean(inh_head_direction_indices)
  657. # TODO: Standart deviation also for the population
  658. exc_hdi_n_and_seed_mean = exc_hdi_frame.groupby(level=[0, 2]).mean()
  659. exc_hdi_n_and_seed_std_dev = exc_hdi_frame.groupby(level=[0, 2]).std()
  660. inh_hdi_n_and_seed_mean = inh_hdi_frame.groupby(level=[0, 2]).mean()
  661. inh_hdi_n_and_seed_std_dev = inh_hdi_frame.groupby(level=[0, 2]).std()
  662. exc_style_dict = {
  663. 'no conn': ['grey', 'dashed', '', 0],
  664. 'ellipsoid': ['red', 'solid', '^', 8.],
  665. 'circular': ['lightsalmon', 'solid', '^', 8.]
  666. }
  667. inh_style_dict = {
  668. 'no conn': ['grey', 'dashed', '', 0],
  669. 'ellipsoid': ['blue', 'solid', 'o', 8.],
  670. 'circular': ['lightblue', 'solid', 'o', 8.]
  671. }
  672. fig, ax = plt.subplots(1, 1)
  673. for label in label_range:
  674. if label == 'no conn':
  675. ax.axhline(exc_hdi_n_and_seed_mean[0, label], color='grey', linestyle='--')
  676. ax.annotate('input', xy=(1.01, 0.44), xycoords='axes fraction')
  677. continue
  678. exc_hdi_mean = exc_hdi_n_and_seed_mean[:, label]
  679. exc_hdi_std = exc_hdi_n_and_seed_std_dev[:, label]
  680. inh_hdi_mean = inh_hdi_n_and_seed_mean[:, label]
  681. inh_hdi_std = inh_hdi_n_and_seed_std_dev[:, label]
  682. corr_len_range = exc_hdi_mean.keys().to_numpy()
  683. exc_col, exc_lin, exc_mar, exc_mar_size = exc_style_dict[label]
  684. inh_col, inh_lin, inh_mar, inh_mar_size = inh_style_dict[label]
  685. ax.plot(corr_len_range, exc_hdi_mean, label='exc., ' + label, marker=exc_mar, color=exc_col, linestyle=exc_lin,
  686. markersize=exc_mar_size, alpha=0.5)
  687. plt.fill_between(corr_len_range, exc_hdi_mean - exc_hdi_std,
  688. exc_hdi_mean + exc_hdi_std, alpha=0.3, color=exc_col)
  689. ax.plot(corr_len_range, inh_hdi_mean, label='inh., ' + label, marker=inh_mar, color=inh_col, linestyle=inh_lin,
  690. markersize=inh_mar_size, alpha=0.5)
  691. plt.fill_between(corr_len_range, inh_hdi_mean - inh_hdi_std,
  692. inh_hdi_mean + inh_hdi_std, alpha=0.3, color=inh_col)
  693. ax.set_xlabel('Correlation length')
  694. ax.set_ylabel('Head Direction Index')
  695. ax.axvline(206.9, color='k', linewidth=0.5)
  696. ax.set_ylim(0.0, 1.0)
  697. ax.set_xlim(0.0, 400.)
  698. tablelegend(ax, ncol=2, bbox_to_anchor=(1, 1),
  699. row_labels=['exc.', 'inh.'],
  700. col_labels=['ellipsoid', 'circular'],
  701. title_label='')
  702. # plt.legend()
  703. if save_figs:
  704. plt.savefig(FIGURE_SAVE_PATH + 'exc_and_inh_hdi_over_corr_len_scaled.png', dpi=200)
  705. def plot_in_degree_map(traj, plot_run_names):
  706. n_ex = int(np.sqrt(traj.N_E))
  707. max_degree = 0
  708. for run_name in plot_run_names:
  709. ie_adjacency = traj.results.runs[run_name].ie_adjacency
  710. exc_degree = np.sum(ie_adjacency, axis=0)
  711. run_max_degree = np.max(exc_degree)
  712. if run_max_degree > max_degree:
  713. max_degree = run_max_degree
  714. fig, axes = plt.subplots(1, 2, figsize=(9., 4.5))
  715. for ax, run_name in zip(axes, plot_run_names[:-1]):
  716. traj.f_set_crun(run_name)
  717. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  718. X, Y = get_position_mesh(traj.results.runs[run_name].ex_positions)
  719. number_of_excitatory_neurons_per_row = int(np.sqrt(traj.N_E))
  720. ie_adjacency = traj.results.runs[run_name].ie_adjacency
  721. exc_degree = np.sum(ie_adjacency, axis=0)
  722. c = ax.pcolor(X, Y, np.reshape(exc_degree, (number_of_excitatory_neurons_per_row,
  723. number_of_excitatory_neurons_per_row)), vmin=0, vmax=max_degree,
  724. cmap='hot')
  725. ax.set_title(label)
  726. fig.colorbar(c, ax=ax, label="in/out-degree")
  727. fig.suptitle('in/out-degree', fontsize=16)
  728. traj.f_restore_default()
  729. if save_figs:
  730. plt.savefig(FIGURE_SAVE_PATH + 'in_degree_map.png', dpi=200)
  731. def plot_spatial_hdi_map(traj, plot_run_names):
  732. max_val = 0
  733. for run_name in plot_run_names:
  734. hdis = traj.results.runs[run_name].head_direction_indices
  735. run_max_val = np.max(hdis)
  736. if run_max_val > max_val:
  737. max_val = run_max_val
  738. fig, axes = plt.subplots(1, 3, figsize=(13.5, 4.5))
  739. for ax, run_name in zip(axes, plot_run_names):
  740. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  741. positions = traj.results.runs[run_name].ex_positions
  742. head_direction_indices = traj.results[run_name].head_direction_indices
  743. print('Mean {}-HDI = {}'.format(label, np.mean(head_direction_indices)))
  744. c = plot_hdi_in_space(ax, positions, head_direction_indices, max_val)
  745. ax.set_title(label)
  746. fig.colorbar(c, ax=ax, label="head direction index")
  747. fig.suptitle('spatial HDI map', fontsize=16)
  748. if save_figs:
  749. plt.savefig(FIGURE_SAVE_PATH + 'spatial_hdi_map.png', dpi=200)
  750. def plot_ellipse_hdi_over_circular_hdi(traj, plot_run_names):
  751. labels = []
  752. inh_hdis = []
  753. exc_hdis = []
  754. no_conn_hdi = 0.
  755. colors = ['black', 'red']
  756. for run_idx, run_name in enumerate(plot_run_names):
  757. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  758. if label != 'no conn':
  759. labels.append(label)
  760. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  761. inh_hdis.append(inh_head_direction_indices)
  762. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  763. exc_hdis.append(exc_head_direction_indices)
  764. else:
  765. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  766. no_conn_hdi = np.mean(exc_head_direction_indices)
  767. fig, ax = plt.subplots(1, 1, figsize=(4.5, 4.5))
  768. plt.subplots_adjust(wspace=0, hspace=0)
  769. bins = np.linspace(0.0, 1.0, 21, endpoint=True)
  770. ax.scatter(exc_hdis[1], exc_hdis[0], color='r', alpha=0.3)
  771. ax.scatter(inh_hdis[1], inh_hdis[0], color='b', alpha=0.3)
  772. ax.set_xlabel('{} HDI'.format(labels[1]))
  773. ax.set_ylabel('{} HDI'.format(labels[0]))
  774. ax.plot([0.0, 1.0], [0.0, 1.0], 'k')
  775. # fig.tight_layout()
  776. if save_figs:
  777. plt.savefig(FIGURE_SAVE_PATH + 'ellipse_hdi_over_circular_hdi.png', dpi=200)
  778. def plot_interneuron_entropy_map(traj, plot_run_names):
  779. n_inh = int(np.sqrt(traj.N_I))
  780. entropy_bins = np.linspace(-np.pi, np.pi, 30)
  781. fig, axes = plt.subplots(1, 2, figsize=(9., 4.5))
  782. for ax, run_name in zip(axes, plot_run_names[:-1]):
  783. traj.f_set_crun(run_name)
  784. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  785. inhibitory_axonal_cloud_array = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  786. inh_positions = [[p[0], p[1]] for p in inhibitory_axonal_cloud_array]
  787. X, Y = get_position_mesh(inh_positions)
  788. ie_adjacency = traj.results.runs[run_name].ie_adjacency
  789. ex_tunings = traj.results.runs[run_name].ex_tunings
  790. print(np.unique(ie_adjacency))
  791. exc_tunings = [ex_tunings[adj] for adj in ie_adjacency.astype(bool)]
  792. for i in range(len(exc_tunings)):
  793. print(len(exc_tunings[i]))
  794. print(exc_tunings)
  795. interneuron_entropy = np.array([get_interneuron_entropy(conn_exc_tunings, entropy_bins) for conn_exc_tunings in exc_tunings])
  796. print(interneuron_entropy.shape)
  797. c = ax.pcolor(X, Y, np.reshape(interneuron_entropy, (n_inh,
  798. n_inh)), vmin=0, vmax=5.,
  799. cmap='hot')
  800. ax.set_title('{}, mean: {:2.2f}'.format(label, np.mean(interneuron_entropy)))
  801. fig.colorbar(c, ax=ax)
  802. fig.suptitle('interneuron entropy map', fontsize=16)
  803. traj.f_restore_default()
  804. fig.tight_layout()
  805. if save_figs:
  806. plt.savefig(FIGURE_SAVE_PATH + 'interneuron_entropy_map.png', dpi=200)
  807. def plot_hdi_over_in_degree_binned(traj, plot_run_names):
  808. fig, ax = plt.subplots(1, 1, figsize=(4.5, 4.5))
  809. for run_idx, run_name in enumerate(plot_run_names):
  810. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  811. if label == 'no conn':
  812. continue
  813. ie_adjacency = traj.results.runs[run_name].ie_adjacency
  814. exc_degree = np.sum(ie_adjacency, axis=0)
  815. head_direction_indices = traj.results[run_name].head_direction_indices
  816. n_bins = 13
  817. bins = np.arange(n_bins + 1) - 0.5
  818. exc_degree_bin_ids = np.digitize(exc_degree, bins)
  819. # print(bins)
  820. # print(exc_degree)
  821. # print(exc_degree_bin_ids)
  822. hdis_per_bin = [[] for i in range(n_bins)]
  823. for idx, hdi in zip(exc_degree_bin_ids, head_direction_indices):
  824. hdis_per_bin[idx - 1].append(hdi)
  825. mean_hdi_per_bin = [np.mean(hdis) for hdis in hdis_per_bin]
  826. ax.bar(np.arange(n_bins), mean_hdi_per_bin, label=label, alpha=0.3)
  827. ax.legend()
  828. ax.set_xlabel("In-degree of exc. neurons")
  829. ax.set_ylabel("Mean Head Direction Index")
  830. # ax.set_title('hdi over in-degree', fontsize=16)
  831. if save_figs:
  832. plt.savefig(FIGURE_SAVE_PATH + 'hdi_over_in_degree_binned.png', dpi=200)
  833. def plot_in_degree_hist(traj, plot_run_names):
  834. fig, ax = plt.subplots(1, 1, figsize=(4.5, 4.5))
  835. for run_idx, run_name in enumerate(plot_run_names):
  836. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  837. if label == 'no conn':
  838. continue
  839. ie_adjacency = traj.results.runs[run_name].ie_adjacency
  840. exc_degree = np.sum(ie_adjacency, axis=0)
  841. head_direction_indices = traj.results[run_name].head_direction_indices
  842. n_bins = 13
  843. bins = np.arange(n_bins + 1) - 0.5
  844. in_degree_hist, bin_edges = np.histogram(exc_degree, bins)
  845. print(in_degree_hist)
  846. # ax.hist(exc_degree, bins=bins, label=label, alpha=0.3)
  847. ax.bar(np.arange(n_bins), in_degree_hist, label=label, alpha=0.3)
  848. ax.legend()
  849. ax.set_xlabel("In-degree of exc. neurons")
  850. ax.set_ylabel("# exc. neurons")
  851. # ax.set_title('hdi over in-degree', fontsize=16)
  852. if save_figs:
  853. plt.savefig(FIGURE_SAVE_PATH + 'in_degree_hist.png', dpi=200)
  854. def plot_hdi_over_in_degree(traj, plot_run_names):
  855. fig, ax = plt.subplots(1, 1)
  856. for run_idx, run_name in enumerate(plot_run_names):
  857. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  858. if label == 'no conn':
  859. continue
  860. ie_adjacency = traj.results.runs[run_name].ie_adjacency
  861. exc_degree = np.sum(ie_adjacency, axis=0)
  862. sort_ids = exc_degree.argsort()
  863. exc_degree_plt = exc_degree[sort_ids]
  864. head_direction_indices = traj.results[run_name].head_direction_indices
  865. hdi_plt = head_direction_indices
  866. hdi_plt = hdi_plt[sort_ids]
  867. ax.scatter(exc_degree_plt, hdi_plt, label=label, alpha=0.3)
  868. ax.legend()
  869. ax.set_xlabel("In-degree of exc. neurons")
  870. ax.set_ylabel("Head Direction Index")
  871. ax.set_title('hdi over in-degree', fontsize=16)
  872. if save_figs:
  873. plt.savefig(FIGURE_SAVE_PATH + 'hdi_over_in_degree.png', dpi=200)
  874. def plot_cut_off_map(traj, plot_run_names, cut_off_distances):
  875. n_ex = int(np.sqrt(traj.N_E))
  876. run_name = plot_run_names[1]
  877. fig, axes = plt.subplots(1, 3, figsize=(10.5, 3.5))
  878. for ax, cut_off_dist in zip(axes, cut_off_distances):
  879. traj.f_set_crun(run_name)
  880. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  881. ex_positions = traj.results.runs[run_name].ex_positions
  882. ex_tunings = traj.results.runs[run_name].ex_tunings
  883. inhibitory_axonal_cloud_array = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  884. exc_cut_off_ids = (ex_positions[:, 0] >= cut_off_dist) & \
  885. (ex_positions[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  886. (ex_positions[:, 1] >= cut_off_dist) & \
  887. (ex_positions[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  888. inh_cut_off_ids = (inhibitory_axonal_cloud_array[:, 0] >= cut_off_dist) & \
  889. (inhibitory_axonal_cloud_array[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  890. (inhibitory_axonal_cloud_array[:, 1] >= cut_off_dist) & \
  891. (inhibitory_axonal_cloud_array[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  892. axonal_clouds = [Pickle(p[0], p[1], traj.morphology.long_axis, traj.morphology.short_axis, p[2]) for p in
  893. inhibitory_axonal_cloud_array[inh_cut_off_ids]]
  894. # ex_tunings[exc_cut_off_ids] = 1.0
  895. cut_off_ex_tunings = [(ex_tunings[i] if exc_cut_off_ids[i] else -4*np.pi/6) for i in range(len(ex_tunings))]
  896. X, Y = get_correct_position_mesh(ex_positions)
  897. head_dir_preference = np.array(cut_off_ex_tunings).reshape((n_ex, n_ex))
  898. # TODO: Why was this transposed for plotting? (now changed)
  899. c = ax.pcolor(X, Y, head_dir_preference, vmin=-np.pi, vmax=np.pi, cmap='hsv')
  900. ax.set_title('{} um cut off'.format(cut_off_dist))
  901. # fig.colorbar(c, ax=ax, label="Tuning")
  902. if label != 'no conn' and axonal_clouds is not None:
  903. for i, p in enumerate(axonal_clouds):
  904. ell = p.get_ellipse()
  905. ax.add_artist(ell)
  906. # fig.suptitle('axonal cloud', fontsize=16)
  907. traj.f_restore_default()
  908. fig.tight_layout()
  909. if save_figs:
  910. plt.savefig(FIGURE_SAVE_PATH + 'cut_off_map.png', dpi=200)
  911. def main():
  912. global save_figs
  913. traj = Trajectory(TRAJ_NAME, add_time=False, dynamic_imports=Brian2MonitorResult)
  914. NO_LOADING = 0
  915. FULL_LOAD = 2
  916. traj.f_load(filename=DATA_FOLDER + TRAJ_NAME + ".hdf5", load_parameters=FULL_LOAD, load_results=NO_LOADING)
  917. traj.v_auto_load = True
  918. save_figs = True
  919. plot_corr_len = get_closest_correlation_length(traj, 200.0)
  920. par_dict = {'seed': 1, 'correlation_length': plot_corr_len}
  921. plot_run_names = filter_run_names_by_par_dict(traj, par_dict)
  922. print(plot_run_names)
  923. direction_idx = 6
  924. dir_indices = [0, 3, 6, 9]
  925. cut_off_distances = [0., 50., 100.] # in micrometers
  926. # plot_axonal_clouds(traj, plot_run_names)
  927. # #
  928. plot_ellipse_hdi_over_circular_hdi(traj, plot_run_names)
  929. ex_polar_plot_id = plot_firing_rate_map_excitatory(traj, direction_idx, plot_run_names)
  930. #
  931. in_polar_plot_id, in_max_rate = plot_firing_rate_map_inhibitory(traj, direction_idx, plot_run_names)
  932. #
  933. ex_polar_plot_hdi, in_polar_plot_hdi = plot_hdi_histogram_combined_and_overlayed(traj, plot_run_names,
  934. ex_polar_plot_id, in_polar_plot_id,
  935. cut_off_distances[0])
  936. ex_polar_plot_hdi, in_polar_plot_hdi = plot_hdi_histogram_combined_and_overlayed(traj, plot_run_names,
  937. ex_polar_plot_id, in_polar_plot_id,
  938. cut_off_distances[1])
  939. ex_polar_plot_hdi, in_polar_plot_hdi = plot_hdi_histogram_combined_and_overlayed(traj, plot_run_names,
  940. ex_polar_plot_id, in_polar_plot_id,
  941. cut_off_distances[2])
  942. plot_cut_off_map(traj, plot_run_names, cut_off_distances)
  943. plot_averaged_firing_rate_map_excitatory(traj, plot_run_names)
  944. plot_interneuron_entropy_map(traj, plot_run_names)
  945. if not save_figs:
  946. plt.show()
  947. traj.f_restore_default()
  948. if __name__ == "__main__":
  949. main()