paper_figures_spatial_head_direction_network_perlin_map.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  1. import os
  2. import matplotlib.legend as mlegend
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. import pandas as pd
  6. from matplotlib.patches import Ellipse
  7. from matplotlib.patches import Polygon
  8. from matplotlib.patches import Rectangle
  9. from mpl_toolkits.axes_grid1 import ImageGrid
  10. from pypet import Trajectory
  11. from pypet.brian2 import Brian2MonitorResult
  12. from scripts.interneuron_placement import get_position_mesh, Pickle, get_correct_position_mesh
  13. from scripts.model_figure.plot_circular_colorbar import plot_colorbar
  14. from scripts.spatial_maps.simplex_input_tuning_correlation.correlation_length_distance_perlin import \
  15. correlation_length_fit_dict
  16. from scripts.spatial_network.figures_spatial_head_direction_network_orientation_map import plot_hdi_in_space
  17. from scripts.spatial_network.perlin.figure_utils import remove_frame, remove_ticks, add_length_scale, cm_per_inch, \
  18. panel_size, head_direction_input_colormap
  19. from scripts.spatial_network.perlin.run_entropy_maximisation_perlin_map import DATA_FOLDER, TRAJ_NAME, \
  20. get_input_head_directions, POLARIZED, CIRCULAR, NO_SYNAPSES
  21. plt.style.use('figures.mplstyle')
  22. FIGURE_SAVE_PATH = '../../../figures/figure_4_paper_perlin/'
  23. # FIGURE_SAVE_PATH = '../../figures/figure_4_poster_fens/'
  24. save_figs = False
  25. def tablelegend(ax, col_labels=None, row_labels=None, title_label="", *args, **kwargs):
  26. """
  27. Place a table legend on the axes.
  28. Creates a legend where the labels are not directly placed with the artists,
  29. but are used as row and column headers, looking like this:
  30. title_label | col_labels[1] | col_labels[2] | col_labels[3]
  31. -------------------------------------------------------------
  32. row_labels[1] |
  33. row_labels[2] | <artists go there>
  34. row_labels[3] |
  35. Parameters
  36. ----------
  37. ax : `matplotlib.axes.Axes`
  38. The artist that contains the legend table, i.e. current axes instant.
  39. col_labels : list of str, optional
  40. A list of labels to be used as column headers in the legend table.
  41. `len(col_labels)` needs to match `ncol`.
  42. row_labels : list of str, optional
  43. A list of labels to be used as row headers in the legend table.
  44. `len(row_labels)` needs to match `len(handles) // ncol`.
  45. title_label : str, optional
  46. Label for the top left corner in the legend table.
  47. ncol : int
  48. Number of columns.
  49. Other Parameters
  50. ----------------
  51. Refer to `matplotlib.legend.Legend` for other parameters.
  52. """
  53. #################### same as `matplotlib.axes.Axes.legend` #####################
  54. handles, labels, extra_args, kwargs = mlegend._parse_legend_args([ax], *args, **kwargs)
  55. if len(extra_args):
  56. raise TypeError('legend only accepts two non-keyword arguments')
  57. if col_labels is None and row_labels is None:
  58. ax.legend_ = mlegend.Legend(ax, handles, labels, **kwargs)
  59. ax.legend_._remove_method = ax._remove_legend
  60. return ax.legend_
  61. #################### modifications for table legend ############################
  62. else:
  63. ncol = kwargs.pop('ncol')
  64. handletextpad = kwargs.pop('handletextpad', 0 if col_labels is None else -2)
  65. title_label = [title_label]
  66. # blank rectangle handle
  67. extra = [Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)]
  68. # empty label
  69. empty = [""]
  70. # number of rows infered from number of handles and desired number of columns
  71. nrow = len(handles) // ncol
  72. # organise the list of handles and labels for table construction
  73. if col_labels is None:
  74. assert nrow == len(
  75. row_labels), "nrow = len(handles) // ncol = %s, but should be equal to len(row_labels) = %s." % (
  76. nrow, len(row_labels))
  77. leg_handles = extra * nrow
  78. leg_labels = row_labels
  79. elif row_labels is None:
  80. assert ncol == len(col_labels), "ncol = %s, but should be equal to len(col_labels) = %s." % (
  81. ncol, len(col_labels))
  82. leg_handles = []
  83. leg_labels = []
  84. else:
  85. assert nrow == len(
  86. row_labels), "nrow = len(handles) // ncol = %s, but should be equal to len(row_labels) = %s." % (
  87. nrow, len(row_labels))
  88. assert ncol == len(col_labels), "ncol = %s, but should be equal to len(col_labels) = %s." % (
  89. ncol, len(col_labels))
  90. leg_handles = extra + extra * nrow
  91. leg_labels = title_label + row_labels
  92. for col in range(ncol):
  93. if col_labels is not None:
  94. leg_handles += extra
  95. leg_labels += [col_labels[col]]
  96. leg_handles += handles[col * nrow:(col + 1) * nrow]
  97. leg_labels += empty * nrow
  98. # Create legend
  99. ax.legend_ = mlegend.Legend(ax, leg_handles, leg_labels, ncol=ncol + int(row_labels is not None),
  100. handletextpad=handletextpad, **kwargs)
  101. ax.legend_._remove_method = ax._remove_legend
  102. return ax.legend_
  103. def get_closest_correlation_length(traj, correlation_length):
  104. available_lengths = sorted(list(set(traj.f_get("correlation_length").f_get_range())))
  105. closest_length = available_lengths[np.argmin(np.abs(np.array(available_lengths) - correlation_length))]
  106. if closest_length != correlation_length:
  107. print("Warning: desired correlation length {:.1f} not available. Taking {:.1f} instead".format(
  108. correlation_length, closest_length))
  109. corr_len = closest_length
  110. return corr_len
  111. def colorbar(mappable):
  112. from mpl_toolkits.axes_grid1 import make_axes_locatable
  113. import matplotlib.pyplot as plt
  114. last_axes = plt.gca()
  115. ax = mappable.axes
  116. fig = ax.figure
  117. divider = make_axes_locatable(ax)
  118. cax = divider.append_axes("right", size="5%", pad=0.05)
  119. cbar = fig.colorbar(mappable, cax=cax)
  120. plt.sca(last_axes)
  121. return cbar
  122. def plot_firing_rate_map_excitatory(traj, direction_idx, plot_run_names, exemplary_excitatory_neuron_id):
  123. max_val = 0
  124. for run_name in plot_run_names:
  125. fr_array = traj.results.runs[run_name].firing_rate_array
  126. f_rates = fr_array[:, direction_idx]
  127. run_max_val = np.max(f_rates)
  128. if run_max_val > max_val:
  129. # if traj.derived_parameters.runs[run_name].morphology.morph_label == POLARIZED:
  130. # n_id_max_rate = np.argmax(f_rates)
  131. max_val = run_max_val
  132. n_id_polar_plot = exemplary_excitatory_neuron_id
  133. # Mark the neuron that is shown in polar plot
  134. ex_positions = traj.results.runs[plot_run_names[0]].ex_positions
  135. polar_plot_x, polar_plot_y = ex_positions[n_id_polar_plot]
  136. # Vertices for the plotted triangle
  137. tr_scale = 30.
  138. tr_x = tr_scale * np.cos(2. * np.pi / 3. + np.pi / 2.)
  139. tr_y = tr_scale * np.sin(2. * np.pi / 3. + np.pi / 2.) + polar_plot_y
  140. tr_vertices = np.array(
  141. [[polar_plot_x, polar_plot_y + tr_scale], [tr_x + polar_plot_x, tr_y], [-tr_x + polar_plot_x, tr_y]])
  142. height = 1 * panel_size
  143. width = 3 * panel_size
  144. fig = plt.figure(figsize=(width, height))
  145. axes = ImageGrid(fig, (0.05, 0.15, 0.85, 0.7), axes_pad=panel_size / 6.0, cbar_location="right",
  146. cbar_mode="single",
  147. cbar_size="7%", cbar_pad=panel_size / 10.0,
  148. nrows_ncols=(1, 3))
  149. for ax, run_name in zip(axes, [plot_run_names[i] for i in [2, 0, 1]]):
  150. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  151. X, Y = get_correct_position_mesh(traj.results.runs[run_name].ex_positions)
  152. firing_rate_array = traj.results[run_name].firing_rate_array
  153. number_of_excitatory_neurons_per_row = int(np.sqrt(traj.N_E))
  154. c = ax.pcolor(X, Y, np.reshape(firing_rate_array[:, direction_idx], (number_of_excitatory_neurons_per_row,
  155. number_of_excitatory_neurons_per_row)),
  156. vmin=0, vmax=max_val, cmap='Reds')
  157. # ax.set_title(adjust_label(label))
  158. # ax.add_artist(Ellipse((polar_plot_x, polar_plot_y), 20., 20., color='k', fill=False, lw=2.))
  159. # ax.add_artist(Ellipse((polar_plot_x, polar_plot_y), 20., 20., color='w', fill=False, lw=1.))
  160. ax.add_artist(Polygon(tr_vertices, closed=True, fill=False, lw=2.5, color='k'))
  161. ax.add_artist(Polygon(tr_vertices, closed=True, fill=False, lw=1.5, color='w'))
  162. for spine in ax.spines.values():
  163. spine.set_edgecolor("grey")
  164. spine.set_linewidth(1)
  165. remove_ticks(ax)
  166. # fig.suptitle('spatial firing rate map', fontsize=16)
  167. ax.cax.colorbar(c)
  168. ax.cax.annotate("fr (Hz)", xy=(1, 1), xytext=(3, 3), xycoords="axes fraction", textcoords="offset points")
  169. # fig.tight_layout()
  170. if save_figs:
  171. plt.savefig(FIGURE_SAVE_PATH + 'C_firing_rate_map_excitatory.png', dpi=300)
  172. plt.close(fig)
  173. def plot_firing_rate_map_inhibitory(traj, direction_idx, plot_run_names, selected_inhibitory_neuron):
  174. max_val = 0
  175. for run_name in plot_run_names:
  176. fr_array = traj.results.runs[run_name].inh_firing_rate_array
  177. f_rates = fr_array[:, direction_idx]
  178. run_max_val = np.max(f_rates)
  179. if run_max_val > max_val:
  180. max_val = run_max_val
  181. n_id_polar_plot = selected_inhibitory_neuron
  182. # Mark the neuron that is shown in Polar plot
  183. inhibitory_axonal_cloud_array = traj.results.runs[plot_run_names[1]].inhibitory_axonal_cloud_array
  184. polar_plot_x = inhibitory_axonal_cloud_array[n_id_polar_plot, 0]
  185. polar_plot_y = inhibitory_axonal_cloud_array[n_id_polar_plot, 1]
  186. width = 3 * panel_size
  187. height = panel_size
  188. fig = plt.figure(figsize=(width, height))
  189. axes = ImageGrid(fig, (0.05, 0.15, 0.85, 0.7), axes_pad=panel_size / 6.0, cbar_location="right",
  190. cbar_mode="single",
  191. cbar_size="7%", cbar_pad=panel_size / 10.0,
  192. nrows_ncols=(1, 3))
  193. for ax, run_name in zip(axes, [plot_run_names[i] for i in [2, 0, 1]]):
  194. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  195. inhibitory_axonal_cloud_array = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  196. inh_positions = [[p[0], p[1]] for p in inhibitory_axonal_cloud_array]
  197. X, Y = get_correct_position_mesh(inh_positions)
  198. inh_firing_rate_array = traj.results[run_name].inh_firing_rate_array
  199. number_of_inhibitory_neurons_per_row = int(np.sqrt(traj.N_I))
  200. c = ax.pcolor(X, Y, np.reshape(inh_firing_rate_array[:, direction_idx], (number_of_inhibitory_neurons_per_row,
  201. number_of_inhibitory_neurons_per_row)),
  202. vmin=0, vmax=max_val, cmap='Blues')
  203. # ax.set_title(adjust_label(label))
  204. circle_r = 40.
  205. ax.add_artist(Ellipse((polar_plot_x, polar_plot_y), circle_r, circle_r, color='k', fill=False, lw=4.5))
  206. ax.add_artist(Ellipse((polar_plot_x, polar_plot_y), circle_r, circle_r, color='w', fill=False, lw=3))
  207. for spine in ax.spines.values():
  208. spine.set_edgecolor("grey")
  209. spine.set_linewidth(0.5)
  210. remove_ticks(ax)
  211. # fig.colorbar(c, ax=ax, label="f (Hz)")
  212. # fig.suptitle('spatial firing rate map', fontsize=16)
  213. ax.cax.colorbar(c)
  214. ax.cax.annotate("fr (Hz)", xy=(1, 1), xytext=(3, 3), xycoords="axes fraction", textcoords="offset points")
  215. # fig.tight_layout()
  216. if save_figs:
  217. plt.savefig(FIGURE_SAVE_PATH + 'C_firing_rate_map_inhibitory.png', dpi=300)
  218. plt.close(fig)
  219. return max_val
  220. def plot_hdi_over_tuning(traj, plot_run_names):
  221. fig, ax = plt.subplots(1, 1)
  222. for run_idx, run_name in enumerate(plot_run_names):
  223. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  224. ex_tunings = traj.results.runs[run_name].ex_tunings
  225. ex_tunings_plt = np.array(ex_tunings)
  226. sort_ids = ex_tunings_plt.argsort()
  227. ex_tunings_plt = ex_tunings_plt[sort_ids]
  228. head_direction_indices = traj.results[run_name].head_direction_indices
  229. hdi_plt = head_direction_indices
  230. hdi_plt = hdi_plt[sort_ids]
  231. ax.scatter(ex_tunings_plt, hdi_plt, label=label, alpha=0.3)
  232. ax.legend()
  233. ax.set_xlabel("Angles (rad)")
  234. ax.set_ylabel("head direction index")
  235. ax.set_title('hdi over input tuning', fontsize=16)
  236. if save_figs:
  237. plt.savefig(FIGURE_SAVE_PATH + 'hdi_over_tuning.png')
  238. plt.close(fig)
  239. def normal_labels(label):
  240. if label == POLARIZED:
  241. label = 'polar'
  242. elif label == NO_SYNAPSES:
  243. label = 'no interneurons'
  244. return label
  245. def short_labels(label):
  246. if label == POLARIZED:
  247. label = 'polar'
  248. elif label == CIRCULAR:
  249. label = 'circ.'
  250. elif label == "no conn":
  251. label = "no inh."
  252. return label
  253. def plot_input_map(traj, run_name, figsize=(panel_size, panel_size), figname='input_map.png'):
  254. n_ex = int(np.sqrt(traj.N_E))
  255. width, height = figsize
  256. fig = plt.figure(figsize=(width, height))
  257. axes = ImageGrid(fig, (0.15, 0.1, 0.7, 0.8), axes_pad=panel_size / 3.0, cbar_location="right", cbar_mode=None,
  258. nrows_ncols=(1, 1))
  259. ax = axes[0]
  260. traj.f_set_crun(run_name)
  261. X, Y = get_correct_position_mesh(traj.results.runs[run_name].ex_positions)
  262. head_dir_preference = np.array(traj.results.runs[run_name].ex_tunings).reshape((n_ex, n_ex))
  263. scale_length = traj.morphology.long_axis * 2
  264. traj.f_restore_default()
  265. ax.pcolor(X, Y, head_dir_preference, vmin=-np.pi, vmax=np.pi, cmap=head_direction_input_colormap)
  266. for spine in ax.spines.values():
  267. spine.set_edgecolor("grey")
  268. spine.set_linewidth(0.5)
  269. remove_ticks(ax)
  270. start_scale_x = 100
  271. end_scale_x = start_scale_x + scale_length
  272. start_scale_y = -70
  273. end_scale_y = start_scale_y
  274. add_length_scale(ax, scale_length, start_scale_x, end_scale_x, start_scale_y, end_scale_y)
  275. ax.cax.set_visible(False)
  276. if save_figs:
  277. plt.savefig(FIGURE_SAVE_PATH + figname)
  278. plt.close(fig)
  279. def plot_axonal_clouds(traj, plot_run_names):
  280. n_ex = int(np.sqrt(traj.N_E))
  281. height = 1 * panel_size
  282. width = 3 * panel_size
  283. cluster_positions = [(250, 250), (750, 200), (450, 600)]
  284. cluster_sizes = [4, 4, 4]
  285. selected_neurons = []
  286. inhibitory_positions = traj.results.runs[plot_run_names[0]].inhibitory_axonal_cloud_array[:, :2]
  287. for cluster_position, number_of_neurons_in_cluster in zip(cluster_positions, cluster_sizes):
  288. selection = get_neurons_close_to_given_position(cluster_position, number_of_neurons_in_cluster,
  289. inhibitory_positions)
  290. selected_neurons.extend(selection)
  291. fig = plt.figure(figsize=(width, height))
  292. axes = ImageGrid(fig, 111, axes_pad=0.15, cbar_location="right", cbar_mode="single", cbar_size="7%",
  293. nrows_ncols=(1, 3))
  294. for ax, run_name in zip(axes, [plot_run_names[i] for i in [2, 0, 1]]):
  295. traj.f_set_crun(run_name)
  296. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  297. X, Y = get_correct_position_mesh(traj.results.runs[run_name].ex_positions)
  298. inhibitory_axonal_cloud_array = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  299. axonal_clouds = [Pickle(p[0], p[1], traj.morphology.long_axis, traj.morphology.short_axis, p[2]) for p in
  300. inhibitory_axonal_cloud_array]
  301. head_dir_preference = np.array(traj.results.runs[run_name].ex_tunings).reshape((n_ex, n_ex))
  302. c = ax.pcolor(X, Y, head_dir_preference, vmin=-np.pi, vmax=np.pi, cmap=head_direction_input_colormap)
  303. # ax.set_title(normal_labels(label))
  304. ax.set_aspect('equal')
  305. remove_frame(ax)
  306. remove_ticks(ax)
  307. # fig.colorbar(c, ax=ax, label="Tuning")
  308. if label != NO_SYNAPSES and axonal_clouds is not None:
  309. for i, p in enumerate(axonal_clouds):
  310. ell = p.get_ellipse()
  311. if i in selected_neurons:
  312. edgecolor = 'black'
  313. alpha = 1
  314. zorder = 10
  315. linewidth = 1
  316. else:
  317. edgecolor = 'gray'
  318. alpha = 0.5
  319. zorder = 1
  320. linewidth = 0.3
  321. ell.set_edgecolor(edgecolor)
  322. ell.set_alpha(alpha)
  323. ell.set_zorder(zorder)
  324. ell.set_linewidth(linewidth)
  325. ax.add_artist(ell)
  326. traj.f_set_crun(plot_run_names[0])
  327. scale_length = traj.morphology.long_axis * 2
  328. traj.f_restore_default()
  329. start_scale_x = 100
  330. end_scale_x = start_scale_x + scale_length
  331. start_scale_y = -70
  332. end_scale_y = start_scale_y
  333. add_length_scale(axes[0], scale_length, start_scale_x, end_scale_x, start_scale_y, end_scale_y)
  334. axes[1].set_yticklabels([])
  335. axes[2].set_yticklabels([])
  336. axes[0].cax.set_visible(False)
  337. traj.f_restore_default()
  338. if save_figs:
  339. plt.savefig(FIGURE_SAVE_PATH + 'B_i_axonal_clouds.png')
  340. plt.close(fig)
  341. def get_neurons_close_to_given_position(cluster_position, number_of_neurons_in_cluster, positions):
  342. position = np.array(cluster_position)
  343. distance_vectors = positions - np.expand_dims(position, 0).repeat(positions.shape[0],
  344. axis=0)
  345. distances = np.linalg.norm(distance_vectors, axis=1)
  346. selection = list(np.argpartition(distances, number_of_neurons_in_cluster)[:number_of_neurons_in_cluster])
  347. return selection
  348. def plot_orientation_maps_diff_scales(traj):
  349. n_ex = int(np.sqrt(traj.N_E))
  350. scale_run_names = []
  351. plot_scales = [0.0, 100.0, 200.0, 300.0]
  352. for scale in plot_scales:
  353. par_dict = {'seed': 1, 'correlation_length': get_closest_correlation_length(traj, scale), 'long_axis': 100.}
  354. scale_run_names.append(*filter_run_names_by_par_dict(traj, par_dict))
  355. fig, axes = plt.subplots(1, 4, figsize=(18., 4.5))
  356. for ax, run_name, scale in zip(axes, scale_run_names, plot_scales):
  357. traj.f_set_crun(run_name)
  358. X, Y = get_position_mesh(traj.results.runs[run_name].ex_positions)
  359. head_dir_preference = np.array(traj.results.runs[run_name].ex_tunings).reshape((n_ex, n_ex))
  360. # TODO: Why was this transposed for plotting? (now changed)
  361. c = ax.pcolor(X, Y, head_dir_preference, vmin=-np.pi, vmax=np.pi, cmap='twilight')
  362. ax.set_title('Correlation length: {}'.format(scale))
  363. fig.colorbar(c, ax=ax, label="Tuning")
  364. # fig.suptitle('axonal cloud', fontsize=16)
  365. traj.f_restore_default()
  366. if save_figs:
  367. plt.savefig(FIGURE_SAVE_PATH + 'orientation_maps_diff_scales.png')
  368. plt.close(fig)
  369. def plot_orientation_maps_diff_scales_with_ellipse(traj):
  370. n_ex = int(np.sqrt(traj.N_E))
  371. scale_run_names = []
  372. plot_scales = [0.0, 400.0, 800.0]
  373. real_scales = [get_closest_correlation_length(traj, scale) for scale in plot_scales]
  374. for scale in plot_scales:
  375. par_dict = {'seed': 1, 'correlation_length': get_closest_correlation_length(traj, scale), 'long_axis': 100.}
  376. scale_run_names.append(*filter_run_names_by_par_dict(traj, par_dict))
  377. print(scale_run_names)
  378. inhibitory_positions = traj.results.runs[scale_run_names[1]].inhibitory_axonal_cloud_array[:, :2]
  379. selected_polar_neuron = get_neurons_close_to_given_position((300, 300), 1, inhibitory_positions)[0]
  380. print(selected_polar_neuron)
  381. selected_circular_neuron = get_neurons_close_to_given_position((600, 600), 1, inhibitory_positions)[0]
  382. width = panel_size
  383. height = 1.5 * panel_size
  384. fig = plt.figure(figsize=(width, height))
  385. axes = ImageGrid(fig, 111, axes_pad=0.15,
  386. nrows_ncols=(len(plot_scales), 1))
  387. for ax, run_name, scale in zip(axes, scale_run_names, real_scales):
  388. traj.f_set_crun(run_name)
  389. X, Y = get_position_mesh(traj.results.runs[run_name].ex_positions)
  390. inhibitory_axonal_cloud_array = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  391. axonal_clouds = [Pickle(p[0], p[1], traj.morphology.long_axis, traj.morphology.short_axis, p[2]) for p in
  392. inhibitory_axonal_cloud_array]
  393. head_dir_preference = np.array(traj.results.runs[run_name].ex_tunings).reshape((n_ex, n_ex))
  394. # TODO: Why was this transposed for plotting? (now changed)
  395. c = ax.pcolor(X, Y, head_dir_preference, vmin=-np.pi, vmax=np.pi, cmap=head_direction_input_colormap)
  396. # ax.set_title('Correlation length: {}'.format(scale))
  397. # fig.colorbar(c, ax=ax, label="Tuning")
  398. ax.set_xticks([])
  399. ax.set_yticks([])
  400. p1 = axonal_clouds[selected_polar_neuron]
  401. ell = p1.get_ellipse()
  402. ell._linewidth = 2.
  403. ax.add_artist(ell)
  404. p2 = axonal_clouds[selected_circular_neuron]
  405. circ_r = 2 * np.sqrt(p2.a * p2.b)
  406. circ = Ellipse((p2.x, p2.y), circ_r, circ_r, fill=False, zorder=2, edgecolor='k')
  407. circ._linewidth = 2.
  408. ax.add_artist(circ)
  409. ax.annotate("{:.0f}".format(scale), xy=(1.0, 0.5), xytext=(2, 0), xycoords="axes fraction", textcoords="offset "
  410. "points",
  411. va="center", ha="left")
  412. remove_frame(ax)
  413. # fig.suptitle('axonal cloud', fontsize=16)
  414. traj.f_restore_default()
  415. add_length_scale(axes[1], 200, -300, -100, 50, 50)
  416. axes[0].annotate("input maps", xy=(-0.5, 1.0), xycoords="axes fraction", rotation=90, ha="left", va="top")
  417. fig.tight_layout()
  418. if save_figs:
  419. plt.savefig(FIGURE_SAVE_PATH + 'F_orientation_maps_diff_scales_with_ellipse.png')
  420. plt.close(fig)
  421. def plot_polar_plot_excitatory(traj, plot_run_names, selected_neuron_idx,
  422. figname=FIGURE_SAVE_PATH + 'D_polar_plot_excitatory.png'):
  423. directions = np.linspace(-np.pi, np.pi, traj.input.number_of_directions, endpoint=False)
  424. directions_plt = list(directions)
  425. directions_plt.append(directions[0])
  426. height = panel_size
  427. width = panel_size
  428. fig, ax = plt.subplots(1, 1, figsize=(height, width), subplot_kw=dict(projection='polar'))
  429. # head_direction_indices = traj.results.runs[plot_run_names[0]].head_direction_indices
  430. # sorted_ids = np.argsort(head_direction_indices)
  431. # plot_n_idx = sorted_ids[-75]
  432. plot_n_idx = selected_neuron_idx
  433. line_styles = ['dotted', 'solid', 'dashed']
  434. colors = ['r', 'lightsalmon', 'grey']
  435. line_widths = [1.5, 1.5, 1]
  436. zorders = [10, 2, 1]
  437. max_rate = 0.0
  438. for run_idx, run_name in enumerate(plot_run_names):
  439. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  440. hdi = traj.results.runs[run_name].head_direction_indices[selected_neuron_idx]
  441. tuning_vectors = traj.results.runs[run_name].tuning_vectors
  442. rate_plot = [np.linalg.norm(v) for v in tuning_vectors[plot_n_idx]]
  443. run_max_rate = np.max(rate_plot)
  444. if run_max_rate > max_rate:
  445. max_rate = run_max_rate
  446. rate_plot.append(rate_plot[0])
  447. ax.plot(directions_plt, rate_plot, linewidth=line_widths[run_idx],
  448. label='{:s} {:.2f}'.format(short_labels(label), hdi),
  449. color=colors[run_idx], linestyle=line_styles[run_idx], zorder=zorders[run_idx])
  450. # ax.set_title('Firing Rate')
  451. # ax.plot([0.0, 0.0], [0.0, 1.05 * max_rate], color='red', alpha=0.25, linewidth=4.)
  452. # TODO: Set ticks for polar
  453. ticks = [40., 80.]
  454. ax.set_rgrids(ticks, labels=["{:.0f} Hz".format(ticklabel) if idx == len(ticks) - 1 else "" for idx, ticklabel in
  455. enumerate(ticks)], angle=60)
  456. ax.set_thetagrids([0, 90, 180, 270], labels=[])
  457. ax.xaxis.grid(linewidth=0.4)
  458. ax.yaxis.grid(linewidth=0.4)
  459. leg = ax.legend(loc="lower right", bbox_to_anchor=(1.15, -0.15), handlelength=1, fontsize="medium")
  460. leg.get_frame().set_linewidth(0.0)
  461. ax.axes.spines["polar"].set_visible(False)
  462. if save_figs:
  463. plt.savefig(figname)
  464. plt.close(fig)
  465. def plot_polar_plot_inhibitory(traj, plot_run_names, selected_neuron_idx, figname=FIGURE_SAVE_PATH +
  466. 'D_polar_plot_inhibitory.png'):
  467. directions = np.linspace(-np.pi, np.pi, traj.input.number_of_directions, endpoint=False)
  468. directions_plt = list(directions)
  469. directions_plt.append(directions[0])
  470. height = panel_size
  471. width = panel_size
  472. fig, ax = plt.subplots(1, 1, figsize=(height, width), subplot_kw=dict(projection='polar'))
  473. # head_direction_indices = traj.results.runs[plot_run_names[0]].inh_head_direction_indices
  474. # sorted_ids = np.argsort(head_direction_indices)
  475. # plot_n_idx = sorted_ids[-75]
  476. plot_n_idx = selected_neuron_idx
  477. line_styles = ['dotted', 'solid']
  478. colors = ['b', 'lightblue']
  479. line_widths = [1.5, 1.5]
  480. zorders = [10, 2]
  481. for run_idx, run_name in enumerate(plot_run_names[:2]):
  482. # ax = axes[max_hdi_idx, run_idx]
  483. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  484. hdi = traj.results.runs[run_name].inh_head_direction_indices[selected_neuron_idx]
  485. tuning_vectors = traj.results.runs[run_name].inh_tuning_vectors
  486. rate_plot = [np.linalg.norm(v) for v in tuning_vectors[plot_n_idx]]
  487. rate_plot.append(rate_plot[0])
  488. ax.plot(directions_plt, rate_plot, linewidth=line_widths[run_idx],
  489. label='{:s} {:.2f}'.format(short_labels(label), hdi),
  490. color=colors[run_idx], linestyle=line_styles[run_idx], zorder=zorders[run_idx])
  491. # ax.set_title('Inh. Firing Rate')
  492. # TODO: Set ticks for polar
  493. # ticks = [np.round(max_rate / 3.), np.round(max_rate * 2. / 3.), np.round(max_rate)]
  494. ticks = [40., 80., 120.]
  495. ax.set_rgrids(ticks, labels=["{:.0f} Hz".format(ticklabel) if idx == len(ticks) - 1 else "" for idx, ticklabel in
  496. enumerate(ticks)], angle=60)
  497. ax.set_thetagrids([0, 90, 180, 270], labels=[])
  498. ax.xaxis.grid(linewidth=0.4)
  499. ax.yaxis.grid(linewidth=0.4)
  500. leg = ax.legend(loc="lower right", bbox_to_anchor=(1.15, -0.15), handlelength=1, fontsize="medium")
  501. leg.get_frame().set_linewidth(0.0)
  502. ax.axes.spines["polar"].set_visible(False)
  503. if save_figs:
  504. plt.savefig(figname)
  505. plt.close(fig)
  506. def plot_hdi_over_corr_len(traj, plot_run_names):
  507. corr_len_expl = traj.f_get('correlation_length').f_get_range()
  508. seed_expl = traj.f_get('seed').f_get_range()
  509. label_expl = [traj.derived_parameters.runs[run_name].morphology.morph_label for run_name in traj.f_get_run_names()]
  510. label_range = set(label_expl)
  511. hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  512. hdi_frame.index.names = ["corr_len", "seed", "label"]
  513. for run_name, corr_len, seed, label in zip(plot_run_names, corr_len_expl, seed_expl, label_expl):
  514. ex_tunings = traj.results.runs[run_name].ex_tunings
  515. head_direction_indices = traj.results[run_name].head_direction_indices
  516. hdi_frame[corr_len, seed, label] = np.mean(head_direction_indices)
  517. # TODO: Standart deviation also for the population
  518. hdi_exc_n_and_seed_mean = hdi_frame.groupby(level=[0, 2]).mean()
  519. hdi_exc_n_and_seed_std_dev = hdi_frame.groupby(level=[0, 2]).std()
  520. # Ellipsoid markers
  521. rx, ry = 5., 12.
  522. # area = rx * ry * np.pi * 2.
  523. area = 1.
  524. theta = np.arange(0, 2 * np.pi + 0.01, 0.1)
  525. verts = np.column_stack([rx / area * np.cos(theta), ry / area * np.sin(theta)])
  526. style_dict = {
  527. NO_SYNAPSES: ['grey', 'dashed', '', 0],
  528. POLARIZED: ['blue', 'solid', verts, 10.],
  529. CIRCULAR: ['lightblue', 'solid', 'o', 8.]
  530. }
  531. # colors = ['blue', 'grey', 'lightblue']
  532. # linestyles = ['solid', 'dashed', 'solid']
  533. # markers = [verts, '', 'o']
  534. fig, ax = plt.subplots(1, 1)
  535. for label in label_range:
  536. hdi_mean = hdi_exc_n_and_seed_mean[:, label]
  537. hdi_std = hdi_exc_n_and_seed_std_dev[:, label]
  538. corr_len_range = hdi_mean.keys().to_numpy()
  539. col, lin, mar, mar_size = style_dict[label]
  540. ax.plot(corr_len_range, hdi_mean, label=label, marker=mar, color=col, linestyle=lin, markersize=mar_size)
  541. plt.fill_between(corr_len_range, hdi_mean - hdi_std,
  542. hdi_mean + hdi_std, alpha=0.4, color=col)
  543. ax.set_xlabel('Correlation length')
  544. ax.set_ylabel('Head Direction Index')
  545. ax.axvline(206.9, color='k', linewidth=0.5)
  546. ax.set_ylim(0.0, 1.0)
  547. ax.set_xlim(0.0, 400.)
  548. ax.legend()
  549. if save_figs:
  550. plt.savefig(FIGURE_SAVE_PATH + 'hdi_over_corr_len_scaled.png', dpi=200)
  551. plt.close(fig)
  552. def plot_hdi_histogram_excitatory(traj, plot_run_names):
  553. labels = []
  554. hdis = []
  555. colors = ['black', 'red', 'green']
  556. for run_idx, run_name in enumerate(plot_run_names):
  557. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  558. labels.append(label)
  559. head_direction_indices = traj.results.runs[run_name].head_direction_indices
  560. hdis.append(head_direction_indices)
  561. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  562. ax.hist(hdis, color=colors, label=labels, bins=30)
  563. for hdi, color in zip(hdis, colors):
  564. mean_hdi = np.mean(hdi)
  565. ax.axvline(mean_hdi, 0, 1, color=color, linestyle='--')
  566. ax.set_xlabel("HDI")
  567. ax.legend()
  568. fig.tight_layout()
  569. if save_figs:
  570. plt.savefig(FIGURE_SAVE_PATH + 'hdi_histogram_excitatory.png', dpi=200)
  571. plt.close(fig)
  572. def plot_hdi_violin_excitatory(traj, plot_run_names):
  573. labels = []
  574. hdis = []
  575. colors = ['black', 'red', 'green']
  576. no_conn_hdi = 0.
  577. for run_idx, run_name in enumerate(plot_run_names):
  578. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  579. head_direction_indices = traj.results.runs[run_name].head_direction_indices
  580. if label == NO_SYNAPSES:
  581. no_conn_hdi = np.mean(head_direction_indices)
  582. else:
  583. labels.append(label)
  584. hdis.append(sorted(head_direction_indices))
  585. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  586. # hdis = np.array(hdis)
  587. viol_plt = ax.violinplot(hdis, showmeans=True, showextrema=False)
  588. viol_plt['cmeans'].set_color('black')
  589. for pc in viol_plt['bodies']:
  590. pc.set_facecolor('red')
  591. pc.set_edgecolor('black')
  592. pc.set_alpha(0.7)
  593. ax.axhline(no_conn_hdi, color='black', linestyle='--')
  594. ax.annotate(NO_SYNAPSES, xy=(0.45, 0.48), xycoords='axes fraction')
  595. ax.set_xticks(np.arange(1, len(labels) + 1))
  596. ax.set_xticklabels(labels)
  597. ax.set_ylabel('HDI')
  598. fig.tight_layout()
  599. if save_figs:
  600. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_excitatory.png', dpi=200)
  601. plt.close(fig)
  602. def plot_hdi_violin_inhibitory(traj, plot_run_names):
  603. labels = []
  604. hdis = []
  605. colors = ['black', 'red']
  606. for run_idx, run_name in enumerate(plot_run_names):
  607. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  608. if label != NO_SYNAPSES:
  609. labels.append(label)
  610. head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  611. hdis.append(sorted(head_direction_indices))
  612. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  613. viol_plt = ax.violinplot(hdis, showmeans=True, showextrema=False)
  614. viol_plt['cmeans'].set_color('black')
  615. for pc in viol_plt['bodies']:
  616. pc.set_facecolor('blue')
  617. pc.set_edgecolor('black')
  618. pc.set_alpha(0.7)
  619. ax.set_xticks(np.arange(1, len(labels) + 1))
  620. ax.set_xticklabels(labels)
  621. ax.set_ylabel('HDI')
  622. fig.tight_layout()
  623. if save_figs:
  624. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_inhibitory.png', dpi=200)
  625. plt.close(fig)
  626. def plot_hdi_violin_combined(traj, plot_run_names):
  627. labels = []
  628. inh_hdis = []
  629. exc_hdis = []
  630. no_conn_hdi = 0.
  631. colors = ['black', 'red']
  632. for run_idx, run_name in enumerate(plot_run_names):
  633. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  634. if label != NO_SYNAPSES:
  635. labels.append(label)
  636. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  637. inh_hdis.append(sorted(inh_head_direction_indices))
  638. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  639. exc_hdis.append(sorted(exc_head_direction_indices))
  640. else:
  641. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  642. no_conn_hdi = np.mean(exc_head_direction_indices)
  643. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  644. inh_viol_plt = ax.violinplot(inh_hdis, showmeans=True, showextrema=False)
  645. # viol_plt['cmeans'].set_color('black')
  646. #
  647. # for pc in viol_plt['bodies']:
  648. # pc.set_facecolor('blue')
  649. # pc.set_edgecolor('black')
  650. # pc.set_alpha(0.7)
  651. for b in inh_viol_plt['bodies']:
  652. m = np.mean(b.get_paths()[0].vertices[:, 0])
  653. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], m, np.inf)
  654. b.set_color('b')
  655. exc_viol_plt = ax.violinplot(exc_hdis, showmeans=True, showextrema=False)
  656. for b in exc_viol_plt['bodies']:
  657. m = np.mean(b.get_paths()[0].vertices[:, 0])
  658. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], -np.inf, m)
  659. b.set_color('r')
  660. ax.axhline(no_conn_hdi, color='black', linestyle='--')
  661. ax.annotate(NO_SYNAPSES, xy=(0.45, 0.48), xycoords='axes fraction')
  662. ax.set_xticks(np.arange(1, len(labels) + 1))
  663. ax.set_xticklabels(labels)
  664. ax.set_ylabel('HDI')
  665. fig.tight_layout()
  666. if save_figs:
  667. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_combined.svg', dpi=200)
  668. plt.close(fig)
  669. def plot_hdi_violin_combined_and_overlayed(traj, plot_run_names, ex_polar_plot_id, in_polar_plot_id):
  670. labels = []
  671. inh_hdis = []
  672. exc_hdis = []
  673. no_conn_hdi = 0.
  674. in_polar_plot_hdi = []
  675. ex_polar_plot_hdi = []
  676. colors = ['black', 'red']
  677. for run_idx, run_name in enumerate(plot_run_names):
  678. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  679. if label != NO_SYNAPSES:
  680. labels.append(label)
  681. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  682. inh_hdis.append(sorted(inh_head_direction_indices))
  683. in_polar_plot_hdi.append(inh_head_direction_indices[in_polar_plot_id])
  684. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  685. exc_hdis.append(sorted(exc_head_direction_indices))
  686. ex_polar_plot_hdi.append(exc_head_direction_indices[ex_polar_plot_id])
  687. else:
  688. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  689. no_conn_hdi = np.mean(exc_head_direction_indices)
  690. ex_polar_plot_hdi.append(exc_head_direction_indices[ex_polar_plot_id])
  691. fig, ax = plt.subplots(1, 1, figsize=(3.5, 4.5))
  692. inh_ell_viol_plt = ax.violinplot(inh_hdis[0], showmeans=True, showextrema=False)
  693. for b in inh_ell_viol_plt['bodies']:
  694. m = np.mean(b.get_paths()[0].vertices[:, 0])
  695. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], m, np.inf)
  696. b.set_color('b')
  697. mean_line = inh_ell_viol_plt['cmeans']
  698. mean_line.set_color('b')
  699. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], m, np.inf)
  700. exc_ell_viol_plt = ax.violinplot(exc_hdis[0], showmeans=True, showextrema=False)
  701. for b in exc_ell_viol_plt['bodies']:
  702. m = np.mean(b.get_paths()[0].vertices[:, 0])
  703. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], m, np.inf)
  704. b.set_color('r')
  705. mean_line = exc_ell_viol_plt['cmeans']
  706. mean_line.set_color('r')
  707. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], m, np.inf)
  708. inh_cir_viol_plt = ax.violinplot(inh_hdis[1], showmeans=True, showextrema=False)
  709. for b in inh_cir_viol_plt['bodies']:
  710. m = np.mean(b.get_paths()[0].vertices[:, 0])
  711. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], -np.inf, m)
  712. b.set_color('b')
  713. mean_line = inh_cir_viol_plt['cmeans']
  714. mean_line.set_color('b')
  715. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], -np.inf, m)
  716. exc_cir_viol_plt = ax.violinplot(exc_hdis[1], showmeans=True, showextrema=False)
  717. for b in exc_cir_viol_plt['bodies']:
  718. m = np.mean(b.get_paths()[0].vertices[:, 0])
  719. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], -np.inf, m)
  720. b.set_color('r')
  721. mean_line = exc_cir_viol_plt['cmeans']
  722. mean_line.set_color('r')
  723. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], -np.inf, m)
  724. ax.axhline(no_conn_hdi, 0.5, 1., color='black', linestyle='--')
  725. ax.axvline(1.0, color='k')
  726. ax.annotate(NO_SYNAPSES, xy=(0.75, 0.415), xycoords='axes fraction')
  727. ax.set_xlim(0.5, 1.5)
  728. ax.set_ylim(0.0, 1.0)
  729. ax.set_xticks([0.75, 1.25])
  730. ax.set_xticklabels([CIRCULAR, POLARIZED])
  731. ax.set_ylabel('HDI')
  732. fig.tight_layout()
  733. if save_figs:
  734. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_combined_and_overlayed.svg', dpi=200)
  735. plt.close(fig)
  736. return ex_polar_plot_hdi, in_polar_plot_hdi
  737. def plot_hdi_histogram_combined_and_overlayed(traj, plot_run_names, ex_polar_plot_id, in_polar_plot_id, cut_off_dist):
  738. labels = []
  739. inh_hdis = []
  740. exc_hdis = []
  741. no_conn_hdi = 0.
  742. for run_idx, run_name in enumerate(plot_run_names):
  743. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  744. if label != NO_SYNAPSES:
  745. labels.append(normal_labels(label))
  746. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  747. inh_axonal_cloud = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  748. inh_cut_off_ids = (inh_axonal_cloud[:, 0] >= cut_off_dist) & \
  749. (inh_axonal_cloud[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  750. (inh_axonal_cloud[:, 1] >= cut_off_dist) & \
  751. (inh_axonal_cloud[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  752. # print(inh_positions)
  753. inh_hdis.append(sorted(inh_head_direction_indices[inh_cut_off_ids]))
  754. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  755. ex_positions = traj.results.runs[run_name].ex_positions
  756. # print(ex_positions)
  757. exc_cut_off_ids = (ex_positions[:, 0] >= cut_off_dist) & \
  758. (ex_positions[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  759. (ex_positions[:, 1] >= cut_off_dist) & \
  760. (ex_positions[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  761. exc_hdis.append(sorted(exc_head_direction_indices[exc_cut_off_ids]))
  762. else:
  763. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  764. no_conn_hdi = np.mean(exc_head_direction_indices)
  765. # Look for a representative excitatory neuron
  766. hdi_mean_dict = {}
  767. excitatory_hdi_means = [np.mean(hdis) for hdis in exc_hdis]
  768. hdi_mean_dict["polar_exc"] = excitatory_hdi_means[0]
  769. hdi_mean_dict["circular_exc"] = excitatory_hdi_means[1]
  770. inhibitory_hdi_means = [np.mean(hdis) for hdis in inh_hdis]
  771. hdi_mean_dict["polar_inh"] = inhibitory_hdi_means[0]
  772. hdi_mean_dict["circular_inh"] = inhibitory_hdi_means[1]
  773. # # fig = plt.figure(figsize=(3.5, 3.5))
  774. # # gs1 = gridspec.GridSpec(1, 2)
  775. #
  776. # fig = plt.figure(constrained_layout=True)
  777. # gs = gridspec.GridSpec(ncols=1, nrows=2, hspace=0.0, wspace=0.0, figure=fig)
  778. # # gs.update(wspace=0.0, hspace=0.0) # set the spacing between axes.
  779. # # f2_ax1 = fig.add_subplot(gs[0, 0])
  780. # # f2_ax2 = fig.add_subplot(gs[0, 1])
  781. # print(gs.get_subplot_params())
  782. width = 2 * panel_size
  783. height = 1.2 * panel_size
  784. fig, axes = plt.subplots(2, 1, figsize=(width, height))
  785. plt.subplots_adjust(wspace=0, hspace=0.1)
  786. bins = np.linspace(0.0, 1.0, 21, endpoint=True)
  787. max_density = 0
  788. for i in range(2):
  789. # i = i + 1 # grid spec indexes from 0
  790. # ax = fig.add_subplot(gs[i])
  791. ax = axes[i]
  792. density_e, _, _ = ax.hist(exc_hdis[i], color='r', edgecolor='r', alpha=0.3, bins=bins, density=True)
  793. density_i, _, _ = ax.hist(inh_hdis[i], color='b', edgecolor='b', alpha=0.3, bins=bins, density=True)
  794. max_density = np.max([max_density, np.max(density_e), np.max(density_i)])
  795. ax.axvline(np.mean(exc_hdis[i]), color='r')
  796. ax.axvline(np.mean(inh_hdis[i]), color='b')
  797. ax.axvline(no_conn_hdi, color='dimgrey', linestyle='--', linewidth=2.5)
  798. ax.set_ylabel(labels[i], rotation='vertical')
  799. # plt.axis('on')
  800. if i == 0:
  801. ax.set_xticklabels([])
  802. else:
  803. ax.set_xlabel('head direction index')
  804. remove_frame(ax, ["top", "right", "bottom"])
  805. max_density = 1.2 * max_density
  806. fig.subplots_adjust(left=0.2, right=0.95, bottom=0.2)
  807. axes[0].annotate('% cells', (0, 1.0), xycoords='axes fraction', va="bottom", ha="right")
  808. axes[1].annotate("no ihn.\n{:.2f}".format(no_conn_hdi), xy=(no_conn_hdi, max_density),
  809. xytext=(-2, 0), xycoords="data",
  810. textcoords="offset points",
  811. va="top", ha="right", color="dimgrey")
  812. for i, ax in enumerate(axes):
  813. ax.annotate("{:.2f}".format(np.mean(exc_hdis[i])), xy=(np.mean(exc_hdis[i]), max_density),
  814. xytext=(2, 0), xycoords="data",
  815. textcoords="offset points",
  816. va="top", ha="left", color="r")
  817. i_ha = "left" if i == 1 else "right"
  818. i_offset = 2 if i == 1 else -2
  819. ax.annotate("{:.2f}".format(np.mean(inh_hdis[i])), xy=(np.mean(inh_hdis[i]), max_density),
  820. xytext=(i_offset, 0), xycoords="data",
  821. textcoords="offset points",
  822. va="top", ha=i_ha, color="b")
  823. for ax in axes:
  824. ax.set_ylim(0, max_density)
  825. # plt.annotate('probability density', (-0.2,1.5), xycoords='axes fraction', rotation=90, fontsize=18)
  826. if save_figs:
  827. plt.savefig(FIGURE_SAVE_PATH + 'E_hdi_histogram_combined_and_overlayed_cutoff_{}um.png'.format(cut_off_dist))
  828. plt.close(fig)
  829. return hdi_mean_dict
  830. def get_neurons_with_given_hdi(polar_hdi, circular_hdi, max_number_of_suggestions, plot_run_names, traj, type):
  831. polar_run_name = plot_run_names[0]
  832. circular_run_name = plot_run_names[1]
  833. polar_ex_hdis = traj.results.runs[polar_run_name].head_direction_indices if type == "ex" else traj.results.runs[
  834. polar_run_name].inh_head_direction_indices
  835. circular_ex_hdis = traj.results.runs[circular_run_name].head_direction_indices if type == "ex" else \
  836. traj.results.runs[
  837. polar_run_name].inh_head_direction_indices
  838. neuron_indices = get_indices_of_closest_values(polar_ex_hdis, polar_hdi,
  839. circular_ex_hdis,
  840. circular_hdi, 0.1 * np.abs(
  841. polar_hdi - circular_hdi), max_number_of_suggestions)
  842. return neuron_indices
  843. def get_indices_of_closest_values(first_list, first_value, second_list, second_value, absolute_tolerance_list_one,
  844. number_of_indices):
  845. is_close_in_list_one = np.abs(first_list - first_value) < absolute_tolerance_list_one
  846. indices_close_in_list_one = np.where(is_close_in_list_one)[0]
  847. indices_closest_in_list_two = indices_close_in_list_one[np.argpartition(np.abs(second_list[
  848. indices_close_in_list_one] - second_value),
  849. number_of_indices)]
  850. return indices_closest_in_list_two[:number_of_indices]
  851. def plot_hdi_histogram_inhibitory(traj, plot_run_names, in_polar_plot_id):
  852. labels = []
  853. hdis = []
  854. colors = ['black', 'red']
  855. for run_idx, run_name in enumerate(plot_run_names):
  856. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  857. if label != NO_SYNAPSES:
  858. labels.append(label)
  859. head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  860. print('inh {}: {}'.format(label, head_direction_indices[in_polar_plot_id]))
  861. hdis.append(head_direction_indices)
  862. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  863. ax.hist(hdis, color=colors, label=labels, bins=30)
  864. for hdi, color in zip(hdis, colors):
  865. mean_hdi = np.mean(hdi)
  866. ax.axvline(mean_hdi, 0, 1, color=color, linestyle='--')
  867. ax.set_xlabel("HDI")
  868. ax.legend()
  869. fig.tight_layout()
  870. if save_figs:
  871. plt.savefig(FIGURE_SAVE_PATH + 'hdi_histogram_inhibitory.png', dpi=200)
  872. plt.close(fig)
  873. def filter_run_names_by_par_dict(traj, par_dict):
  874. run_name_list = []
  875. for run_idx, run_name in enumerate(traj.f_get_run_names()):
  876. traj.f_set_crun(run_name)
  877. paramters_equal = True
  878. for key, val in par_dict.items():
  879. if (traj.par[key] != val):
  880. paramters_equal = False
  881. if paramters_equal:
  882. run_name_list.append(run_name)
  883. traj.f_restore_default()
  884. return run_name_list
  885. def plot_exc_and_inh_hdi_over_simplex_grid_scale(traj, plot_run_names):
  886. corr_len_expl = traj.f_get('correlation_length').f_get_range()
  887. seed_expl = traj.f_get('seed').f_get_range()
  888. label_expl = [traj.derived_parameters.runs[run_name].morphology.morph_label for run_name in traj.f_get_run_names()]
  889. label_range = set(label_expl)
  890. exc_hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  891. exc_hdi_frame.index.names = ["corr_len", "seed", "label"]
  892. inh_hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  893. inh_hdi_frame.index.names = ["corr_len", "seed", "label"]
  894. for run_name, corr_len, seed, label in zip(plot_run_names, corr_len_expl, seed_expl, label_expl):
  895. ex_tunings = traj.results.runs[run_name].ex_tunings
  896. head_direction_indices = traj.results[run_name].head_direction_indices
  897. # TODO: Actual correlation lengths
  898. # actual_corr_len = get_correlation_length(ex_tunings.reshape((30,30)), 450, 30)
  899. exc_hdi_frame[corr_len, seed, label] = np.mean(head_direction_indices)
  900. inh_head_direction_indices = traj.results[run_name].inh_head_direction_indices
  901. inh_hdi_frame[corr_len, seed, label] = np.mean(inh_head_direction_indices)
  902. # TODO: Standard deviation also for the population
  903. exc_hdi_n_and_seed_mean = exc_hdi_frame.groupby(level=[0, 2]).mean()
  904. exc_hdi_n_and_seed_std_dev = exc_hdi_frame.groupby(level=[0, 2]).std()
  905. inh_hdi_n_and_seed_mean = inh_hdi_frame.groupby(level=[0, 2]).mean()
  906. inh_hdi_n_and_seed_std_dev = inh_hdi_frame.groupby(level=[0, 2]).std()
  907. markersize = 4.
  908. exc_style_dict = {
  909. NO_SYNAPSES: ['dimgrey', 'dashed', '', 0],
  910. POLARIZED: ['red', 'solid', '^', markersize],
  911. CIRCULAR: ['lightsalmon', 'solid', '^', markersize]
  912. }
  913. inh_style_dict = {
  914. NO_SYNAPSES: ['dimgrey', 'dashed', '', 0],
  915. POLARIZED: ['blue', 'solid', 'o', markersize],
  916. CIRCULAR: ['lightblue', 'solid', 'o', markersize]
  917. }
  918. # colors = ['blue', 'grey', 'lightblue']
  919. # linestyles = ['solid', 'dashed', 'solid']
  920. # markers = [verts, '', 'o']
  921. # corr_len_fit_dict = correlation_length_fit_dict(traj, load=True)
  922. width = 2 * panel_size
  923. height = 1.2 * panel_size
  924. fig, ax = plt.subplots(1, 1, figsize=(width, height))
  925. for label in sorted(label_range, reverse=True):
  926. if label == NO_SYNAPSES:
  927. no_conn_hdi = exc_hdi_n_and_seed_mean[1, label]
  928. ax.axhline(no_conn_hdi, color='grey', linestyle='--')
  929. ax.annotate(short_labels(label), xy=(1.0, no_conn_hdi), xytext=(0, -2), xycoords='axes fraction',
  930. textcoords="offset points",
  931. va="top", \
  932. ha="right",
  933. color="dimgrey")
  934. continue
  935. exc_hdi_mean = exc_hdi_n_and_seed_mean[:, label]
  936. exc_hdi_std = exc_hdi_n_and_seed_std_dev[:, label]
  937. inh_hdi_mean = inh_hdi_n_and_seed_mean[:, label]
  938. inh_hdi_std = inh_hdi_n_and_seed_std_dev[:, label]
  939. corr_len_range = exc_hdi_mean.keys().to_numpy()
  940. print(label)
  941. for corr_len, ex_hdi, in_hdi in zip(corr_len_range, exc_hdi_mean, inh_hdi_mean):
  942. print("length: {:.2f} um, ex hdi: {:.2f} and in hdi {:.2f}".format(corr_len, ex_hdi, in_hdi))
  943. exc_col, exc_lin, exc_mar, exc_mar_size = exc_style_dict[label]
  944. inh_col, inh_lin, inh_mar, inh_mar_size = inh_style_dict[label]
  945. simplex_grid_scale = corr_len_range * np.sqrt(2)
  946. ax.plot(simplex_grid_scale, exc_hdi_mean, label='exc., ' + label, marker=exc_mar, color=exc_col, linestyle=exc_lin,
  947. markersize=exc_mar_size, alpha=0.5)
  948. plt.fill_between(simplex_grid_scale, exc_hdi_mean - exc_hdi_std,
  949. exc_hdi_mean + exc_hdi_std, alpha=0.3, color=exc_col)
  950. ax.plot(simplex_grid_scale, inh_hdi_mean, label='inh., ' + label, marker=inh_mar, color=inh_col, linestyle=inh_lin,
  951. markersize=inh_mar_size, alpha=0.5)
  952. plt.fill_between(simplex_grid_scale, inh_hdi_mean - inh_hdi_std,
  953. inh_hdi_mean + inh_hdi_std, alpha=0.3, color=inh_col)
  954. ax.set_xlabel('simplex grid scale')
  955. ax.set_ylabel('head direction index')
  956. ax.axvline(get_closest_correlation_length(traj, 200.0) * np.sqrt(2), color='k', linewidth=0.5, zorder=0)
  957. ax.set_ylim(0.0, 1.0)
  958. # ax.set_xlim(0.0, np.max(corr_len_range))
  959. remove_frame(ax, ["right", "top"])
  960. tablelegend(ax, ncol=2, bbox_to_anchor=(1.1, 1.1), loc="upper right",
  961. row_labels=None,
  962. col_labels=[short_labels(label) for label in sorted(label_range - {"no conn"}, reverse=True)],
  963. title_label='', borderaxespad=0, handlelength=2, edgecolor='white')
  964. fig.subplots_adjust(bottom=0.2, left=0.2)
  965. # plt.legend()
  966. if save_figs:
  967. plt.savefig(FIGURE_SAVE_PATH + 'F_hdi_over_corr_len_scaled.png')
  968. plt.close(fig)
  969. def plot_exc_and_inh_hdi_over_fit_corr_len(traj, plot_run_names):
  970. corr_len_expl = traj.f_get('correlation_length').f_get_range()
  971. seed_expl = traj.f_get('seed').f_get_range()
  972. label_expl = [traj.derived_parameters.runs[run_name].morphology.morph_label for run_name in traj.f_get_run_names()]
  973. label_range = set(label_expl)
  974. exc_hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  975. exc_hdi_frame.index.names = ["corr_len", "seed", "label"]
  976. inh_hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  977. inh_hdi_frame.index.names = ["corr_len", "seed", "label"]
  978. for run_name, corr_len, seed, label in zip(plot_run_names, corr_len_expl, seed_expl, label_expl):
  979. ex_tunings = traj.results.runs[run_name].ex_tunings
  980. head_direction_indices = traj.results[run_name].head_direction_indices
  981. # TODO: Actual correlation lengths
  982. # actual_corr_len = get_correlation_length(ex_tunings.reshape((30,30)), 450, 30)
  983. exc_hdi_frame[corr_len, seed, label] = np.mean(head_direction_indices)
  984. inh_head_direction_indices = traj.results[run_name].inh_head_direction_indices
  985. inh_hdi_frame[corr_len, seed, label] = np.mean(inh_head_direction_indices)
  986. # TODO: Standard deviation also for the population
  987. exc_hdi_n_and_seed_mean = exc_hdi_frame.groupby(level=[0, 2]).mean()
  988. exc_hdi_n_and_seed_std_dev = exc_hdi_frame.groupby(level=[0, 2]).std()
  989. inh_hdi_n_and_seed_mean = inh_hdi_frame.groupby(level=[0, 2]).mean()
  990. inh_hdi_n_and_seed_std_dev = inh_hdi_frame.groupby(level=[0, 2]).std()
  991. markersize = 4.
  992. exc_style_dict = {
  993. NO_SYNAPSES: ['dimgrey', 'dashed', '', 0],
  994. POLARIZED: ['red', 'solid', '^', markersize],
  995. CIRCULAR: ['lightsalmon', 'solid', '^', markersize]
  996. }
  997. inh_style_dict = {
  998. NO_SYNAPSES: ['dimgrey', 'dashed', '', 0],
  999. POLARIZED: ['blue', 'solid', 'o', markersize],
  1000. CIRCULAR: ['lightblue', 'solid', 'o', markersize]
  1001. }
  1002. # colors = ['blue', 'grey', 'lightblue']
  1003. # linestyles = ['solid', 'dashed', 'solid']
  1004. # markers = [verts, '', 'o']
  1005. corr_len_fit_dict = correlation_length_fit_dict(traj, load=True)
  1006. width = 2 * panel_size
  1007. height = 1.2 * panel_size
  1008. fig, ax = plt.subplots(1, 1, figsize=(width, height))
  1009. for label in sorted(label_range, reverse=True):
  1010. if label == NO_SYNAPSES:
  1011. no_conn_hdi = exc_hdi_n_and_seed_mean[1, label]
  1012. ax.axhline(no_conn_hdi, color='grey', linestyle='--')
  1013. ax.annotate(short_labels(label), xy=(1.0, no_conn_hdi), xytext=(0, -2), xycoords='axes fraction',
  1014. textcoords="offset points",
  1015. va="top", \
  1016. ha="right",
  1017. color="dimgrey")
  1018. continue
  1019. exc_hdi_mean = exc_hdi_n_and_seed_mean[:, label]
  1020. exc_hdi_std = exc_hdi_n_and_seed_std_dev[:, label]
  1021. inh_hdi_mean = inh_hdi_n_and_seed_mean[:, label]
  1022. inh_hdi_std = inh_hdi_n_and_seed_std_dev[:, label]
  1023. corr_len_range = exc_hdi_mean.keys().to_numpy()
  1024. print(label)
  1025. for corr_len, ex_hdi, in_hdi in zip(corr_len_range, exc_hdi_mean, inh_hdi_mean):
  1026. print("length: {:.2f} um, ex hdi: {:.2f} and in hdi {:.2f}".format(corr_len, ex_hdi, in_hdi))
  1027. exc_col, exc_lin, exc_mar, exc_mar_size = exc_style_dict[label]
  1028. inh_col, inh_lin, inh_mar, inh_mar_size = inh_style_dict[label]
  1029. fit_corr_len = [corr_len_fit_dict[corr_len] for corr_len in corr_len_range]
  1030. print(corr_len_range)
  1031. print(fit_corr_len)
  1032. ax.plot(fit_corr_len, exc_hdi_mean, label='exc., ' + label, marker=exc_mar, color=exc_col, linestyle=exc_lin,
  1033. markersize=exc_mar_size, alpha=0.5)
  1034. plt.fill_between(fit_corr_len, exc_hdi_mean - exc_hdi_std,
  1035. exc_hdi_mean + exc_hdi_std, alpha=0.3, color=exc_col)
  1036. ax.plot(fit_corr_len, inh_hdi_mean, label='inh., ' + label, marker=inh_mar, color=inh_col, linestyle=inh_lin,
  1037. markersize=inh_mar_size, alpha=0.5)
  1038. plt.fill_between(fit_corr_len, inh_hdi_mean - inh_hdi_std,
  1039. inh_hdi_mean + inh_hdi_std, alpha=0.3, color=inh_col)
  1040. ax.set_xlabel('correlation length')
  1041. ax.set_ylabel('head direction index')
  1042. ax.axvline(corr_len_fit_dict[get_closest_correlation_length(traj, 200.0)], color='k', linewidth=0.5, zorder=0)
  1043. ax.set_ylim(0.0, 1.0)
  1044. # ax.set_xlim(0.0, np.max(corr_len_range))
  1045. remove_frame(ax, ["right", "top"])
  1046. tablelegend(ax, ncol=2, bbox_to_anchor=(1.1, 1.1), loc="upper right",
  1047. row_labels=None,
  1048. col_labels=[short_labels(label) for label in sorted(label_range - {"no conn"}, reverse=True)],
  1049. title_label='', borderaxespad=0, handlelength=2, edgecolor='white')
  1050. fig.subplots_adjust(bottom=0.2, left=0.2)
  1051. # plt.legend()
  1052. if save_figs:
  1053. plt.savefig(FIGURE_SAVE_PATH + 'hdi_over_fit_corr_len.png')
  1054. plt.close(fig)
  1055. def plot_in_degree_map(traj, plot_run_names):
  1056. n_ex = int(np.sqrt(traj.N_E))
  1057. max_degree = 0
  1058. for run_name in plot_run_names:
  1059. ie_adjacency = traj.results.runs[run_name].ie_adjacency
  1060. exc_degree = np.sum(ie_adjacency, axis=0)
  1061. run_max_degree = np.max(exc_degree)
  1062. if run_max_degree > max_degree:
  1063. max_degree = run_max_degree
  1064. fig, axes = plt.subplots(1, 2, figsize=(9., 4.5))
  1065. for ax, run_name in zip(axes, plot_run_names[:-1]):
  1066. traj.f_set_crun(run_name)
  1067. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  1068. X, Y = get_position_mesh(traj.results.runs[run_name].ex_positions)
  1069. number_of_excitatory_neurons_per_row = int(np.sqrt(traj.N_E))
  1070. ie_adjacency = traj.results.runs[run_name].ie_adjacency
  1071. exc_degree = np.sum(ie_adjacency, axis=0)
  1072. c = ax.pcolor(X, Y, np.reshape(exc_degree, (number_of_excitatory_neurons_per_row,
  1073. number_of_excitatory_neurons_per_row)), vmin=0, vmax=max_degree,
  1074. cmap='hot')
  1075. ax.set_title(label)
  1076. fig.colorbar(c, ax=ax, label="in/out-degree")
  1077. fig.suptitle('in/out-degree', fontsize=16)
  1078. traj.f_restore_default()
  1079. if save_figs:
  1080. plt.savefig(FIGURE_SAVE_PATH + 'in_degree_map.png', dpi=200)
  1081. plt.close(fig)
  1082. def plot_spatial_hdi_map(traj, plot_run_names):
  1083. max_val = 0
  1084. for run_name in plot_run_names:
  1085. hdis = traj.results.runs[run_name].head_direction_indices
  1086. run_max_val = np.max(hdis)
  1087. if run_max_val > max_val:
  1088. max_val = run_max_val
  1089. fig, axes = plt.subplots(1, 3, figsize=(13.5, 4.5))
  1090. for ax, run_name in zip(axes, plot_run_names):
  1091. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  1092. positions = traj.results.runs[run_name].ex_positions
  1093. head_direction_indices = traj.results[run_name].head_direction_indices
  1094. print('Mean {}-HDI = {}'.format(label, np.mean(head_direction_indices)))
  1095. c = plot_hdi_in_space(ax, positions, head_direction_indices, max_val)
  1096. ax.set_title(label)
  1097. fig.colorbar(c, ax=ax, label="head direction index")
  1098. fig.suptitle('spatial HDI map', fontsize=16)
  1099. if save_figs:
  1100. plt.savefig(FIGURE_SAVE_PATH + 'spatial_hdi_map.png', dpi=200)
  1101. plt.close(fig)
  1102. def plot_exc_spatial_hdi_map(traj, plot_run_names):
  1103. max_val = 0
  1104. for run_name in plot_run_names:
  1105. hdis = traj.results.runs[run_name].head_direction_indices
  1106. run_max_val = np.max(hdis)
  1107. if run_max_val > max_val:
  1108. max_val = run_max_val
  1109. fig, axes = plt.subplots(1, 3, figsize=(13.5, 4.5))
  1110. for ax, run_name in zip(axes, plot_run_names):
  1111. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  1112. positions = traj.results.runs[run_name].ex_positions
  1113. head_direction_indices = traj.results[run_name].head_direction_indices
  1114. print('Mean {}-HDI = {}'.format(label, np.mean(head_direction_indices)))
  1115. c = plot_hdi_in_space(ax, positions, head_direction_indices, max_val)
  1116. ax.set_title(label)
  1117. fig.colorbar(c, ax=ax, label="head direction index")
  1118. fig.suptitle('spatial exc. HDI map', fontsize=16)
  1119. if save_figs:
  1120. plt.savefig(FIGURE_SAVE_PATH + 'spatial_exc_hdi_map.png', dpi=200)
  1121. plt.close(fig)
  1122. def plot_inh_spatial_hdi_map(traj, plot_run_names):
  1123. max_val = 0
  1124. for run_name in plot_run_names:
  1125. hdis = traj.results.runs[run_name].inh_head_direction_indices
  1126. run_max_val = np.max(hdis)
  1127. if run_max_val > max_val:
  1128. max_val = run_max_val
  1129. fig, axes = plt.subplots(1, 3, figsize=(13.5, 4.5))
  1130. for ax, run_name in zip(axes, plot_run_names):
  1131. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  1132. ax_cloud = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  1133. positions = [[x, y] for x, y, phi in ax_cloud]
  1134. head_direction_indices = traj.results[run_name].inh_head_direction_indices
  1135. print('Mean {}-HDI = {}'.format(label, np.mean(head_direction_indices)))
  1136. c = plot_hdi_in_space(ax, positions, head_direction_indices, max_val)
  1137. ax.set_title(label)
  1138. fig.colorbar(c, ax=ax, label="head direction index")
  1139. fig.suptitle('spatial inh. HDI map', fontsize=16)
  1140. if save_figs:
  1141. plt.savefig(FIGURE_SAVE_PATH + 'spatial_inh_hdi_map.png', dpi=200)
  1142. plt.close(fig)
  1143. def get_phase_difference(total_difference):
  1144. """
  1145. Map accumulated phase difference to shortest possible difference
  1146. :param total_difference:
  1147. :return: relative_difference
  1148. """
  1149. return (total_difference + np.pi) % (2 * np.pi) - np.pi
  1150. def plot_firing_rate_similar_vs_diff_tuning(traj, plot_run_names):
  1151. # The plot that Imre wanted
  1152. n_bins = traj.parameters.input.number_of_directions
  1153. fig, ax = plt.subplots(1, 1, figsize=(9, 9))
  1154. dir_bins = np.linspace(-np.pi, np.pi, n_bins + 1)
  1155. print(dir_bins)
  1156. plot_fr_array = []
  1157. labels = []
  1158. similarity_threshold = np.pi / 6.
  1159. directions = np.linspace(-np.pi, np.pi, traj.input.number_of_directions, endpoint=False)
  1160. for run_idx, run_name in enumerate(plot_run_names):
  1161. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  1162. labels.append(label)
  1163. fr_similar_tunings = []
  1164. fr_different_tunings = []
  1165. ex_tunings = traj.results.runs[run_name].ex_tunings
  1166. firing_rate_array = traj.results[run_name].firing_rate_array
  1167. for tuning, firing_rates in zip(ex_tunings, firing_rate_array):
  1168. for idx, dir in enumerate(directions):
  1169. if np.abs(get_phase_difference(tuning - dir)) <= similarity_threshold:
  1170. fr_similar_tunings.append(firing_rates[idx])
  1171. elif np.abs(get_phase_difference(tuning + np.pi - dir)) <= similarity_threshold:
  1172. fr_different_tunings.append(firing_rates[idx])
  1173. plot_fr_array.append([np.mean(fr_similar_tunings), np.mean(fr_different_tunings)])
  1174. x = np.arange(3) # the label locations
  1175. width = 0.35 # the width of the bars
  1176. plot_fr_array = np.array(plot_fr_array)
  1177. rects1 = ax.bar(x - width / 2, plot_fr_array[:, 0], width,
  1178. label='theta pref +/- {}°'.format(np.round(similarity_threshold / np.pi * 180)))
  1179. rects2 = ax.bar(x + width / 2, plot_fr_array[:, 1], width,
  1180. label='theta pref + 180° +/- {}°'.format(np.round(similarity_threshold / np.pi * 180)))
  1181. ax.set_xticks(x)
  1182. ax.set_xticklabels(labels)
  1183. ax.set_title('Mean firing rate for tunings similar and different to input')
  1184. ax.set_ylabel('Mean firing rate')
  1185. ax.legend()
  1186. def autolabel(rects):
  1187. """Attach a text label above each bar in *rects*, displaying its height."""
  1188. for rect in rects:
  1189. height = rect.get_height()
  1190. ax.annotate('{}'.format(np.round(height)),
  1191. xy=(rect.get_x() + rect.get_width() / 2, height),
  1192. xytext=(0, 3), # 3 points vertical offset
  1193. textcoords="offset points",
  1194. ha='center', va='bottom')
  1195. autolabel(rects1)
  1196. autolabel(rects2)
  1197. fig.tight_layout()
  1198. if save_figs:
  1199. plt.savefig(FIGURE_SAVE_PATH + 'firing_rate_similar_vs_diff_tuning.png', dpi=200)
  1200. plt.close(fig)
  1201. def get_firing_rates_along_preferred_axis(traj, run_name, neuron_idx):
  1202. firing_rates = traj.results[run_name].firing_rate_array[neuron_idx, :]
  1203. tuning = traj.results[run_name].ex_tunings[neuron_idx]
  1204. anti_tuning = tuning + np.pi if tuning + np.pi < np.pi else tuning - np.pi
  1205. tuning_idx = np.argmin(np.abs(directions - tuning))
  1206. anti_tuning_idx = np.argmin(np.abs(directions - anti_tuning))
  1207. firing_at_the_preferred_direction = firing_rates[tuning_idx]
  1208. firing_at_the_opposite_direction = firing_rates[anti_tuning_idx]
  1209. return firing_at_the_preferred_direction, firing_at_the_opposite_direction
  1210. def get_hdi(traj, run_name, neuron_idx, type):
  1211. return traj.results.runs[run_name].head_direction_indices[neuron_idx] if type=="ex" else traj.results.runs[
  1212. run_name].inh_head_direction_indices[neuron_idx]
  1213. if __name__ == "__main__":
  1214. traj = Trajectory(TRAJ_NAME, add_time=False, dynamic_imports=Brian2MonitorResult)
  1215. NO_LOADING = 0
  1216. FULL_LOAD = 2
  1217. traj.f_load(filename=os.path.join(DATA_FOLDER, TRAJ_NAME + ".hdf5"), load_parameters=FULL_LOAD,
  1218. load_results=NO_LOADING)
  1219. traj.v_auto_load = True
  1220. save_figs = True
  1221. print("# Plotting script polarized interneurons")
  1222. print()
  1223. map_length_scale = 200.0
  1224. map_seed = 1
  1225. exemplary_head_direction = 0
  1226. # corr_len_fit_dict = correlation_length_fit_dict(traj, load=True)
  1227. # plt.plot(corr_len_fit_dict.keys(),corr_len_fit_dict.values())
  1228. # plt.show()
  1229. # abbrechen
  1230. print("## Map specifications")
  1231. print("\tcorrelation length: {:.1f} um".format(map_length_scale))
  1232. print("\tmap seed: {:d}".format(map_seed))
  1233. print()
  1234. print("## Input specification")
  1235. print("\tselected head direction: {:.0f}°".format(exemplary_head_direction))
  1236. print()
  1237. print("## Selected simulations")
  1238. plot_corr_len = get_closest_correlation_length(traj, map_length_scale)
  1239. par_dict = {'seed': map_seed, 'correlation_length': plot_corr_len}
  1240. plot_run_names = filter_run_names_by_par_dict(traj, par_dict)
  1241. run_name_dict = {}
  1242. for run_name in plot_run_names:
  1243. traj.f_set_crun(run_name)
  1244. run_name_dict[traj.derived_parameters.runs[run_name].morphology.morph_label] = run_name
  1245. for network_type, run_name in run_name_dict.items():
  1246. print("{:s}: {:s}".format(network_type, run_name))
  1247. directions = get_input_head_directions(traj)
  1248. direction_idx = np.argmin(np.abs(np.array(directions) - np.deg2rad(exemplary_head_direction)))
  1249. selected_neuron_excitatory = 1716
  1250. selected_inhibitory_neuron = 144
  1251. print("## Figure specification")
  1252. print("\tpanel size: {:.2f} cm".format(panel_size * cm_per_inch))
  1253. print()
  1254. #
  1255. plot_colorbar(figsize=(0.8 * panel_size, 0.8 * panel_size), figname=FIGURE_SAVE_PATH + "A_i_colormap.svg")
  1256. plot_input_map(traj, run_name_dict[POLARIZED], figname="A_i_exemplary_input_map.png",
  1257. figsize=(panel_size, panel_size))
  1258. plot_axonal_clouds(traj, plot_run_names)
  1259. #
  1260. plot_firing_rate_map_excitatory(traj, direction_idx, plot_run_names, selected_neuron_excitatory)
  1261. in_max_rate = plot_firing_rate_map_inhibitory(traj, direction_idx, plot_run_names, selected_inhibitory_neuron)
  1262. #
  1263. hdi_means = plot_hdi_histogram_combined_and_overlayed(
  1264. traj, plot_run_names,
  1265. selected_neuron_excitatory,
  1266. selected_inhibitory_neuron,
  1267. cut_off_dist=100.)
  1268. #
  1269. number_of_suggestions = 20
  1270. representative_excitatory_neuron_indices = get_neurons_with_given_hdi(hdi_means["polar_exc"], hdi_means[
  1271. "circular_exc"],
  1272. number_of_suggestions, plot_run_names,
  1273. traj, "ex")
  1274. representative_inhibitory_neuron_indices = get_neurons_with_given_hdi(hdi_means["polar_inh"],
  1275. hdi_means["circular_inh"],
  1276. number_of_suggestions, plot_run_names,
  1277. traj, "in")
  1278. plot_polar_plot_excitatory(traj, plot_run_names, selected_neuron_excitatory)
  1279. for suggested_excitatory_neuron in representative_excitatory_neuron_indices:
  1280. preferred_polar, opposite_polar = get_firing_rates_along_preferred_axis(
  1281. traj, run_name_dict["ellipsoid"], suggested_excitatory_neuron)
  1282. preferred_circular, opposite_circular = get_firing_rates_along_preferred_axis(
  1283. traj, run_name_dict["circular"], suggested_excitatory_neuron)
  1284. plot_polar_plot_excitatory(traj, plot_run_names, suggested_excitatory_neuron,
  1285. figname=FIGURE_SAVE_PATH + "X_polar_plot_excitatory_neuron_signal_increase_{"
  1286. ":0>2.0f}_noise_decrease_{"
  1287. ":0>2.0f}_neuron_id_{"
  1288. ":d}.png".format(
  1289. preferred_polar-preferred_circular,
  1290. opposite_circular-opposite_polar, suggested_excitatory_neuron))
  1291. plot_polar_plot_inhibitory(traj, plot_run_names, selected_inhibitory_neuron)
  1292. for suggested_inhibitory_neuron in representative_inhibitory_neuron_indices:
  1293. polar_hdi = get_hdi(traj, run_name_dict["ellipsoid"], suggested_inhibitory_neuron, "in")
  1294. circular_hdi = get_hdi(traj, run_name_dict["circular"], suggested_inhibitory_neuron, "in")
  1295. plot_polar_plot_inhibitory(traj, plot_run_names, suggested_inhibitory_neuron,
  1296. figname=FIGURE_SAVE_PATH + "X_polar_plot_inhibitory_neuron_polarized_{"
  1297. ":.2f}_circular_{:.2f}_neuron_id_{"
  1298. ":d}.png".format(polar_hdi, circular_hdi,
  1299. suggested_inhibitory_neuron))
  1300. plot_firing_rate_similar_vs_diff_tuning(traj, plot_run_names)
  1301. plot_orientation_maps_diff_scales_with_ellipse(traj)
  1302. plot_exc_and_inh_hdi_over_simplex_grid_scale(traj, traj.f_get_run_names())
  1303. plot_exc_and_inh_hdi_over_fit_corr_len(traj, traj.f_get_run_names())
  1304. if not save_figs:
  1305. plt.show()
  1306. traj.f_restore_default()