paper_figures_orientation_map.py 73 KB

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