paper_figures_spatial_head_direction_network_perlin_map.py 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700
  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. labels = ['polar ', 'circ. ', 'no inh.']
  436. line_widths = [1.5, 1.5, 1]
  437. zorders = [10, 2, 1]
  438. max_rate = 0.0
  439. ax.plot([], [], color='white',label=' HDI')
  440. for run_idx, run_name in enumerate(plot_run_names):
  441. # label = traj.derived_parameters.runs[run_name].morphology.morph_label
  442. label = labels[run_idx]
  443. hdi = traj.results.runs[run_name].head_direction_indices[selected_neuron_idx]
  444. tuning_vectors = traj.results.runs[run_name].tuning_vectors
  445. rate_plot = [np.linalg.norm(v) for v in tuning_vectors[plot_n_idx]]
  446. run_max_rate = np.max(rate_plot)
  447. if run_max_rate > max_rate:
  448. max_rate = run_max_rate
  449. rate_plot.append(rate_plot[0])
  450. ax.plot(directions_plt, rate_plot, linewidth=line_widths[run_idx],
  451. label='{:s} {:.2f}'.format(short_labels(label), hdi),
  452. color=colors[run_idx], linestyle=line_styles[run_idx], zorder=zorders[run_idx])
  453. # ax.set_title('Firing Rate')
  454. # ax.plot([0.0, 0.0], [0.0, 1.05 * max_rate], color='red', alpha=0.25, linewidth=4.)
  455. # TODO: Set ticks for polar
  456. ticks = [40., 80.]
  457. ax.set_rgrids(ticks, labels=["{:.0f} Hz".format(ticklabel) if idx == len(ticks) - 1 else "" for idx, ticklabel in
  458. enumerate(ticks)], angle=60)
  459. ax.set_thetagrids([0, 90, 180, 270], labels=[])
  460. ax.xaxis.grid(linewidth=0.4)
  461. ax.yaxis.grid(linewidth=0.4)
  462. leg = ax.legend(loc="lower right", bbox_to_anchor=(1.15, -0.2), handlelength=1, fontsize="medium")
  463. leg.get_frame().set_linewidth(0.0)
  464. ax.axes.spines["polar"].set_visible(False)
  465. if save_figs:
  466. plt.savefig(figname)
  467. plt.close(fig)
  468. def plot_polar_plot_inhibitory(traj, plot_run_names, selected_neuron_idx, figname=FIGURE_SAVE_PATH +
  469. 'D_polar_plot_inhibitory.png'):
  470. directions = np.linspace(-np.pi, np.pi, traj.input.number_of_directions, endpoint=False)
  471. directions_plt = list(directions)
  472. directions_plt.append(directions[0])
  473. height = panel_size
  474. width = panel_size
  475. fig, ax = plt.subplots(1, 1, figsize=(height, width), subplot_kw=dict(projection='polar'))
  476. # head_direction_indices = traj.results.runs[plot_run_names[0]].inh_head_direction_indices
  477. # sorted_ids = np.argsort(head_direction_indices)
  478. # plot_n_idx = sorted_ids[-75]
  479. plot_n_idx = selected_neuron_idx
  480. line_styles = ['dotted', 'solid']
  481. colors = ['b', 'lightblue']
  482. labels = ['polar ', 'circ. ']
  483. line_widths = [1.5, 1.5]
  484. zorders = [10, 2]
  485. ax.plot([], [], color='white',label=' HDI')
  486. hdis = []
  487. for run_idx, run_name in enumerate(plot_run_names[:2]):
  488. # ax = axes[max_hdi_idx, run_idx]
  489. # label = traj.derived_parameters.runs[run_name].morphology.morph_label
  490. label = labels[run_idx]
  491. hdi = traj.results.runs[run_name].inh_head_direction_indices[selected_neuron_idx]
  492. hdis.append(hdi)
  493. tuning_vectors = traj.results.runs[run_name].inh_tuning_vectors
  494. rate_plot = [np.linalg.norm(v) for v in tuning_vectors[plot_n_idx]]
  495. rate_plot.append(rate_plot[0])
  496. ax.plot(directions_plt, rate_plot, linewidth=line_widths[run_idx],
  497. label='{:s} {:.2f}'.format(short_labels(label), hdi),
  498. color=colors[run_idx], linestyle=line_styles[run_idx], zorder=zorders[run_idx])
  499. # ax.set_title('Inh. Firing Rate')
  500. # TODO: Set ticks for polar
  501. # ticks = [np.round(max_rate / 3.), np.round(max_rate * 2. / 3.), np.round(max_rate)]
  502. ticks = [40., 80., 120.]
  503. ax.set_rgrids(ticks, labels=["{:.0f} Hz".format(ticklabel) if idx == len(ticks) - 1 else "" for idx, ticklabel in
  504. enumerate(ticks)], angle=60)
  505. ax.set_thetagrids([0, 90, 180, 270], labels=[])
  506. ax.xaxis.grid(linewidth=0.4)
  507. ax.yaxis.grid(linewidth=0.4)
  508. leg = ax.legend(loc="lower right", bbox_to_anchor=(1.15, -0.15), handlelength=1, fontsize="medium")
  509. leg.get_frame().set_linewidth(0.0)
  510. # hdi_box = ax.text(1.15, -0.15, 'HDI \n{:.2f} \n{:.2f}'.format(hdis[0], hdis[1]))
  511. ax.axes.spines["polar"].set_visible(False)
  512. if save_figs:
  513. plt.savefig(figname)
  514. plt.close(fig)
  515. def plot_hdi_over_corr_len(traj, plot_run_names):
  516. corr_len_expl = traj.f_get('correlation_length').f_get_range()
  517. seed_expl = traj.f_get('seed').f_get_range()
  518. label_expl = [traj.derived_parameters.runs[run_name].morphology.morph_label for run_name in traj.f_get_run_names()]
  519. label_range = set(label_expl)
  520. hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  521. hdi_frame.index.names = ["corr_len", "seed", "label"]
  522. for run_name, corr_len, seed, label in zip(plot_run_names, corr_len_expl, seed_expl, label_expl):
  523. ex_tunings = traj.results.runs[run_name].ex_tunings
  524. head_direction_indices = traj.results[run_name].head_direction_indices
  525. hdi_frame[corr_len, seed, label] = np.mean(head_direction_indices)
  526. # TODO: Standart deviation also for the population
  527. hdi_exc_n_and_seed_mean = hdi_frame.groupby(level=[0, 2]).mean()
  528. hdi_exc_n_and_seed_std_dev = hdi_frame.groupby(level=[0, 2]).std()
  529. # Ellipsoid markers
  530. rx, ry = 5., 12.
  531. # area = rx * ry * np.pi * 2.
  532. area = 1.
  533. theta = np.arange(0, 2 * np.pi + 0.01, 0.1)
  534. verts = np.column_stack([rx / area * np.cos(theta), ry / area * np.sin(theta)])
  535. style_dict = {
  536. NO_SYNAPSES: ['grey', 'dashed', '', 0],
  537. POLARIZED: ['blue', 'solid', verts, 10.],
  538. CIRCULAR: ['lightblue', 'solid', 'o', 8.]
  539. }
  540. # colors = ['blue', 'grey', 'lightblue']
  541. # linestyles = ['solid', 'dashed', 'solid']
  542. # markers = [verts, '', 'o']
  543. fig, ax = plt.subplots(1, 1)
  544. for label in label_range:
  545. hdi_mean = hdi_exc_n_and_seed_mean[:, label]
  546. hdi_std = hdi_exc_n_and_seed_std_dev[:, label]
  547. corr_len_range = hdi_mean.keys().to_numpy()
  548. col, lin, mar, mar_size = style_dict[label]
  549. ax.plot(corr_len_range, hdi_mean, label=label, marker=mar, color=col, linestyle=lin, markersize=mar_size)
  550. plt.fill_between(corr_len_range, hdi_mean - hdi_std,
  551. hdi_mean + hdi_std, alpha=0.4, color=col)
  552. ax.set_xlabel('Correlation length')
  553. ax.set_ylabel('Head Direction Index')
  554. ax.axvline(206.9, color='k', linewidth=0.5)
  555. ax.set_ylim(0.0, 1.0)
  556. ax.set_xlim(0.0, 400.)
  557. ax.legend()
  558. if save_figs:
  559. plt.savefig(FIGURE_SAVE_PATH + 'hdi_over_corr_len_scaled.png', dpi=200)
  560. plt.close(fig)
  561. def plot_hdi_histogram_excitatory(traj, plot_run_names):
  562. labels = []
  563. hdis = []
  564. colors = ['black', 'red', 'green']
  565. for run_idx, run_name in enumerate(plot_run_names):
  566. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  567. labels.append(label)
  568. head_direction_indices = traj.results.runs[run_name].head_direction_indices
  569. hdis.append(head_direction_indices)
  570. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  571. ax.hist(hdis, color=colors, label=labels, bins=30)
  572. for hdi, color in zip(hdis, colors):
  573. mean_hdi = np.mean(hdi)
  574. ax.axvline(mean_hdi, 0, 1, color=color, linestyle='--')
  575. ax.set_xlabel("HDI")
  576. ax.legend()
  577. fig.tight_layout()
  578. if save_figs:
  579. plt.savefig(FIGURE_SAVE_PATH + 'hdi_histogram_excitatory.png', dpi=200)
  580. plt.close(fig)
  581. def plot_hdi_violin_excitatory(traj, plot_run_names):
  582. labels = []
  583. hdis = []
  584. colors = ['black', 'red', 'green']
  585. no_conn_hdi = 0.
  586. for run_idx, run_name in enumerate(plot_run_names):
  587. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  588. head_direction_indices = traj.results.runs[run_name].head_direction_indices
  589. if label == NO_SYNAPSES:
  590. no_conn_hdi = np.mean(head_direction_indices)
  591. else:
  592. labels.append(label)
  593. hdis.append(sorted(head_direction_indices))
  594. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  595. # hdis = np.array(hdis)
  596. viol_plt = ax.violinplot(hdis, showmeans=True, showextrema=False)
  597. viol_plt['cmeans'].set_color('black')
  598. for pc in viol_plt['bodies']:
  599. pc.set_facecolor('red')
  600. pc.set_edgecolor('black')
  601. pc.set_alpha(0.7)
  602. ax.axhline(no_conn_hdi, color='black', linestyle='--')
  603. ax.annotate(NO_SYNAPSES, xy=(0.45, 0.48), xycoords='axes fraction')
  604. ax.set_xticks(np.arange(1, len(labels) + 1))
  605. ax.set_xticklabels(labels)
  606. ax.set_ylabel('HDI')
  607. fig.tight_layout()
  608. if save_figs:
  609. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_excitatory.png', dpi=200)
  610. plt.close(fig)
  611. def plot_hdi_violin_inhibitory(traj, plot_run_names):
  612. labels = []
  613. hdis = []
  614. colors = ['black', 'red']
  615. for run_idx, run_name in enumerate(plot_run_names):
  616. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  617. if label != NO_SYNAPSES:
  618. labels.append(label)
  619. head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  620. hdis.append(sorted(head_direction_indices))
  621. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  622. viol_plt = ax.violinplot(hdis, showmeans=True, showextrema=False)
  623. viol_plt['cmeans'].set_color('black')
  624. for pc in viol_plt['bodies']:
  625. pc.set_facecolor('blue')
  626. pc.set_edgecolor('black')
  627. pc.set_alpha(0.7)
  628. ax.set_xticks(np.arange(1, len(labels) + 1))
  629. ax.set_xticklabels(labels)
  630. ax.set_ylabel('HDI')
  631. fig.tight_layout()
  632. if save_figs:
  633. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_inhibitory.png', dpi=200)
  634. plt.close(fig)
  635. def plot_hdi_violin_combined(traj, plot_run_names):
  636. labels = []
  637. inh_hdis = []
  638. exc_hdis = []
  639. no_conn_hdi = 0.
  640. colors = ['black', 'red']
  641. for run_idx, run_name in enumerate(plot_run_names):
  642. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  643. if label != NO_SYNAPSES:
  644. labels.append(label)
  645. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  646. inh_hdis.append(sorted(inh_head_direction_indices))
  647. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  648. exc_hdis.append(sorted(exc_head_direction_indices))
  649. else:
  650. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  651. no_conn_hdi = np.mean(exc_head_direction_indices)
  652. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  653. inh_viol_plt = ax.violinplot(inh_hdis, showmeans=True, showextrema=False)
  654. # viol_plt['cmeans'].set_color('black')
  655. #
  656. # for pc in viol_plt['bodies']:
  657. # pc.set_facecolor('blue')
  658. # pc.set_edgecolor('black')
  659. # pc.set_alpha(0.7)
  660. for b in inh_viol_plt['bodies']:
  661. m = np.mean(b.get_paths()[0].vertices[:, 0])
  662. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], m, np.inf)
  663. b.set_color('b')
  664. exc_viol_plt = ax.violinplot(exc_hdis, showmeans=True, showextrema=False)
  665. for b in exc_viol_plt['bodies']:
  666. m = np.mean(b.get_paths()[0].vertices[:, 0])
  667. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], -np.inf, m)
  668. b.set_color('r')
  669. ax.axhline(no_conn_hdi, color='black', linestyle='--')
  670. ax.annotate(NO_SYNAPSES, xy=(0.45, 0.48), xycoords='axes fraction')
  671. ax.set_xticks(np.arange(1, len(labels) + 1))
  672. ax.set_xticklabels(labels)
  673. ax.set_ylabel('HDI')
  674. fig.tight_layout()
  675. if save_figs:
  676. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_combined.svg', dpi=200)
  677. plt.close(fig)
  678. def plot_hdi_violin_combined_and_overlayed(traj, plot_run_names, ex_polar_plot_id, in_polar_plot_id):
  679. labels = []
  680. inh_hdis = []
  681. exc_hdis = []
  682. no_conn_hdi = 0.
  683. in_polar_plot_hdi = []
  684. ex_polar_plot_hdi = []
  685. colors = ['black', 'red']
  686. for run_idx, run_name in enumerate(plot_run_names):
  687. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  688. if label != NO_SYNAPSES:
  689. labels.append(label)
  690. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  691. inh_hdis.append(sorted(inh_head_direction_indices))
  692. in_polar_plot_hdi.append(inh_head_direction_indices[in_polar_plot_id])
  693. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  694. exc_hdis.append(sorted(exc_head_direction_indices))
  695. ex_polar_plot_hdi.append(exc_head_direction_indices[ex_polar_plot_id])
  696. else:
  697. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  698. no_conn_hdi = np.mean(exc_head_direction_indices)
  699. ex_polar_plot_hdi.append(exc_head_direction_indices[ex_polar_plot_id])
  700. fig, ax = plt.subplots(1, 1, figsize=(3.5, 4.5))
  701. inh_ell_viol_plt = ax.violinplot(inh_hdis[0], showmeans=True, showextrema=False)
  702. for b in inh_ell_viol_plt['bodies']:
  703. m = np.mean(b.get_paths()[0].vertices[:, 0])
  704. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], m, np.inf)
  705. b.set_color('b')
  706. mean_line = inh_ell_viol_plt['cmeans']
  707. mean_line.set_color('b')
  708. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], m, np.inf)
  709. exc_ell_viol_plt = ax.violinplot(exc_hdis[0], showmeans=True, showextrema=False)
  710. for b in exc_ell_viol_plt['bodies']:
  711. m = np.mean(b.get_paths()[0].vertices[:, 0])
  712. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], m, np.inf)
  713. b.set_color('r')
  714. mean_line = exc_ell_viol_plt['cmeans']
  715. mean_line.set_color('r')
  716. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], m, np.inf)
  717. inh_cir_viol_plt = ax.violinplot(inh_hdis[1], showmeans=True, showextrema=False)
  718. for b in inh_cir_viol_plt['bodies']:
  719. m = np.mean(b.get_paths()[0].vertices[:, 0])
  720. b.get_paths()[0].vertices[:, 0] = np.clip(b.get_paths()[0].vertices[:, 0], -np.inf, m)
  721. b.set_color('b')
  722. mean_line = inh_cir_viol_plt['cmeans']
  723. mean_line.set_color('b')
  724. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], -np.inf, m)
  725. exc_cir_viol_plt = ax.violinplot(exc_hdis[1], showmeans=True, showextrema=False)
  726. for b in exc_cir_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], -np.inf, m)
  729. b.set_color('r')
  730. mean_line = exc_cir_viol_plt['cmeans']
  731. mean_line.set_color('r')
  732. mean_line.get_paths()[0].vertices[:, 0] = np.clip(mean_line.get_paths()[0].vertices[:, 0], -np.inf, m)
  733. ax.axhline(no_conn_hdi, 0.5, 1., color='black', linestyle='--')
  734. ax.axvline(1.0, color='k')
  735. ax.annotate(NO_SYNAPSES, xy=(0.75, 0.415), xycoords='axes fraction')
  736. ax.set_xlim(0.5, 1.5)
  737. ax.set_ylim(0.0, 1.0)
  738. ax.set_xticks([0.75, 1.25])
  739. ax.set_xticklabels([CIRCULAR, POLARIZED])
  740. ax.set_ylabel('HDI')
  741. fig.tight_layout()
  742. if save_figs:
  743. plt.savefig(FIGURE_SAVE_PATH + 'hdi_violin_combined_and_overlayed.svg', dpi=200)
  744. plt.close(fig)
  745. return ex_polar_plot_hdi, in_polar_plot_hdi
  746. def plot_hdi_histogram_combined_and_overlayed(traj, plot_run_names, ex_polar_plot_id, in_polar_plot_id, cut_off_dist):
  747. labels = []
  748. inh_hdis = []
  749. exc_hdis = []
  750. no_conn_hdi = 0.
  751. for run_idx, run_name in enumerate(plot_run_names):
  752. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  753. if label != NO_SYNAPSES:
  754. labels.append(normal_labels(label))
  755. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  756. inh_axonal_cloud = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  757. inh_cut_off_ids = (inh_axonal_cloud[:, 0] >= cut_off_dist) & \
  758. (inh_axonal_cloud[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  759. (inh_axonal_cloud[:, 1] >= cut_off_dist) & \
  760. (inh_axonal_cloud[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  761. # print(inh_positions)
  762. inh_hdis.append(sorted(inh_head_direction_indices[inh_cut_off_ids]))
  763. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  764. ex_positions = traj.results.runs[run_name].ex_positions
  765. # print(ex_positions)
  766. exc_cut_off_ids = (ex_positions[:, 0] >= cut_off_dist) & \
  767. (ex_positions[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  768. (ex_positions[:, 1] >= cut_off_dist) & \
  769. (ex_positions[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  770. exc_hdis.append(sorted(exc_head_direction_indices[exc_cut_off_ids]))
  771. else:
  772. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  773. no_conn_hdi = np.mean(exc_head_direction_indices)
  774. # Look for a representative excitatory neuron
  775. hdi_mean_dict = {}
  776. excitatory_hdi_means = [np.mean(hdis) for hdis in exc_hdis]
  777. hdi_mean_dict["polar_exc"] = excitatory_hdi_means[0]
  778. hdi_mean_dict["circular_exc"] = excitatory_hdi_means[1]
  779. inhibitory_hdi_means = [np.mean(hdis) for hdis in inh_hdis]
  780. hdi_mean_dict["polar_inh"] = inhibitory_hdi_means[0]
  781. hdi_mean_dict["circular_inh"] = inhibitory_hdi_means[1]
  782. # # fig = plt.figure(figsize=(3.5, 3.5))
  783. # # gs1 = gridspec.GridSpec(1, 2)
  784. #
  785. # fig = plt.figure(constrained_layout=True)
  786. # gs = gridspec.GridSpec(ncols=1, nrows=2, hspace=0.0, wspace=0.0, figure=fig)
  787. # # gs.update(wspace=0.0, hspace=0.0) # set the spacing between axes.
  788. # # f2_ax1 = fig.add_subplot(gs[0, 0])
  789. # # f2_ax2 = fig.add_subplot(gs[0, 1])
  790. # print(gs.get_subplot_params())
  791. width = 2 * panel_size
  792. height = 1.2 * panel_size
  793. fig, axes = plt.subplots(2, 1, figsize=(width, height))
  794. plt.subplots_adjust(wspace=0, hspace=0.1)
  795. bins = np.linspace(0.0, 1.0, 21, endpoint=True)
  796. max_density = 0
  797. for i in range(2):
  798. # i = i + 1 # grid spec indexes from 0
  799. # ax = fig.add_subplot(gs[i])
  800. ax = axes[i]
  801. density_e, _, _ = ax.hist(exc_hdis[i], color='r', edgecolor='r', alpha=0.3, bins=bins, density=True)
  802. density_i, _, _ = ax.hist(inh_hdis[i], color='b', edgecolor='b', alpha=0.3, bins=bins, density=True)
  803. max_density = np.max([max_density, np.max(density_e), np.max(density_i)])
  804. ax.axvline(np.mean(exc_hdis[i]), color='r')
  805. ax.axvline(np.mean(inh_hdis[i]), color='b')
  806. ax.axvline(no_conn_hdi, color='dimgrey', linestyle='--', linewidth=1.5)
  807. ax.set_ylabel(labels[i], rotation='vertical')
  808. # plt.axis('on')
  809. if i == 0:
  810. ax.set_xticklabels([])
  811. else:
  812. ax.set_xlabel('head direction index')
  813. remove_frame(ax, ["top", "right", "bottom"])
  814. max_density = 1.2 * max_density
  815. fig.subplots_adjust(left=0.2, right=0.95, bottom=0.2)
  816. axes[0].annotate('% cells', (0, 1.0), xycoords='axes fraction', va="bottom", ha="right")
  817. axes[1].annotate("no ihn.\n{:.2f}".format(no_conn_hdi), xy=(no_conn_hdi, max_density),
  818. xytext=(-2, 0), xycoords="data",
  819. textcoords="offset points",
  820. va="top", ha="right", color="dimgrey")
  821. for i, ax in enumerate(axes):
  822. ax.annotate("{:.2f}".format(np.mean(exc_hdis[i])), xy=(np.mean(exc_hdis[i]), max_density),
  823. xytext=(2, 0), xycoords="data",
  824. textcoords="offset points",
  825. va="top", ha="left", color="r")
  826. # i_ha = "left" if i == 1 else "right"
  827. # i_offset = 2 if i == 1 else -2
  828. i_ha = "right"
  829. i_offset = -1
  830. ax.annotate("{:.2f}".format(np.mean(inh_hdis[i])), xy=(np.mean(inh_hdis[i]), max_density),
  831. xytext=(i_offset, 0), xycoords="data",
  832. textcoords="offset points",
  833. va="top", ha=i_ha, color="b")
  834. for ax in axes:
  835. ax.set_ylim(0, max_density)
  836. # plt.annotate('probability density', (-0.2,1.5), xycoords='axes fraction', rotation=90, fontsize=18)
  837. if save_figs:
  838. plt.savefig(FIGURE_SAVE_PATH + 'E_hdi_histogram_combined_and_overlayed_cutoff_{}um.png'.format(cut_off_dist))
  839. plt.close(fig)
  840. return hdi_mean_dict
  841. def get_neurons_with_given_hdi(polar_hdi, circular_hdi, max_number_of_suggestions, plot_run_names, traj, type):
  842. polar_run_name = plot_run_names[0]
  843. circular_run_name = plot_run_names[1]
  844. polar_ex_hdis = traj.results.runs[polar_run_name].head_direction_indices if type == "ex" else traj.results.runs[
  845. polar_run_name].inh_head_direction_indices
  846. circular_ex_hdis = traj.results.runs[circular_run_name].head_direction_indices if type == "ex" else \
  847. traj.results.runs[
  848. polar_run_name].inh_head_direction_indices
  849. neuron_indices = get_indices_of_closest_values(polar_ex_hdis, polar_hdi,
  850. circular_ex_hdis,
  851. circular_hdi, 0.1 * np.abs(
  852. polar_hdi - circular_hdi), max_number_of_suggestions)
  853. return neuron_indices
  854. def get_indices_of_closest_values(first_list, first_value, second_list, second_value, absolute_tolerance_list_one,
  855. number_of_indices):
  856. is_close_in_list_one = np.abs(first_list - first_value) < absolute_tolerance_list_one
  857. indices_close_in_list_one = np.where(is_close_in_list_one)[0]
  858. indices_closest_in_list_two = indices_close_in_list_one[np.argpartition(np.abs(second_list[
  859. indices_close_in_list_one] - second_value),
  860. number_of_indices)]
  861. return indices_closest_in_list_two[:number_of_indices]
  862. def plot_hdi_histogram_inhibitory(traj, plot_run_names, in_polar_plot_id):
  863. labels = []
  864. hdis = []
  865. colors = ['black', 'red']
  866. for run_idx, run_name in enumerate(plot_run_names):
  867. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  868. if label != NO_SYNAPSES:
  869. labels.append(label)
  870. head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  871. print('inh {}: {}'.format(label, head_direction_indices[in_polar_plot_id]))
  872. hdis.append(head_direction_indices)
  873. fig, ax = plt.subplots(1, 1, figsize=(6, 3))
  874. ax.hist(hdis, color=colors, label=labels, bins=30)
  875. for hdi, color in zip(hdis, colors):
  876. mean_hdi = np.mean(hdi)
  877. ax.axvline(mean_hdi, 0, 1, color=color, linestyle='--')
  878. ax.set_xlabel("HDI")
  879. ax.legend()
  880. fig.tight_layout()
  881. if save_figs:
  882. plt.savefig(FIGURE_SAVE_PATH + 'hdi_histogram_inhibitory.png', dpi=200)
  883. plt.close(fig)
  884. def filter_run_names_by_par_dict(traj, par_dict):
  885. run_name_list = []
  886. for run_idx, run_name in enumerate(traj.f_get_run_names()):
  887. traj.f_set_crun(run_name)
  888. paramters_equal = True
  889. for key, val in par_dict.items():
  890. if (traj.par[key] != val):
  891. paramters_equal = False
  892. if paramters_equal:
  893. run_name_list.append(run_name)
  894. traj.f_restore_default()
  895. return run_name_list
  896. def plot_exc_and_inh_hdi_over_simplex_grid_scale(traj, plot_run_names, cut_off_dist):
  897. corr_len_expl = traj.f_get('correlation_length').f_get_range()
  898. seed_expl = traj.f_get('seed').f_get_range()
  899. label_expl = [traj.derived_parameters.runs[run_name].morphology.morph_label for run_name in traj.f_get_run_names()]
  900. label_range = set(label_expl)
  901. exc_hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  902. exc_hdi_frame.index.names = ["corr_len", "seed", "label"]
  903. inh_hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  904. inh_hdi_frame.index.names = ["corr_len", "seed", "label"]
  905. for run_name, corr_len, seed, label in zip(plot_run_names, corr_len_expl, seed_expl, label_expl):
  906. ex_tunings = traj.results.runs[run_name].ex_tunings
  907. inh_hdis = []
  908. exc_hdis = []
  909. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  910. inh_axonal_cloud = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  911. inh_cut_off_ids = (inh_axonal_cloud[:, 0] >= cut_off_dist) & \
  912. (inh_axonal_cloud[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  913. (inh_axonal_cloud[:, 1] >= cut_off_dist) & \
  914. (inh_axonal_cloud[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  915. inh_hdis.append(sorted(inh_head_direction_indices[inh_cut_off_ids]))
  916. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  917. ex_positions = traj.results.runs[run_name].ex_positions
  918. exc_cut_off_ids = (ex_positions[:, 0] >= cut_off_dist) & \
  919. (ex_positions[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  920. (ex_positions[:, 1] >= cut_off_dist) & \
  921. (ex_positions[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  922. exc_hdis.append(sorted(exc_head_direction_indices[exc_cut_off_ids]))
  923. exc_hdi_frame[corr_len, seed, label] = np.mean(exc_hdis)
  924. inh_hdi_frame[corr_len, seed, label] = np.mean(inh_hdis)
  925. # TODO: Standard deviation also for the population
  926. exc_hdi_n_and_seed_mean = exc_hdi_frame.groupby(level=[0, 2]).mean()
  927. exc_hdi_n_and_seed_std_dev = exc_hdi_frame.groupby(level=[0, 2]).std()
  928. inh_hdi_n_and_seed_mean = inh_hdi_frame.groupby(level=[0, 2]).mean()
  929. inh_hdi_n_and_seed_std_dev = inh_hdi_frame.groupby(level=[0, 2]).std()
  930. markersize = 4.
  931. exc_style_dict = {
  932. NO_SYNAPSES: ['dimgrey', 'dashed', '', 0],
  933. POLARIZED: ['red', 'solid', '^', markersize],
  934. CIRCULAR: ['lightsalmon', 'solid', '^', markersize]
  935. }
  936. inh_style_dict = {
  937. NO_SYNAPSES: ['dimgrey', 'dashed', '', 0],
  938. POLARIZED: ['blue', 'solid', 'o', markersize],
  939. CIRCULAR: ['lightblue', 'solid', 'o', markersize]
  940. }
  941. # colors = ['blue', 'grey', 'lightblue']
  942. # linestyles = ['solid', 'dashed', 'solid']
  943. # markers = [verts, '', 'o']
  944. # corr_len_fit_dict = correlation_length_fit_dict(traj, load=True)
  945. width = 2 * panel_size
  946. height = 1.2 * panel_size
  947. fig, ax = plt.subplots(1, 1, figsize=(width, height))
  948. for label in sorted(label_range, reverse=True):
  949. if label == NO_SYNAPSES:
  950. no_conn_hdi = exc_hdi_n_and_seed_mean[1, label]
  951. ax.axhline(no_conn_hdi, color='grey', linestyle='--')
  952. ax.annotate(short_labels(label), xy=(1.0, no_conn_hdi), xytext=(0, -2), xycoords='axes fraction',
  953. textcoords="offset points",
  954. va="top", \
  955. ha="right",
  956. color="dimgrey")
  957. continue
  958. exc_hdi_mean = exc_hdi_n_and_seed_mean[:, label]
  959. exc_hdi_std = exc_hdi_n_and_seed_std_dev[:, label]
  960. inh_hdi_mean = inh_hdi_n_and_seed_mean[:, label]
  961. inh_hdi_std = inh_hdi_n_and_seed_std_dev[:, label]
  962. corr_len_range = exc_hdi_mean.keys().to_numpy()
  963. print(label)
  964. for corr_len, ex_hdi, in_hdi in zip(corr_len_range, exc_hdi_mean, inh_hdi_mean):
  965. print("length: {:.2f} um, ex hdi: {:.2f} and in hdi {:.2f}".format(corr_len, ex_hdi, in_hdi))
  966. exc_col, exc_lin, exc_mar, exc_mar_size = exc_style_dict[label]
  967. inh_col, inh_lin, inh_mar, inh_mar_size = inh_style_dict[label]
  968. simplex_grid_scale = corr_len_range * np.sqrt(2)
  969. ax.plot(simplex_grid_scale, exc_hdi_mean, label='exc., ' + label, marker=exc_mar, color=exc_col, linestyle=exc_lin,
  970. markersize=exc_mar_size, alpha=0.5)
  971. plt.fill_between(simplex_grid_scale, exc_hdi_mean - exc_hdi_std,
  972. exc_hdi_mean + exc_hdi_std, alpha=0.3, color=exc_col)
  973. ax.plot(simplex_grid_scale, inh_hdi_mean, label='inh., ' + label, marker=inh_mar, color=inh_col, linestyle=inh_lin,
  974. markersize=inh_mar_size, alpha=0.5)
  975. plt.fill_between(simplex_grid_scale, inh_hdi_mean - inh_hdi_std,
  976. inh_hdi_mean + inh_hdi_std, alpha=0.3, color=inh_col)
  977. ax.set_xlabel('simplex grid scale')
  978. ax.set_ylabel('HDI')
  979. ax.axvline(get_closest_correlation_length(traj, 200.0) * np.sqrt(2), color='k', linewidth=0.5, zorder=0)
  980. ax.set_ylim(0.0, 1.0)
  981. # ax.set_xlim(0.0, np.max(corr_len_range))
  982. remove_frame(ax, ["right", "top"])
  983. tablelegend(ax, ncol=2, bbox_to_anchor=(1.1, 1.1), loc="upper right",
  984. row_labels=None,
  985. col_labels=[short_labels(label) for label in sorted(label_range - {"no conn"}, reverse=True)],
  986. title_label='', borderaxespad=0, handlelength=2, edgecolor='white')
  987. fig.subplots_adjust(bottom=0.2, left=0.2)
  988. # plt.legend()
  989. if save_figs:
  990. plt.savefig(FIGURE_SAVE_PATH + 'F_hdi_over_grid_scale.png')
  991. plt.close(fig)
  992. def plot_exc_and_inh_hdi_over_fit_corr_len(traj, plot_run_names, cut_off_dist):
  993. corr_len_expl = traj.f_get('correlation_length').f_get_range()
  994. seed_expl = traj.f_get('seed').f_get_range()
  995. label_expl = [traj.derived_parameters.runs[run_name].morphology.morph_label for run_name in traj.f_get_run_names()]
  996. label_range = set(label_expl)
  997. exc_hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  998. exc_hdi_frame.index.names = ["corr_len", "seed", "label"]
  999. inh_hdi_frame = pd.Series(index=[corr_len_expl, seed_expl, label_expl])
  1000. inh_hdi_frame.index.names = ["corr_len", "seed", "label"]
  1001. for run_name, corr_len, seed, label in zip(plot_run_names, corr_len_expl, seed_expl, label_expl):
  1002. ex_tunings = traj.results.runs[run_name].ex_tunings
  1003. inh_hdis = []
  1004. exc_hdis = []
  1005. inh_head_direction_indices = traj.results.runs[run_name].inh_head_direction_indices
  1006. inh_axonal_cloud = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  1007. inh_cut_off_ids = (inh_axonal_cloud[:, 0] >= cut_off_dist) & \
  1008. (inh_axonal_cloud[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  1009. (inh_axonal_cloud[:, 1] >= cut_off_dist) & \
  1010. (inh_axonal_cloud[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  1011. inh_hdis.append(sorted(inh_head_direction_indices[inh_cut_off_ids]))
  1012. exc_head_direction_indices = traj.results.runs[run_name].head_direction_indices
  1013. ex_positions = traj.results.runs[run_name].ex_positions
  1014. exc_cut_off_ids = (ex_positions[:, 0] >= cut_off_dist) & \
  1015. (ex_positions[:, 0] <= traj.parameters.map.sheet_size - cut_off_dist) & \
  1016. (ex_positions[:, 1] >= cut_off_dist) & \
  1017. (ex_positions[:, 1] <= traj.parameters.map.sheet_size - cut_off_dist)
  1018. exc_hdis.append(sorted(exc_head_direction_indices[exc_cut_off_ids]))
  1019. exc_hdi_frame[corr_len, seed, label] = np.mean(exc_hdis)
  1020. inh_hdi_frame[corr_len, seed, label] = np.mean(inh_hdis)
  1021. # TODO: Standard deviation also for the population
  1022. exc_hdi_n_and_seed_mean = exc_hdi_frame.groupby(level=[0, 2]).mean()
  1023. exc_hdi_n_and_seed_std_dev = exc_hdi_frame.groupby(level=[0, 2]).std()
  1024. inh_hdi_n_and_seed_mean = inh_hdi_frame.groupby(level=[0, 2]).mean()
  1025. inh_hdi_n_and_seed_std_dev = inh_hdi_frame.groupby(level=[0, 2]).std()
  1026. markersize = 4.
  1027. exc_style_dict = {
  1028. NO_SYNAPSES: ['dimgrey', 'dashed', '', 0],
  1029. POLARIZED: ['red', 'solid', '^', markersize],
  1030. CIRCULAR: ['lightsalmon', 'solid', '^', markersize]
  1031. }
  1032. inh_style_dict = {
  1033. NO_SYNAPSES: ['dimgrey', 'dashed', '', 0],
  1034. POLARIZED: ['blue', 'solid', 'o', markersize],
  1035. CIRCULAR: ['lightblue', 'solid', 'o', markersize]
  1036. }
  1037. # colors = ['blue', 'grey', 'lightblue']
  1038. # linestyles = ['solid', 'dashed', 'solid']
  1039. # markers = [verts, '', 'o']
  1040. corr_len_fit_dict = correlation_length_fit_dict(traj, map_type='perlin', load=True)
  1041. width = 2 * panel_size
  1042. height = 1.2 * panel_size
  1043. fig, ax = plt.subplots(1, 1, figsize=(width, height))
  1044. for label in sorted(label_range, reverse=True):
  1045. if label == NO_SYNAPSES:
  1046. no_conn_hdi = exc_hdi_n_and_seed_mean[1, label]
  1047. ax.axhline(no_conn_hdi, color='grey', linestyle='--')
  1048. ax.annotate(short_labels(label), xy=(1.0, no_conn_hdi), xytext=(0, -2), xycoords='axes fraction',
  1049. textcoords="offset points",
  1050. va="top", \
  1051. ha="right",
  1052. color="dimgrey")
  1053. continue
  1054. exc_hdi_mean = exc_hdi_n_and_seed_mean[:, label]
  1055. exc_hdi_std = exc_hdi_n_and_seed_std_dev[:, label]
  1056. inh_hdi_mean = inh_hdi_n_and_seed_mean[:, label]
  1057. inh_hdi_std = inh_hdi_n_and_seed_std_dev[:, label]
  1058. corr_len_range = exc_hdi_mean.keys().to_numpy()
  1059. print(label)
  1060. for corr_len, ex_hdi, in_hdi in zip(corr_len_range, exc_hdi_mean, inh_hdi_mean):
  1061. print("length: {:.2f} um, ex hdi: {:.2f} and in hdi {:.2f}".format(corr_len, ex_hdi, in_hdi))
  1062. exc_col, exc_lin, exc_mar, exc_mar_size = exc_style_dict[label]
  1063. inh_col, inh_lin, inh_mar, inh_mar_size = inh_style_dict[label]
  1064. fit_corr_len = [corr_len_fit_dict[corr_len] for corr_len in corr_len_range]
  1065. print(corr_len_range)
  1066. print(fit_corr_len)
  1067. ax.plot(fit_corr_len, exc_hdi_mean, label='exc., ' + label, marker=exc_mar, color=exc_col, linestyle=exc_lin,
  1068. markersize=exc_mar_size, alpha=0.5)
  1069. plt.fill_between(fit_corr_len, exc_hdi_mean - exc_hdi_std,
  1070. exc_hdi_mean + exc_hdi_std, alpha=0.3, color=exc_col)
  1071. ax.plot(fit_corr_len, inh_hdi_mean, label='inh., ' + label, marker=inh_mar, color=inh_col, linestyle=inh_lin,
  1072. markersize=inh_mar_size, alpha=0.5)
  1073. plt.fill_between(fit_corr_len, inh_hdi_mean - inh_hdi_std,
  1074. inh_hdi_mean + inh_hdi_std, alpha=0.3, color=inh_col)
  1075. ax.set_xlabel('correlation length')
  1076. ax.set_ylabel('HDI')
  1077. ax.axvline(corr_len_fit_dict[get_closest_correlation_length(traj, 200.0)], color='k', linewidth=0.5, zorder=0)
  1078. ax.set_ylim(0.0, 1.0)
  1079. # ax.set_xlim(0.0, np.max(corr_len_range))
  1080. remove_frame(ax, ["right", "top"])
  1081. tablelegend(ax, ncol=2, bbox_to_anchor=(1.1, 1.1), loc="upper right",
  1082. row_labels=None,
  1083. col_labels=[short_labels(label) for label in sorted(label_range - {"no conn"}, reverse=True)],
  1084. title_label='', borderaxespad=0, handlelength=2, edgecolor='white')
  1085. fig.subplots_adjust(bottom=0.2, left=0.2)
  1086. # plt.legend()
  1087. if save_figs:
  1088. plt.savefig(FIGURE_SAVE_PATH + 'F_hdi_over_corr_len_scaled.png')
  1089. plt.close(fig)
  1090. def plot_in_degree_map(traj, plot_run_names):
  1091. n_ex = int(np.sqrt(traj.N_E))
  1092. max_degree = 0
  1093. for run_name in plot_run_names:
  1094. ie_adjacency = traj.results.runs[run_name].ie_adjacency
  1095. exc_degree = np.sum(ie_adjacency, axis=0)
  1096. run_max_degree = np.max(exc_degree)
  1097. if run_max_degree > max_degree:
  1098. max_degree = run_max_degree
  1099. fig, axes = plt.subplots(1, 2, figsize=(9., 4.5))
  1100. for ax, run_name in zip(axes, plot_run_names[:-1]):
  1101. traj.f_set_crun(run_name)
  1102. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  1103. X, Y = get_position_mesh(traj.results.runs[run_name].ex_positions)
  1104. number_of_excitatory_neurons_per_row = int(np.sqrt(traj.N_E))
  1105. ie_adjacency = traj.results.runs[run_name].ie_adjacency
  1106. exc_degree = np.sum(ie_adjacency, axis=0)
  1107. c = ax.pcolor(X, Y, np.reshape(exc_degree, (number_of_excitatory_neurons_per_row,
  1108. number_of_excitatory_neurons_per_row)), vmin=0, vmax=max_degree,
  1109. cmap='hot')
  1110. ax.set_title(label)
  1111. fig.colorbar(c, ax=ax, label="in/out-degree")
  1112. fig.suptitle('in/out-degree', fontsize=16)
  1113. traj.f_restore_default()
  1114. if save_figs:
  1115. plt.savefig(FIGURE_SAVE_PATH + 'in_degree_map.png', dpi=200)
  1116. plt.close(fig)
  1117. def plot_spatial_hdi_map(traj, plot_run_names):
  1118. max_val = 0
  1119. for run_name in plot_run_names:
  1120. hdis = traj.results.runs[run_name].head_direction_indices
  1121. run_max_val = np.max(hdis)
  1122. if run_max_val > max_val:
  1123. max_val = run_max_val
  1124. fig, axes = plt.subplots(1, 3, figsize=(13.5, 4.5))
  1125. for ax, run_name in zip(axes, plot_run_names):
  1126. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  1127. positions = traj.results.runs[run_name].ex_positions
  1128. head_direction_indices = traj.results[run_name].head_direction_indices
  1129. print('Mean {}-HDI = {}'.format(label, np.mean(head_direction_indices)))
  1130. c = plot_hdi_in_space(ax, positions, head_direction_indices, max_val)
  1131. ax.set_title(label)
  1132. fig.colorbar(c, ax=ax, label="HDI")
  1133. fig.suptitle('spatial HDI map', fontsize=16)
  1134. if save_figs:
  1135. plt.savefig(FIGURE_SAVE_PATH + 'spatial_hdi_map.png', dpi=200)
  1136. plt.close(fig)
  1137. def plot_exc_spatial_hdi_map(traj, plot_run_names):
  1138. max_val = 0
  1139. for run_name in plot_run_names:
  1140. hdis = traj.results.runs[run_name].head_direction_indices
  1141. run_max_val = np.max(hdis)
  1142. if run_max_val > max_val:
  1143. max_val = run_max_val
  1144. fig, axes = plt.subplots(1, 3, figsize=(13.5, 4.5))
  1145. for ax, run_name in zip(axes, plot_run_names):
  1146. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  1147. positions = traj.results.runs[run_name].ex_positions
  1148. head_direction_indices = traj.results[run_name].head_direction_indices
  1149. print('Mean {}-HDI = {}'.format(label, np.mean(head_direction_indices)))
  1150. c = plot_hdi_in_space(ax, positions, head_direction_indices, max_val)
  1151. ax.set_title(label)
  1152. fig.colorbar(c, ax=ax, label="HDI")
  1153. fig.suptitle('spatial exc. HDI map', fontsize=16)
  1154. if save_figs:
  1155. plt.savefig(FIGURE_SAVE_PATH + 'spatial_exc_hdi_map.png', dpi=200)
  1156. plt.close(fig)
  1157. def plot_inh_spatial_hdi_map(traj, plot_run_names):
  1158. max_val = 0
  1159. for run_name in plot_run_names:
  1160. hdis = traj.results.runs[run_name].inh_head_direction_indices
  1161. run_max_val = np.max(hdis)
  1162. if run_max_val > max_val:
  1163. max_val = run_max_val
  1164. fig, axes = plt.subplots(1, 3, figsize=(13.5, 4.5))
  1165. for ax, run_name in zip(axes, plot_run_names):
  1166. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  1167. ax_cloud = traj.results.runs[run_name].inhibitory_axonal_cloud_array
  1168. positions = [[x, y] for x, y, phi in ax_cloud]
  1169. head_direction_indices = traj.results[run_name].inh_head_direction_indices
  1170. print('Mean {}-HDI = {}'.format(label, np.mean(head_direction_indices)))
  1171. c = plot_hdi_in_space(ax, positions, head_direction_indices, max_val)
  1172. ax.set_title(label)
  1173. fig.colorbar(c, ax=ax, label="HDI")
  1174. fig.suptitle('spatial inh. HDI map', fontsize=16)
  1175. if save_figs:
  1176. plt.savefig(FIGURE_SAVE_PATH + 'spatial_inh_hdi_map.png', dpi=200)
  1177. plt.close(fig)
  1178. def get_phase_difference(total_difference):
  1179. """
  1180. Map accumulated phase difference to shortest possible difference
  1181. :param total_difference:
  1182. :return: relative_difference
  1183. """
  1184. return (total_difference + np.pi) % (2 * np.pi) - np.pi
  1185. def plot_firing_rate_similar_vs_diff_tuning(traj, plot_run_names):
  1186. # The plot that Imre wanted
  1187. n_bins = traj.parameters.input.number_of_directions
  1188. fig, ax = plt.subplots(1, 1, figsize=(9, 9))
  1189. dir_bins = np.linspace(-np.pi, np.pi, n_bins + 1)
  1190. print(dir_bins)
  1191. plot_fr_array = []
  1192. labels = []
  1193. similarity_threshold = np.pi / 6.
  1194. directions = np.linspace(-np.pi, np.pi, traj.input.number_of_directions, endpoint=False)
  1195. for run_idx, run_name in enumerate(plot_run_names):
  1196. label = traj.derived_parameters.runs[run_name].morphology.morph_label
  1197. labels.append(label)
  1198. fr_similar_tunings = []
  1199. fr_different_tunings = []
  1200. ex_tunings = traj.results.runs[run_name].ex_tunings
  1201. firing_rate_array = traj.results[run_name].firing_rate_array
  1202. for tuning, firing_rates in zip(ex_tunings, firing_rate_array):
  1203. for idx, dir in enumerate(directions):
  1204. if np.abs(get_phase_difference(tuning - dir)) <= similarity_threshold:
  1205. fr_similar_tunings.append(firing_rates[idx])
  1206. elif np.abs(get_phase_difference(tuning + np.pi - dir)) <= similarity_threshold:
  1207. fr_different_tunings.append(firing_rates[idx])
  1208. plot_fr_array.append([np.mean(fr_similar_tunings), np.mean(fr_different_tunings)])
  1209. x = np.arange(3) # the label locations
  1210. width = 0.35 # the width of the bars
  1211. plot_fr_array = np.array(plot_fr_array)
  1212. rects1 = ax.bar(x - width / 2, plot_fr_array[:, 0], width,
  1213. label='theta pref +/- {}°'.format(np.round(similarity_threshold / np.pi * 180)))
  1214. rects2 = ax.bar(x + width / 2, plot_fr_array[:, 1], width,
  1215. label='theta pref + 180° +/- {}°'.format(np.round(similarity_threshold / np.pi * 180)))
  1216. ax.set_xticks(x)
  1217. ax.set_xticklabels(labels)
  1218. ax.set_title('Mean firing rate for tunings similar and different to input')
  1219. ax.set_ylabel('Mean firing rate')
  1220. ax.legend()
  1221. def autolabel(rects):
  1222. """Attach a text label above each bar in *rects*, displaying its height."""
  1223. for rect in rects:
  1224. height = rect.get_height()
  1225. ax.annotate('{}'.format(np.round(height)),
  1226. xy=(rect.get_x() + rect.get_width() / 2, height),
  1227. xytext=(0, 3), # 3 points vertical offset
  1228. textcoords="offset points",
  1229. ha='center', va='bottom')
  1230. autolabel(rects1)
  1231. autolabel(rects2)
  1232. fig.tight_layout()
  1233. if save_figs:
  1234. plt.savefig(FIGURE_SAVE_PATH + 'firing_rate_similar_vs_diff_tuning.png', dpi=200)
  1235. plt.close(fig)
  1236. def get_firing_rates_along_preferred_axis(traj, run_name, neuron_idx):
  1237. firing_rates = traj.results[run_name].firing_rate_array[neuron_idx, :]
  1238. tuning = traj.results[run_name].ex_tunings[neuron_idx]
  1239. anti_tuning = tuning + np.pi if tuning + np.pi < np.pi else tuning - np.pi
  1240. tuning_idx = np.argmin(np.abs(directions - tuning))
  1241. anti_tuning_idx = np.argmin(np.abs(directions - anti_tuning))
  1242. firing_at_the_preferred_direction = firing_rates[tuning_idx]
  1243. firing_at_the_opposite_direction = firing_rates[anti_tuning_idx]
  1244. return firing_at_the_preferred_direction, firing_at_the_opposite_direction
  1245. def get_hdi(traj, run_name, neuron_idx, type):
  1246. return traj.results.runs[run_name].head_direction_indices[neuron_idx] if type=="ex" else traj.results.runs[
  1247. run_name].inh_head_direction_indices[neuron_idx]
  1248. if __name__ == "__main__":
  1249. traj = Trajectory(TRAJ_NAME, add_time=False, dynamic_imports=Brian2MonitorResult)
  1250. NO_LOADING = 0
  1251. FULL_LOAD = 2
  1252. traj.f_load(filename=os.path.join(DATA_FOLDER, TRAJ_NAME + ".hdf5"), load_parameters=FULL_LOAD,
  1253. load_results=NO_LOADING)
  1254. traj.v_auto_load = True
  1255. save_figs = True
  1256. print("# Plotting script polarized interneurons")
  1257. print()
  1258. map_length_scale = 200.0
  1259. map_seed = 1
  1260. exemplary_head_direction = 0
  1261. # corr_len_fit_dict = correlation_length_fit_dict(traj, map_type='perlin', load=True)
  1262. # plt.plot(corr_len_fit_dict.keys(),corr_len_fit_dict.values())
  1263. # plt.show()
  1264. # abbrechen
  1265. print("## Map specifications")
  1266. print("\tcorrelation length: {:.1f} um".format(map_length_scale))
  1267. print("\tmap seed: {:d}".format(map_seed))
  1268. print()
  1269. print("## Input specification")
  1270. print("\tselected head direction: {:.0f}°".format(exemplary_head_direction))
  1271. print()
  1272. print("## Selected simulations")
  1273. plot_corr_len = get_closest_correlation_length(traj, map_length_scale)
  1274. par_dict = {'seed': map_seed, 'correlation_length': plot_corr_len}
  1275. plot_run_names = filter_run_names_by_par_dict(traj, par_dict)
  1276. run_name_dict = {}
  1277. for run_name in plot_run_names:
  1278. traj.f_set_crun(run_name)
  1279. run_name_dict[traj.derived_parameters.runs[run_name].morphology.morph_label] = run_name
  1280. for network_type, run_name in run_name_dict.items():
  1281. print("{:s}: {:s}".format(network_type, run_name))
  1282. directions = get_input_head_directions(traj)
  1283. direction_idx = np.argmin(np.abs(np.array(directions) - np.deg2rad(exemplary_head_direction)))
  1284. selected_neuron_excitatory = 1052
  1285. selected_inhibitory_neuron = 28
  1286. print("## Figure specification")
  1287. print("\tpanel size: {:.2f} cm".format(panel_size * cm_per_inch))
  1288. print()
  1289. #
  1290. plot_colorbar(figsize=(0.8 * panel_size, 0.8 * panel_size), figname=FIGURE_SAVE_PATH + "A_i_colormap.svg")
  1291. plot_input_map(traj, run_name_dict[POLARIZED], figname="A_i_exemplary_input_map.png",
  1292. figsize=(panel_size, panel_size))
  1293. plot_axonal_clouds(traj, plot_run_names)
  1294. #
  1295. plot_firing_rate_map_excitatory(traj, direction_idx, plot_run_names, selected_neuron_excitatory)
  1296. in_max_rate = plot_firing_rate_map_inhibitory(traj, direction_idx, plot_run_names, selected_inhibitory_neuron)
  1297. #
  1298. hdi_means = plot_hdi_histogram_combined_and_overlayed(
  1299. traj, plot_run_names,
  1300. selected_neuron_excitatory,
  1301. selected_inhibitory_neuron,
  1302. cut_off_dist=100.)
  1303. #
  1304. number_of_suggestions = 20
  1305. representative_excitatory_neuron_indices = get_neurons_with_given_hdi(hdi_means["polar_exc"], hdi_means[
  1306. "circular_exc"],
  1307. number_of_suggestions, plot_run_names,
  1308. traj, "ex")
  1309. representative_inhibitory_neuron_indices = get_neurons_with_given_hdi(hdi_means["polar_inh"],
  1310. hdi_means["circular_inh"],
  1311. number_of_suggestions, plot_run_names,
  1312. traj, "in")
  1313. plot_polar_plot_excitatory(traj, plot_run_names, selected_neuron_excitatory)
  1314. for suggested_excitatory_neuron in representative_excitatory_neuron_indices:
  1315. preferred_polar, opposite_polar = get_firing_rates_along_preferred_axis(
  1316. traj, run_name_dict["ellipsoid"], suggested_excitatory_neuron)
  1317. preferred_circular, opposite_circular = get_firing_rates_along_preferred_axis(
  1318. traj, run_name_dict["circular"], suggested_excitatory_neuron)
  1319. plot_polar_plot_excitatory(traj, plot_run_names, suggested_excitatory_neuron,
  1320. figname=FIGURE_SAVE_PATH + "X_polar_plot_excitatory_neuron_signal_increase_{"
  1321. ":0>2.0f}_noise_decrease_{"
  1322. ":0>2.0f}_neuron_id_{"
  1323. ":d}.png".format(
  1324. preferred_polar-preferred_circular,
  1325. opposite_circular-opposite_polar, suggested_excitatory_neuron))
  1326. plot_polar_plot_inhibitory(traj, plot_run_names, selected_inhibitory_neuron)
  1327. for suggested_inhibitory_neuron in representative_inhibitory_neuron_indices:
  1328. polar_hdi = get_hdi(traj, run_name_dict["ellipsoid"], suggested_inhibitory_neuron, "in")
  1329. circular_hdi = get_hdi(traj, run_name_dict["circular"], suggested_inhibitory_neuron, "in")
  1330. plot_polar_plot_inhibitory(traj, plot_run_names, suggested_inhibitory_neuron,
  1331. figname=FIGURE_SAVE_PATH + "X_polar_plot_inhibitory_neuron_polarized_{"
  1332. ":.2f}_circular_{:.2f}_neuron_id_{"
  1333. ":d}.png".format(polar_hdi, circular_hdi,
  1334. suggested_inhibitory_neuron))
  1335. plot_firing_rate_similar_vs_diff_tuning(traj, plot_run_names)
  1336. plot_orientation_maps_diff_scales_with_ellipse(traj)
  1337. plot_exc_and_inh_hdi_over_simplex_grid_scale(traj, traj.f_get_run_names(), cut_off_dist=100.)
  1338. plot_exc_and_inh_hdi_over_fit_corr_len(traj, traj.f_get_run_names(), cut_off_dist=100.)
  1339. if not save_figs:
  1340. plt.show()
  1341. traj.f_restore_default()