├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── figure_2.ipynb ├── figure_3.ipynb ├── requirements.in ├── requirements.txt └── src ├── classify_units.py ├── dataset.py ├── plot_utils.py └── scores.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # Distribution / packaging 7 | .Python 8 | build/ 9 | develop-eggs/ 10 | dist/ 11 | downloads/ 12 | eggs/ 13 | .eggs/ 14 | lib/ 15 | lib64/ 16 | parts/ 17 | sdist/ 18 | var/ 19 | wheels/ 20 | share/python-wheels/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | MANIFEST 25 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | # Pull Requests 4 | 5 | Please send in fixes or feature additions through Pull Requests. 6 | 7 | ## Contributor License Agreement 8 | 9 | Contributions to this project must be accompanied by a Contributor License 10 | Agreement. You (or your employer) retain the copyright to your contribution, 11 | this simply gives us permission to use and redistribute your contributions as 12 | part of the project. Head over to to see 13 | your current agreements on file or to sign a new one. 14 | 15 | You generally only need to submit a CLA once, so if you've already submitted one 16 | (even if it was for a different project), you probably don't need to do it 17 | again. 18 | 19 | ## Code reviews 20 | 21 | All submissions, including submissions by project members, require review. We 22 | use GitHub pull requests for this purpose. Consult 23 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 24 | information on using pull requests. 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The Spatial Memory Pipeline 2 | 3 | The Spatial Memory Pipeline [1] is a model that learns to map egocentric visual 4 | and velocity information into allocentric spatial representations. The 5 | representations learned by the model resemble head-direction, boundary-vector 6 | and place-cell responses found in the mammalian hippocampal formation. 7 | 8 | This directory contains notebooks that reproduce figures 2 and 3 in [1] based 9 | on the inputs, outputs and parameters of the trained model. These figures 10 | illustrate the types of representations learned by the model, as well as 11 | the properties of the learned head-direction network. 12 | 13 | ## Usage 14 | 15 | We provide one Colab notebook to reproduce each of figures 2 and 3 of [1]: 16 | 17 | * [Figure 2](https://colab.research.google.com/github/deepmind/spatial_memory_pipeline/blob/master/figure_2.ipynb): displaying the types and distribution of the 18 | spatial representations. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/deepmind/spatial_memory_pipeline/blob/master/figure_2.ipynb) 19 | 20 | * [Figure 3](https://colab.research.google.com/github/deepmind/spatial_memory_pipeline/blob/master/figure_3.ipynb): analyzing the trained head-direction cell network. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/deepmind/spatial_memory_pipeline/blob/master/figure_3.ipynb) 21 | 22 | ## References 23 | 24 | [1] Benigno Uria, Borja Ibarz, Andrea Banino, Vinicius Zambaldi, 25 | Dharshan Kumaran, Demis Hassabis, Caswell Barry, Charles Blundell. 26 | *The Spatial Memory Pipeline: a model of egocentric to allocentric 27 | understanding in mammalian brains*. [bioRxiv 2020.11.11.378141](https://www.biorxiv.org/content/10.1101/2020.11.11.378141v2) 28 | 29 | ## Disclaimer 30 | 31 | Copyright 2022 DeepMind Technologies Limited 32 | 33 | All software is licensed under the Apache License, Version 2.0 (Apache 2.0); you may not use this file except in compliance with the License. You may obtain a copy of the Apache 2.0 license at: https://www.apache.org/licenses/LICENSE-2.0 34 | 35 | All other materials are licensed under the Creative Commons Attribution 4.0 International License (CC-BY). You may obtain a copy of the CC-BY license at: https://creativecommons.org/licenses/by/4.0/legalcode 36 | 37 | Unless required by applicable law or agreed to in writing, all software and materials distributed here under the Apache 2.0 or CC-BY licenses are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the licenses for the specific language governing permissions and limitations under those licenses. 38 | 39 | This is not an official Google product. 40 | -------------------------------------------------------------------------------- /figure_2.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": { 7 | "id": "532jUiWVFvuK" 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "# Copyright 2022 DeepMind Technologies Limited\n", 12 | "#\n", 13 | "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", 14 | "# you may not use this file except in compliance with the License.\n", 15 | "# You may obtain a copy of the License at\n", 16 | "#\n", 17 | "# https://www.apache.org/licenses/LICENSE-2.0\n", 18 | "#\n", 19 | "# Unless required by applicable law or agreed to in writing, software\n", 20 | "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", 21 | "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", 22 | "# See the License for the specific language governing permissions and\n", 23 | "# limitations under the License." 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": null, 29 | "metadata": { 30 | "id": "88TLm4av-SDK" 31 | }, 32 | "outputs": [], 33 | "source": [ 34 | "# Download code to import locally.\n", 35 | "# The '/content' path is meant for cloud-based Google Colab.\n", 36 | "# If running on a local Colab, you may want to change that to a different\n", 37 | "# local path.\n", 38 | "import os\n", 39 | "import requests\n", 40 | "import shutil\n", 41 | "\n", 42 | "path = \"/content\"\n", 43 | "github_path = \"https://raw.githubusercontent.com/deepmind/spatial_memory_pipeline/master/src/\"\n", 44 | "local_folder = \"spatial_memory_pipeline\"\n", 45 | "filenames = [\"classify_units.py\", \"dataset.py\", \"plot_utils.py\", \"scores.py\"]\n", 46 | "\n", 47 | "!cd {path}\n", 48 | "!mkdir {path}/{local_folder}\n", 49 | "!touch {path}/{local_folder}/__init__.py\n", 50 | "\n", 51 | "for name in filenames:\n", 52 | " source = os.path.join(github_path, name)\n", 53 | " dest = os.path.join(path, local_folder, name)\n", 54 | " with requests.get(source, stream=True) as r, open(dest, 'wb') as w:\n", 55 | " r.raise_for_status()\n", 56 | " for chunk in r.iter_content(chunk_size=128):\n", 57 | " w.write(chunk)\n", 58 | " w.close()" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": { 65 | "id": "WMpZRqd-coZD" 66 | }, 67 | "outputs": [], 68 | "source": [ 69 | "# Imports.\n", 70 | "\n", 71 | "import numpy as np\n", 72 | "\n", 73 | "from spatial_memory_pipeline import classify_units\n", 74 | "from spatial_memory_pipeline import dataset\n", 75 | "from spatial_memory_pipeline import plot_utils\n", 76 | "from spatial_memory_pipeline import scores" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "metadata": { 83 | "id": "3YR2b0y7RTaa" 84 | }, 85 | "outputs": [], 86 | "source": [ 87 | "# Load 800 trajectories of 500 steps each.\n", 88 | "\n", 89 | "dataset.download_figure2_files()\n", 90 | "traj_ds = dataset.load_figure_2_trajectories()\n", 91 | "ds = dataset.flatten_trajectories(traj_ds)\n", 92 | "\n", 93 | "print(dataset.description(traj_ds))" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "metadata": { 100 | "id": "V7u-xfXgqRG_" 101 | }, 102 | "outputs": [], 103 | "source": [ 104 | "# Compute classification thresholds for different kinds of units\n", 105 | "# (this may take ~15 minutes).\n", 106 | "#\n", 107 | "# For each type of cell (HD cells, egoBVC cells and BVC cells) we compute\n", 108 | "# resultant vectors associated with the representation and compare them\n", 109 | "# to a threshold obtained from the 99-percentile resultant vector length\n", 110 | "# fromo shuffled versions of the cell responses. See Supplementary methods\n", 111 | "# section in the paper for details.\n", 112 | "\n", 113 | "all_activities = np.concatenate(ds[\"predicted_outputs\"][:3], axis=-1)\n", 114 | "\n", 115 | "(is_hd, hd_threshold, hd_score, hd_rv_len, hd_rv_angles, # HD-cell parameters\n", 116 | " is_ego, ego_threshold, ego_score, ego_dist, ego_ang, # egoBVC parameters\n", 117 | " is_allo, allo_threshold, allo_score, allo_dist, allo_ang) = ( # BVC parameters\n", 118 | " classify_units.classify_units_into_representations(\n", 119 | " all_activities, ds[\"hd\"], ds[\"pos\"], ds[\"world_distances\"], percentile=99)\n", 120 | " )\n", 121 | "\n", 122 | "print(\"HD Resultant vector threshold:\", hd_threshold)\n", 123 | "print(\"HD units:\", np.where(is_hd)[0])\n", 124 | "print(\"EgoBVC Resultant vector threshold:\", ego_threshold)\n", 125 | "print(\"EgoBVC units:\", np.where(is_ego)[0])\n", 126 | "print(\"BVC Resultant vector threshold:\", allo_threshold)\n", 127 | "print(\"BVC units:\", np.where(is_allo)[0])" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": null, 133 | "metadata": { 134 | "id": "HC4ZxsdHAkrT" 135 | }, 136 | "outputs": [], 137 | "source": [ 138 | "# Types of cell per RNN.\n", 139 | "#\n", 140 | "# RNN-1 contains 32 units, RNN-2 128 units, RNN-3 128 units.\n", 141 | "\n", 142 | "units_in_each_rnn = [range(32), range(32, 160), range(160, 288)]\n", 143 | "\n", 144 | "for rnn_idx in range(3):\n", 145 | " units = units_in_each_rnn[rnn_idx]\n", 146 | "\n", 147 | " print(f\"------ RNN-{rnn_idx + 1} -------\",)\n", 148 | " print(\"\\tHD %d (%.1f%%)\" % (np.sum(is_hd[units]), 100 * np.mean(is_hd[units])))\n", 149 | " print(\"\\tegoBVC %d (%.1f%%)\" % (np.sum(is_ego[units]), 100 * np.mean(is_ego[units])))\n", 150 | " print(\"\\tBVC %d (%.1f%%)\" % (np.sum(is_allo[units]), 100 * np.mean(is_allo[units])))\n", 151 | "\n", 152 | " more_allo_than_ego = np.logical_and(allo_score \u003e ego_score, is_ego)[units]\n", 153 | " print(\"\\t\\tBVC (allocentric) score \u003e egoBVC score %d\" % (np.sum(more_allo_than_ego)))" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": null, 159 | "metadata": { 160 | "id": "ZflquMHJkOFh" 161 | }, 162 | "outputs": [], 163 | "source": [ 164 | "# Compute positional stability of the representations (panel F of figure 2).\n", 165 | "\n", 166 | "rnn0_stability = scores.positional_correlations(ds[\"pos\"], ds[\"hd\"], ds[\"predicted_outputs\"][0])\n", 167 | "rnn1_stability = scores.positional_correlations(ds[\"pos\"], ds[\"hd\"], ds[\"predicted_outputs\"][1])\n", 168 | "rnn2_stability = scores.positional_correlations(ds[\"pos\"], ds[\"hd\"], ds[\"predicted_outputs\"][2])" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": null, 174 | "metadata": { 175 | "id": "BEBY4E52eNO1" 176 | }, 177 | "outputs": [], 178 | "source": [ 179 | "# Auxiliary functions for plotting figure\n", 180 | "\n", 181 | "def rnn_label(index):\n", 182 | " return \"RNN-%d\" % (index + 1)\n", 183 | "\n", 184 | "\n", 185 | "def rnn_polars(fig, x, y, text, ds, rnn_index, chosen_units, x_multiplier=1,\n", 186 | " text_offset=0.0, color=\"b\"):\n", 187 | " \"\"\"Polar plot used to represent HD cells.\"\"\"\n", 188 | " polar_axs = fig.add_subplots_to_figure(\n", 189 | " 1,\n", 190 | " len(chosen_units),\n", 191 | " x + 0.05 + 0.25 * (x_multiplier - 1),\n", 192 | " y,\n", 193 | " 0.4,\n", 194 | " 0.4,\n", 195 | " 0.15,\n", 196 | " 0.05,\n", 197 | " text=text,\n", 198 | " text_offset=-0.05 + text_offset,\n", 199 | " projection=\"polar\")\n", 200 | " rv_scorer = scores.ResultantVectorHeadDirectionScorer(36)\n", 201 | " for i, unit in enumerate(chosen_units):\n", 202 | " polar_rm = rv_scorer.calculate_hd_ratemap(\n", 203 | " ds[\"hd\"][:, 0],\n", 204 | " ds[\"predicted_outputs\"][rnn_index][:, unit])\n", 205 | " rv_scorer.plot_polarplot([polar_rm],\n", 206 | " ax=polar_axs[0, i], positive_lobe_color=color)\n", 207 | " polar_axs[0, i].set_xticks(np.linspace(0, 2 * np.pi, 4, endpoint=False))\n", 208 | " polar_axs[0, i].set_xticklabels([\"E\", \"N\", \"W\", \"S\"])\n", 209 | " polar_axs[0, i].xaxis.set_tick_params(pad=-5)\n", 210 | " polar_axs[0, i].set_yticks([0.5])\n", 211 | " polar_axs[0, i].set_ylim(0, 1)\n", 212 | " polar_axs[0, i].spines[\"polar\"].set_linewidth(1)\n", 213 | " polar_axs[0, i].spines[\"polar\"].set_color(\"k\")\n", 214 | "\n", 215 | "\n", 216 | "def rnn_ratemaps(fig, x, y, text, ds, rnn_index, chosen_units, x_multiplier=1,\n", 217 | " cmap=\"jet\", text_offset=0.0):\n", 218 | " \"\"\"Ratemap activity plot, including per-octant ratemaps.\"\"\"\n", 219 | " axs = fig.add_subplots_to_figure(1, len(chosen_units),\n", 220 | " x, y, 0.5 * x_multiplier, 0.5,\n", 221 | " 0.05, 0.05,\n", 222 | " text_offset=text_offset,\n", 223 | " text=text)\n", 224 | " for i, unit in enumerate(chosen_units):\n", 225 | " ratemap = scores.calculate_ratemap(\n", 226 | " ds[\"pos\"][:, 0],\n", 227 | " ds[\"pos\"][:, 1],\n", 228 | " ds[\"predicted_outputs\"][rnn_index][:, unit],\n", 229 | " hd=ds[\"hd\"])[0]\n", 230 | " rmpo = plot_utils.octant_ratemap_to_rgb(ratemap,\n", 231 | " per_octant=True,\n", 232 | " cmap=cmap)\n", 233 | " plot_utils.imshow(axs[0, i], rmpo)\n", 234 | " axs[0, i].set_title(\"%s:%d\" % (rnn_label(rnn_index), unit))\n", 235 | "\n", 236 | "\n", 237 | "def place_cell_ratemaps(fig, x, y, text, ds, mmap_index, chosen_units, x_multiplier=1,\n", 238 | " cmap=\"jet\", text_offset=0.0, size=0.5):\n", 239 | " \"\"\"Plot ratemap for place cells.\"\"\"\n", 240 | " octant_axs = fig.add_subplots_to_figure(\n", 241 | " 1,\n", 242 | " len(chosen_units),\n", 243 | " x,\n", 244 | " y,\n", 245 | " size * x_multiplier,\n", 246 | " size,\n", 247 | " 0.05,\n", 248 | " 0.05,\n", 249 | " text_offset=text_offset,\n", 250 | " text=text)\n", 251 | " for i, unit in enumerate(chosen_units):\n", 252 | " activations = np.exp(ds[\"log_ps_given_y\"][mmap_index][:, unit])\n", 253 | " ratemap = scores.calculate_ratemap(\n", 254 | " ds[\"pos\"][:, 0], ds[\"pos\"][:, 1], activations, hd=ds[\"hd\"])[0]\n", 255 | " rmpo = plot_utils.octant_ratemap_to_rgb(\n", 256 | " ratemap, per_octant=False, cmap=cmap)\n", 257 | " plot_utils.imshow(octant_axs[0, i], rmpo)\n", 258 | " octant_axs[0, i].set_title(\"Mem:%d\" % (unit,))\n" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": null, 264 | "metadata": { 265 | "id": "jpFIJt_Enwh5" 266 | }, 267 | "outputs": [], 268 | "source": [ 269 | "# Plot the figure.\n", 270 | "\n", 271 | "# Indices of the units to be displayed for each type of cell\n", 272 | "chosen_hd_cells = [0, 1, 2, 3, 4]\n", 273 | "chosen_ego_cells = [14, 56, 73, 76, 81]\n", 274 | "chosen_allo_cells = [57, 64, 87, 104, 119]\n", 275 | "chosen_pc_cells = [43, 45, 96, 508, 510]\n", 276 | "\n", 277 | "# Position for each subplot\n", 278 | "rnn1_rm_x, rnn1_rm_y = 0.2, 0.2\n", 279 | "rnn2_rm_x, rnn2_rm_y = 0.2, 1.5\n", 280 | "rnn3_rm_x, rnn3_rm_y = 0.2, 2.2\n", 281 | "pc_rm_x, pc_rm_y = 0.2, 2.9\n", 282 | "spat_stab_x, spat_stab_y = 0.35, 3.6\n", 283 | "all_rv_x, all_rv_y = 1.9, 3.6\n", 284 | "rnn1_rv_x, rnn1_rv_y = 0.35, 5.0\n", 285 | "ego_vs_allo_x, ego_vs_allo_y = 1.9, 5.0\n", 286 | "\n", 287 | "panel_w, panel_h = 1.0, 1.0\n", 288 | "\n", 289 | "# Create the figure\n", 290 | "fig = plot_utils.SuperFigure(3.0, 7.5, dpi=180)\n", 291 | "cmap = \"jet\"\n", 292 | "\n", 293 | "# Plot some HD cells, their polar plot and ratemaps to show spatial uniformity\n", 294 | "rnn_polars(fig, rnn1_rm_x, rnn1_rm_y, \"A)\", ds, rnn_index=0, chosen_units=chosen_hd_cells)\n", 295 | "rnn_ratemaps(fig, rnn1_rm_x, rnn1_rm_y + 0.6, \"B)\", ds, rnn_index=0, chosen_units=chosen_hd_cells, cmap=cmap)\n", 296 | "# Plot some ego-BVC cell ratemaps\n", 297 | "rnn_ratemaps(fig, rnn2_rm_x, rnn2_rm_y, \"C)\", ds, rnn_index=1, chosen_units=chosen_ego_cells, cmap=cmap)\n", 298 | "# Plot some allo-BVC cell ratemaps\n", 299 | "rnn_ratemaps(fig, rnn3_rm_x, rnn3_rm_y, \"D)\", ds, rnn_index=2, chosen_units=chosen_allo_cells, cmap=cmap)\n", 300 | "# Plot some place-cell ratemaps from memory activations\n", 301 | "place_cell_ratemaps(fig, pc_rm_x, pc_rm_y, \"E)\", ds, mmap_index=1, chosen_units=chosen_pc_cells, cmap=cmap)\n", 302 | "\n", 303 | "# Plot a histogram of spatial stability for each RNN\n", 304 | "stability_ax = fig.add_subplots_to_figure(1, 1,\n", 305 | " spat_stab_x, spat_stab_y, panel_w, panel_h,\n", 306 | " text=\"F)\", text_offset=-0.15)[0, 0]\n", 307 | "bins = np.linspace(0, 1, 11)\n", 308 | "plot_utils.prop_hist(stability_ax, rnn0_stability, bins, color=\"b\", alpha=0.7, label=rnn_label(0))\n", 309 | "plot_utils.prop_hist(stability_ax, rnn1_stability, bins, color=\"g\", alpha=0.7, label=rnn_label(1))\n", 310 | "plot_utils.prop_hist(stability_ax, rnn2_stability, bins, color=\"r\", alpha=0.7, label=rnn_label(2))\n", 311 | "stability_ax.set_xlim(0, 1)\n", 312 | "stability_ax.set_ylim(0, 1)\n", 313 | "stability_ax.set_xlabel(\"Spatial stability\")\n", 314 | "stability_ax.set_ylabel(\"Proportion of cells\")\n", 315 | "stability_ax.legend(loc=\"upper left\")\n", 316 | "stability_ax.grid(linewidth=1, linestyle=\"-\", color=\"#333333\", alpha=0.1)\n", 317 | "plot_utils.setup_spines(stability_ax)\n", 318 | "\n", 319 | "## Plot a histogram of directional resultant-vector length for each RNN\n", 320 | "prop_hds_ax = fig.add_subplots_to_figure(1, 1,\n", 321 | " all_rv_x, all_rv_y, panel_w, panel_h,\n", 322 | " text=\"G)\", text_offset=-0.15)[0, 0]\n", 323 | "bins = np.linspace(0, 1, 11)\n", 324 | "plot_utils.prop_hist(prop_hds_ax, hd_rv_len[:32], bins, color=\"b\", alpha=0.7, label=rnn_label(0))\n", 325 | "plot_utils.prop_hist(prop_hds_ax, hd_rv_len[32:160], bins, color=\"g\", alpha=0.7, label=rnn_label(1))\n", 326 | "plot_utils.prop_hist(prop_hds_ax, hd_rv_len[160:], bins, color=\"r\", alpha=0.7, label=rnn_label(2))\n", 327 | "prop_hds_ax.set_ylim(0, 1)\n", 328 | "prop_hds_ax.set_xlim(0, 1.0)\n", 329 | "prop_hds_ax.set_xlabel(\"Resultant vector length\")\n", 330 | "prop_hds_ax.set_ylabel(\"Proportion of cells\")\n", 331 | "prop_hds_ax.legend(loc=\"upper right\")\n", 332 | "prop_hds_ax.grid(linewidth=1, linestyle=\"-\", color=\"#333333\", alpha=0.1)\n", 333 | "plot_utils.setup_spines(prop_hds_ax)\n", 334 | "\n", 335 | "\n", 336 | "## RNN 1 - RV polar plot\n", 337 | "ax = fig.add_subplots_to_figure(1, 1,\n", 338 | " rnn1_rv_x, rnn1_rv_y, panel_w, panel_h,\n", 339 | " text=\"H)\", text_offset=-0.15, projection=\"polar\")[0, 0]\n", 340 | "\n", 341 | "rnn0_rv_angles, rnn0_rv_lengths = hd_rv_angles[:32], hd_rv_len[:32]\n", 342 | "\n", 343 | "for rvang, rvlen in zip(rnn0_rv_angles, rnn0_rv_lengths):\n", 344 | " ax.plot((rvang, rvang), (0, rvlen), color=\"#4C72B0\")\n", 345 | "ax.grid(linewidth=1, linestyle=\":\", color=\"#333333\")\n", 346 | "ax.set_xticks(np.linspace(0, 2*np.pi, 4, endpoint=False))\n", 347 | "ax.set_xticklabels([\"E\", \"N\", \"W\", \"S\"])\n", 348 | "ax.set_ylim(0, 1.0)\n", 349 | "ax.set_yticklabels([\"\", \"%.2f\" % hd_threshold, \"1\"])\n", 350 | "ax.set_yticks([0, hd_threshold])\n", 351 | "ax.grid(linewidth=1, linestyle=\"-\", color=\"#333333\", alpha=0.1)\n", 352 | "plot_utils.setup_spines(ax)\n", 353 | "\n", 354 | "\n", 355 | "# egoBCV scores vs BVC (allocentric) scores\n", 356 | "ego_vs_allo_ax = fig.add_subplots_to_figure(1, 1,\n", 357 | " ego_vs_allo_x, ego_vs_allo_y, panel_w, panel_h,\n", 358 | " text=\"I)\", text_offset=-0.15)[0, 0]\n", 359 | "ego_vs_allo_ax.scatter(ego_score[32:160], allo_score[32:160], color=\"g\", label=rnn_label(1), alpha=0.6, marker=\".\")\n", 360 | "ego_vs_allo_ax.scatter(ego_score[160:], allo_score[160:], color=\"r\", label=rnn_label(2), alpha=0.6, marker=\".\")\n", 361 | "ego_vs_allo_ax.scatter(ego_score[:32], allo_score[:32], color=\"b\", label=rnn_label(0), alpha=0.6, marker=\".\")\n", 362 | "ego_vs_allo_ax.axvline(ego_threshold, color=\"k\", alpha=0.8, linestyle=\"dashed\")\n", 363 | "ego_vs_allo_ax.axhline(allo_threshold, color=\"k\", alpha=0.8, linestyle=\"dashed\")\n", 364 | "ego_vs_allo_ax.set_xlim(0, 0.5)\n", 365 | "ego_vs_allo_ax.set_ylim(0, 0.5)\n", 366 | "\n", 367 | "ego_vs_allo_ax.set_xticks(np.arange(0., 0.51, 0.1))\n", 368 | "ego_vs_allo_ax.set_yticks(np.arange(0., 0.51, 0.1))\n", 369 | "\n", 370 | "ego_vs_allo_ax.set_xlabel(\"Egocentric-BVC score\")\n", 371 | "ego_vs_allo_ax.set_ylabel(\"Allocentric-BVC score\")\n", 372 | "ego_vs_allo_ax.legend()\n", 373 | "ego_vs_allo_ax.grid(linewidth=1, linestyle=\"-\", color=\"#333333\", alpha=0.1)\n", 374 | "plot_utils.setup_spines(ego_vs_allo_ax)" 375 | ] 376 | }, 377 | { 378 | "cell_type": "markdown", 379 | "metadata": { 380 | "id": "J9V54PIRNaiJ" 381 | }, 382 | "source": [ 383 | "" 384 | ] 385 | } 386 | ], 387 | "metadata": { 388 | "colab": { 389 | "collapsed_sections": [], 390 | "name": "figure_2.ipynb", 391 | "private_outputs": true, 392 | "provenance": [] 393 | }, 394 | "kernelspec": { 395 | "display_name": "Python 3", 396 | "name": "python3" 397 | } 398 | }, 399 | "nbformat": 4, 400 | "nbformat_minor": 0 401 | } 402 | -------------------------------------------------------------------------------- /figure_3.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": { 7 | "id": "532jUiWVFvuK" 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "# Copyright 2022 DeepMind Technologies Limited\n", 12 | "#\n", 13 | "# Licensed under the Apache License, Version 2.0 (the \"License\");\n", 14 | "# you may not use this file except in compliance with the License.\n", 15 | "# You may obtain a copy of the License at\n", 16 | "#\n", 17 | "# https://www.apache.org/licenses/LICENSE-2.0\n", 18 | "#\n", 19 | "# Unless required by applicable law or agreed to in writing, software\n", 20 | "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", 21 | "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", 22 | "# See the License for the specific language governing permissions and\n", 23 | "# limitations under the License." 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": null, 29 | "metadata": { 30 | "id": "amXwOIJTov3g" 31 | }, 32 | "outputs": [], 33 | "source": [ 34 | "# Download code to import locally.\n", 35 | "# The '/content' path is meant for cloud-based Google Colab.\n", 36 | "# If running on a local Colab, you may want to change that to a different\n", 37 | "# local path.\n", 38 | "import os\n", 39 | "import requests\n", 40 | "import shutil\n", 41 | "\n", 42 | "path = \"/content\"\n", 43 | "github_path = \"https://raw.githubusercontent.com/deepmind/spatial_memory_pipeline/master/src/\"\n", 44 | "local_folder = \"spatial_memory_pipeline\"\n", 45 | "filenames = [\"dataset.py\", \"plot_utils.py\"]\n", 46 | "\n", 47 | "!cd {path}\n", 48 | "!mkdir {path}/{local_folder}\n", 49 | "!touch {path}/{local_folder}/__init__.py\n", 50 | "\n", 51 | "for name in filenames:\n", 52 | " source = os.path.join(github_path, name)\n", 53 | " dest = os.path.join(path, local_folder, name)\n", 54 | " with requests.get(source, stream=True) as r, open(dest, 'wb') as w:\n", 55 | " r.raise_for_status()\n", 56 | " for chunk in r.iter_content(chunk_size=128):\n", 57 | " w.write(chunk)\n", 58 | " w.close()" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": { 65 | "id": "Ys7gTj2q_7uq" 66 | }, 67 | "outputs": [], 68 | "source": [ 69 | "# Imports.\n", 70 | "\n", 71 | "import matplotlib.pyplot as plt\n", 72 | "from matplotlib.cm import get_cmap\n", 73 | "from matplotlib.offsetbox import OffsetImage\n", 74 | "from matplotlib.offsetbox import AnnotationBbox\n", 75 | "\n", 76 | "import numpy as np\n", 77 | "import scipy.stats\n", 78 | "\n", 79 | "from spatial_memory_pipeline import dataset\n", 80 | "from spatial_memory_pipeline import plot_utils" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": { 87 | "id": "ehlDcLY2D_6J" 88 | }, 89 | "outputs": [], 90 | "source": [ 91 | "# Functions to unroll the model RNNs.\n", 92 | "\n", 93 | "def sigmoid(x):\n", 94 | " return 1. / (1.+np.exp(-x))\n", 95 | "\n", 96 | "\n", 97 | "def softmax(x, axis=-1):\n", 98 | " \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n", 99 | " e_x = np.exp(x - np.amax(x, axis=axis, keepdims=True))\n", 100 | " return e_x / e_x.sum(axis=axis, keepdims=True)\n", 101 | "\n", 102 | "\n", 103 | "def step_of_lstm(state, inputs, w, b):\n", 104 | " forget_bias = 1\n", 105 | " prev_hidden, prev_cell = state\n", 106 | " inputs_and_hidden = np.concatenate([inputs, prev_hidden], axis=-1)\n", 107 | " gates = np.matmul(inputs_and_hidden, w) + b\n", 108 | "\n", 109 | " # i = input_gate, j = next_input, f = forget_gate, o = output_gate\n", 110 | " i, j, f, o = np.split(gates, 4, axis=-1)\n", 111 | "\n", 112 | " forget_mask = sigmoid(f + forget_bias)\n", 113 | " next_cell = forget_mask * prev_cell + sigmoid(i) * np.tanh(j)\n", 114 | " cell_output = next_cell\n", 115 | " next_hidden = sigmoid(cell_output) * sigmoid(o)\n", 116 | "\n", 117 | " return next_hidden, (next_hidden, next_cell)\n", 118 | "\n", 119 | "\n", 120 | "def get_visual_correction_codes(parameters, visual_embeddings):\n", 121 | " \"\"\"Calculates visual correction codes for a set of visual embeddings.\"\"\"\n", 122 | " # hd_embeddings corresponds to m^{(x)} in methods\n", 123 | " hd_embeddings = parameters[\"integrator/memory_map_0/column_context_3\"]\n", 124 | " # memory_of_visual_embeddings corresponds to m^{(y)} in methods\n", 125 | " memory_of_visual_embeddings = parameters[\"integrator/memory_map_0/column_context_2\"]\n", 126 | " # gamma is the correction inverse temperature\n", 127 | " gamma = np.exp(parameters[\"integrator/multi_integrator_nets/mmap_0_context_2_query_beta\"])\n", 128 | " w_s = softmax(gamma * np.matmul(visual_embeddings, memory_of_visual_embeddings.T),\n", 129 | " axis=-1)\n", 130 | " correction_codes = np.matmul(w_s, hd_embeddings)\n", 131 | " return correction_codes\n", 132 | "\n", 133 | "\n", 134 | "def unroll_rnn_with_fixed_vel(initial_state, ang_vel, n_steps, rnn_step_func):\n", 135 | " \"\"\"Unroll one rnn with a constant velocity input.\"\"\"\n", 136 | " B = initial_state.shape[0]\n", 137 | " vel_inputs = np.tile(np.asarray([[np.cos(ang_vel), np.sin(ang_vel)]]),\n", 138 | " (B, 1))\n", 139 | " # Velocities are scaled to increase range\n", 140 | " vel_inputs *= 10\n", 141 | " state_traj = list()\n", 142 | " state_traj.append(initial_state)\n", 143 | " rnn_state = (initial_state, initial_state)\n", 144 | " for t in range(n_steps):\n", 145 | " output, rnn_state = rnn_step_func(rnn_state, vel_inputs)\n", 146 | " state_traj.append(output)\n", 147 | " return np.asarray(state_traj)" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": null, 153 | "metadata": { 154 | "id": "Ht0iwXu0X7x4" 155 | }, 156 | "outputs": [], 157 | "source": [ 158 | "# Auxiliary functions.\n", 159 | "\n", 160 | "def take_if_farther_than(points, distance_f, threshold):\n", 161 | " \"\"\"Filters points choosing a subset such that they are all at least\n", 162 | " `threshold` distance from each other.\n", 163 | "\n", 164 | " Returns a tuple with the indices of the filtered points, and their values.\n", 165 | " \"\"\"\n", 166 | " chosen_points = list()\n", 167 | " chosen_indices = list()\n", 168 | " for i, p in enumerate(points):\n", 169 | " if i == 0:\n", 170 | " chosen_points.append(p)\n", 171 | " chosen_indices.append(i)\n", 172 | " else:\n", 173 | " min_d = np.inf\n", 174 | " for ch in chosen_points:\n", 175 | " if distance_f(p, ch) \u003c min_d:\n", 176 | " min_d = distance_f(p, ch)\n", 177 | " if min_d \u003e threshold:\n", 178 | " chosen_points.append(p)\n", 179 | " chosen_indices.append(i)\n", 180 | " return chosen_indices, np.asarray(chosen_points)\n", 181 | "\n", 182 | "\n", 183 | "def euclidean_dist(a, b):\n", 184 | " return np.linalg.norm(a-b)\n", 185 | "\n", 186 | "\n", 187 | "def autocovariance(state_traj, ignore_n_first=0, max_lag=50):\n", 188 | " T, B, D = state_traj.shape\n", 189 | " autocov = list()\n", 190 | " for b in range(B):\n", 191 | " traj = state_traj[:, b, :]\n", 192 | " mean = np.mean(traj, axis=0)\n", 193 | " ctraj = traj - mean[np.newaxis, ...]\n", 194 | " var = np.var(ctraj, axis=0)\n", 195 | " covar = np.matmul(ctraj, ctraj.T)\n", 196 | " traj_autocov = np.asarray([np.mean([covar[i, i+l] for i in range(ignore_n_first, T-l)]) for l in range(max_lag)])\n", 197 | " autocov.append(traj_autocov)\n", 198 | " return np.asarray(autocov)\n" 199 | ] 200 | }, 201 | { 202 | "cell_type": "markdown", 203 | "metadata": { 204 | "id": "uAW45gklGIlE" 205 | }, 206 | "source": [ 207 | "### Download data" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": null, 213 | "metadata": { 214 | "id": "Cn35yAj1ADTY" 215 | }, 216 | "outputs": [], 217 | "source": [ 218 | "# Download parameters, inputs, and hd cell stats.\n", 219 | "\n", 220 | "dataset.download_figure3_files()\n", 221 | "parameters = dataset.load_figure_3_parameters()\n", 222 | "visual_inputs = dataset.load_figure_3_visual_inputs()\n", 223 | "hd_stats = dataset.load_figure_3_hd_stats()\n", 224 | "\n", 225 | "p_w = parameters[\"integrator/multi_integrator_nets/prediction_rnn_0/w_gates\"]\n", 226 | "p_b = parameters[\"integrator/multi_integrator_nets/prediction_rnn_0/b_gates\"]\n", 227 | "c_w = parameters[\"integrator/multi_integrator_nets/correction_rnn_0/w_gates\"]\n", 228 | "c_b = parameters[\"integrator/multi_integrator_nets/correction_rnn_0/b_gates\"]\n", 229 | "step_of_prediction = lambda state, inputs: step_of_lstm(state, inputs, p_w, p_b)\n", 230 | "step_of_correction = lambda state, inputs: step_of_lstm(state, inputs, c_w, c_b)\n", 231 | "\n", 232 | "rnn_initial_states = parameters[\"integrator/memory_map_0/column_context_3_written\"]\n", 233 | "\n", 234 | "correction_code = get_visual_correction_codes(parameters, visual_inputs[\"embeddings\"])" 235 | ] 236 | }, 237 | { 238 | "cell_type": "code", 239 | "execution_count": null, 240 | "metadata": { 241 | "id": "veuObOlN1kFf" 242 | }, 243 | "outputs": [], 244 | "source": [ 245 | "# Select hd cells, sorted by preferred angle.\n", 246 | "\n", 247 | "hd_cutoff = 0.56\n", 248 | "n_units = len(hd_stats[\"rnn0_rv_angles\"])\n", 249 | "hd_ordering = np.argsort(hd_stats[\"rnn0_rv_angles\"])\n", 250 | "hd_ordering = hd_ordering[hd_stats[\"rnn0_rv_lengths\"][hd_ordering] \u003e hd_cutoff]\n", 251 | "n_hd_cells = len(hd_ordering)" 252 | ] 253 | }, 254 | { 255 | "cell_type": "markdown", 256 | "metadata": { 257 | "id": "xgLpQLXf1kzJ" 258 | }, 259 | "source": [ 260 | "### Dynamics without corrections" 261 | ] 262 | }, 263 | { 264 | "cell_type": "code", 265 | "execution_count": null, 266 | "metadata": { 267 | "id": "93TVibk09ZxU" 268 | }, 269 | "outputs": [], 270 | "source": [ 271 | "# Trajectory with piecewise-constant velocities.\n", 272 | "\n", 273 | "T = 1000\n", 274 | "ang_vel = np.pi / 20\n", 275 | "n_inputs = 2\n", 276 | "\n", 277 | "# Take a valid initial state\n", 278 | "initial_state_index = 8 # Select a state where the angle starts at 0\n", 279 | "initial_state = rnn_initial_states[initial_state_index]\n", 280 | "state = (initial_state, initial_state)\n", 281 | "\n", 282 | "# Construct velocity inputs\n", 283 | "vel = [ang_vel] * (T // 4) + [0] * (T // 4) + [-ang_vel/2.0] * (T // 2)\n", 284 | "vel = np.asarray([[np.cos(v), np.sin(v)] for v in vel])\n", 285 | "\n", 286 | "# Ground-truth integrated velocities\n", 287 | "true_angular_offset = np.cumsum(np.arctan2(vel[:-1, 1], vel[:-1, 0]))\n", 288 | "\n", 289 | "# The network receives the inputs scaled by 10 (to increase the range)\n", 290 | "vel = vel * 10\n", 291 | "trajectory = []\n", 292 | "for i in range(T):\n", 293 | " output, state = step_of_prediction(state, vel[i])\n", 294 | " trajectory.append(output)\n", 295 | "trajectory = np.asarray(trajectory)\n", 296 | "demo_trajectory = trajectory[:, hd_ordering]" 297 | ] 298 | }, 299 | { 300 | "cell_type": "code", 301 | "execution_count": null, 302 | "metadata": { 303 | "id": "ClvZPdp0YJvp" 304 | }, 305 | "outputs": [], 306 | "source": [ 307 | "# Calculate PCA space.\n", 308 | "\n", 309 | "# Remove repeated points\n", 310 | "pca_from = take_if_farther_than(trajectory, euclidean_dist, 0.1)[1]\n", 311 | "pca_from = np.asarray(pca_from)\n", 312 | "cov_mat = np.cov(pca_from.T)\n", 313 | "cov_mat += np.eye(cov_mat.shape[0]) * 1e-4\n", 314 | "\n", 315 | "# Covariance matrix of all units with 16 times the variance for random inits\n", 316 | "diag_cov_mat = cov_mat * np.eye(cov_mat.shape[0]) * 16\n", 317 | "# Distribution of random initialisations\n", 318 | "initial_dist = scipy.stats.multivariate_normal(mean=np.mean(pca_from, axis=0),\n", 319 | " cov=diag_cov_mat)\n", 320 | "\n", 321 | "# PCA\n", 322 | "cov = np.cov(pca_from[:, hd_ordering].T)\n", 323 | "mean = np.mean(pca_from[:, hd_ordering].T, axis=1)\n", 324 | "eiglambda, eigvec = np.linalg.eig(cov)\n", 325 | "def project_on_pca(x):\n", 326 | " return np.matmul(x - mean, eigvec[:, :2]).real" 327 | ] 328 | }, 329 | { 330 | "cell_type": "code", 331 | "execution_count": null, 332 | "metadata": { 333 | "id": "AD3mr9zx2Jn9" 334 | }, 335 | "outputs": [], 336 | "source": [ 337 | "# Trajectories with zero velocity, from different random initialisations.\n", 338 | "\n", 339 | "T = 2000\n", 340 | "B = 100\n", 341 | "ang_vel = 0.0\n", 342 | "vel = np.asarray([[np.cos(ang_vel), np.sin(ang_vel)]] * B)\n", 343 | "vel = vel * 10\n", 344 | "\n", 345 | "trajectories = list()\n", 346 | "for k in range(1000 // B):\n", 347 | " print(\".\", end=\"\")\n", 348 | " state = initial_dist.rvs(B)\n", 349 | " out_traj = [state]\n", 350 | " state = (state, state)\n", 351 | " for _ in range(T):\n", 352 | " output, state = step_of_prediction(state, vel)\n", 353 | " out_traj.append(output)\n", 354 | " trajectories.append(np.rollaxis(np.asarray(out_traj), 1))\n", 355 | "\n", 356 | "trajectories = np.concatenate(trajectories)\n", 357 | "trajectories_ordered = trajectories[:, :, hd_ordering]" 358 | ] 359 | }, 360 | { 361 | "cell_type": "code", 362 | "execution_count": null, 363 | "metadata": { 364 | "id": "avzBxSZCImnJ" 365 | }, 366 | "outputs": [], 367 | "source": [ 368 | "# Find attractor states\n", 369 | "\n", 370 | "all_pca = project_on_pca(trajectories_ordered[:, 3:, :])\n", 371 | "minpca, maxpca = np.amin(all_pca, axis=(0, 1)), np.amax(all_pca, axis=(0, 1))\n", 372 | "pca_range = maxpca - minpca\n", 373 | "pcalims = np.stack([np.abs(minpca - 0.1 * pca_range), np.abs(maxpca + 0.1 * pca_range)]).max(axis=0)\n", 374 | "xlim_pca = [-pcalims[0], pcalims[0]]\n", 375 | "ylim_pca = [-pcalims[1], pcalims[1]]\n", 376 | "chosen = list()\n", 377 | "pca = project_on_pca(trajectories_ordered[:, -1, :])\n", 378 | "converged_angles_on_pca = np.arctan2(pca[:, 1], pca[:, 0])\n", 379 | "for i, ang in zip(converged_angles_on_pca.argsort(), converged_angles_on_pca[converged_angles_on_pca.argsort()]):\n", 380 | " if not chosen:\n", 381 | " chosen.append(i)\n", 382 | " last_ang_added = ang\n", 383 | " elif (ang - last_ang_added) \u003e 0.1*np.pi/360 * 2:\n", 384 | " chosen.append(i)\n", 385 | " last_ang_added = ang\n", 386 | "\n", 387 | "attractor_states = trajectories[chosen, -1, :]" 388 | ] 389 | }, 390 | { 391 | "cell_type": "markdown", 392 | "metadata": { 393 | "id": "jEQle0Y0zuda" 394 | }, 395 | "source": [ 396 | "### Dynamics with visual corrections" 397 | ] 398 | }, 399 | { 400 | "cell_type": "code", 401 | "execution_count": null, 402 | "metadata": { 403 | "id": "611a4znQtWfm" 404 | }, 405 | "outputs": [], 406 | "source": [ 407 | "# Run the correction + dynamics for T steps from the attractor states\n", 408 | "\n", 409 | "T = 200\n", 410 | "B = attractor_states.shape[0]\n", 411 | "I = 512 # Different image corrections\n", 412 | "\n", 413 | "ang_vel = 0.0\n", 414 | "vel_inputs = np.asarray([np.cos(ang_vel), np.sin(ang_vel)]) * 10.0\n", 415 | "vel_inputs = np.tile(vel_inputs[np.newaxis, :], (B, 1))\n", 416 | "\n", 417 | "traj_pca_points = list()\n", 418 | "\n", 419 | "for i in range(I):\n", 420 | " rnn_state = attractor_states\n", 421 | " correction_code_batch = np.tile(correction_code[[i], :], (B, 1))\n", 422 | " image = visual_inputs[\"images\"][i]\n", 423 | "\n", 424 | " state_traj = list()\n", 425 | " state_traj.append(rnn_state)\n", 426 | " rnn_state = (rnn_state, rnn_state)\n", 427 | " for t in range(T):\n", 428 | " out, rnn_state = step_of_correction(rnn_state, correction_code_batch)\n", 429 | " out, rnn_state = step_of_prediction(rnn_state, vel_inputs)\n", 430 | " state_traj.append(out)\n", 431 | " state_traj = np.asarray(state_traj)\n", 432 | "\n", 433 | " pc = project_on_pca(state_traj[:, :, hd_ordering])\n", 434 | " traj_pca_points.append(pc)\n", 435 | "\n", 436 | "traj_pca_points = np.asarray(traj_pca_points)" 437 | ] 438 | }, 439 | { 440 | "cell_type": "code", 441 | "execution_count": null, 442 | "metadata": { 443 | "id": "WwdG65r2uyVr" 444 | }, 445 | "outputs": [], 446 | "source": [ 447 | "# Time to convergence\n", 448 | "\n", 449 | "time_to_single_attractor = np.asarray([np.inf] * traj_pca_points.shape[0])\n", 450 | "for i in range(traj_pca_points.shape[0]):\n", 451 | " for t in range(traj_pca_points.shape[1]):\n", 452 | " att_inds, att_points = take_if_farther_than(traj_pca_points[i, t],\n", 453 | " euclidean_dist,\n", 454 | " 0.1)\n", 455 | " if len(att_inds) == 1:\n", 456 | " time_to_single_attractor[i] = t\n", 457 | " break\n", 458 | "\n", 459 | "examples_in_bin_1 = np.where(np.logical_and(time_to_single_attractor \u003e 0,\n", 460 | " time_to_single_attractor \u003c 10))[0]\n", 461 | "examples_in_bin_final = np.where(time_to_single_attractor \u003e 200)[0]" 462 | ] 463 | }, 464 | { 465 | "cell_type": "markdown", 466 | "metadata": { 467 | "id": "SK0JVnty4hIp" 468 | }, 469 | "source": [ 470 | "### Plot figure 3" 471 | ] 472 | }, 473 | { 474 | "cell_type": "code", 475 | "execution_count": null, 476 | "metadata": { 477 | "id": "UVxMzRfG1u9L" 478 | }, 479 | "outputs": [], 480 | "source": [ 481 | "figsize_y = 5.05\n", 482 | "fig = plot_utils.SuperFigure(6.2, figsize_y, dpi=180)\n", 483 | "\n", 484 | "simulation_panel_coords = [0.45, 0.6, 4.1, 0.5]\n", 485 | "groundtruth_simulation_panel_coords = [0.45, 0.2, 4.1, 0.3]\n", 486 | "pca_panel_coords = [5.1, 0.2, 1.0, 1.0]\n", 487 | "delta_panel_coords = [0.3, 1.6, 1.0, 1.0]\n", 488 | "pca_random_panel_coords = [1.9, 1.6, 1.0, 1.0]\n", 489 | "pca_attractor_panel_coords = [3.5, 1.6, 1.0, 1.0]\n", 490 | "autocorr_panel_coords = [5.1, 1.6, 1.0, 1.0]\n", 491 | "ttc_panel_coords = [0.3, 3.4, 2.0, 1.2]\n", 492 | "\n", 493 | "# Panel A. Simulation of integration of velocities\n", 494 | "ax = fig.add_subplots_to_figure(1, 1, *simulation_panel_coords,\n", 495 | " text=None, text_offset=-0.15)[0, 0]\n", 496 | "ax.matshow(demo_trajectory.T, cmap=\"coolwarm\", aspect=3.5)\n", 497 | "ax.grid(\"off\")\n", 498 | "ax.set_yticks(np.arange(0, n_hd_cells+1, 10))\n", 499 | "ax.set_ylabel(\"Unit\")\n", 500 | "ax.set_xticks(np.arange(0, 1000+1, 100))\n", 501 | "ax.xaxis.tick_bottom()\n", 502 | "ax.set_xlabel(\"Integration steps\")\n", 503 | "plot_utils.setup_spines(ax)\n", 504 | "\n", 505 | "# Panel A. Ground truth angular offset\n", 506 | "unit0_angular_offset = -np.pi\n", 507 | "display_angular_offset = np.arctan2(np.sin(true_angular_offset + unit0_angular_offset),\n", 508 | " np.cos(true_angular_offset + unit0_angular_offset))\n", 509 | "\n", 510 | "ax = fig.add_subplots_to_figure(1, 1, *groundtruth_simulation_panel_coords,\n", 511 | " hspace=0.3, text=\"A)\", text_offset=-0.3)[0, 0]\n", 512 | "ax.plot(display_angular_offset, \".\")\n", 513 | "ax.set_xticks(np.arange(0, 1000+1, 100))\n", 514 | "ax.set_xlim(0, 1000)\n", 515 | "ax.set_ylim(-np.pi, np.pi)\n", 516 | "ax.set_yticks([-np.pi, 0., np.pi])\n", 517 | "ax.set_yticklabels([r\"$-\\pi$\", r\"$0$\", r\"$\\pi$\"])\n", 518 | "\n", 519 | "ax.set_xticks(np.arange(0, 1000+1, 100))\n", 520 | "ax.set_xticklabels([])\n", 521 | "ax.xaxis.tick_bottom()\n", 522 | "ax.set_ylabel(\"True angle\")\n", 523 | "plot_utils.setup_spines(ax)\n", 524 | "\n", 525 | "# Panel B. PCA of simulation\n", 526 | "ax = fig.add_subplots_to_figure(1, 1, *pca_panel_coords,\n", 527 | " text=\"B)\", text_offset=-0.15)[0, 0]\n", 528 | "pca_values = project_on_pca(demo_trajectory)\n", 529 | "ax.scatter(pca_values[:, 0], pca_values[:, 1], alpha=0.1, color=\"grey\")\n", 530 | "ax.set_xlabel(\"PC 1\")\n", 531 | "ax.set_ylabel(\"PC 2\")\n", 532 | "ax.set_xlim(xlim_pca)\n", 533 | "ax.set_ylim(ylim_pca)\n", 534 | "plot_utils.setup_spines(ax)\n", 535 | "\n", 536 | "\n", 537 | "# Panel C. Norm change in state vs time\n", 538 | "ax = fig.add_subplots_to_figure(1, 1, *delta_panel_coords,\n", 539 | " text=\"C)\", text_offset=-0.15)[0, 0]\n", 540 | "delta = np.linalg.norm(trajectories_ordered[:, :-1, :] - trajectories_ordered[:, 1:, :], axis=-1)\n", 541 | "plt.plot(np.quantile(delta, .95, axis=0)[:100], linewidth=1, color=\"b\")\n", 542 | "plt.plot(np.quantile(delta, .05, axis=0)[:100], linewidth=1, color=\"b\")\n", 543 | "plt.plot(delta.mean(axis=0)[:100], linewidth=2, color=\"b\")\n", 544 | "ax.set_xlim(0, 100)\n", 545 | "ax.set_ylim(0, 2)\n", 546 | "ax.set_xlabel(\"Steps of dynamics\")\n", 547 | "ax.set_ylabel(\"Change in activations\")\n", 548 | "plot_utils.setup_spines(ax)\n", 549 | "\n", 550 | "# Panel D. PCA of simulations from random initialisations\n", 551 | "ax = fig.add_subplots_to_figure(1, 1, *pca_random_panel_coords,\n", 552 | " text=\"D)\", text_offset=-0.15)[0, 0]\n", 553 | "initializations = trajectories_ordered[:, 0, :]\n", 554 | "pca_values = project_on_pca(initializations)\n", 555 | "plt.scatter(pca_values[:, 0], pca_values[:, 1], alpha=0.1, color=\"grey\")\n", 556 | "\n", 557 | "not_yet_converged_states = trajectories_ordered[:, 10, :]\n", 558 | "pca_values = project_on_pca(not_yet_converged_states)\n", 559 | "plt.scatter(pca_values[:, 0], pca_values[:, 1], alpha=0.1, color=\"green\")\n", 560 | "\n", 561 | "converged_states = trajectories_ordered[:, -1, :]\n", 562 | "pca_values = project_on_pca(converged_states)\n", 563 | "plt.scatter(pca_values[:, 0], pca_values[:, 1], alpha=1.0, color=\"k\", marker=\"x\")\n", 564 | "\n", 565 | "ax.set_xlabel(\"PC 1\")\n", 566 | "ax.set_ylabel(\"PC 2\")\n", 567 | "ax.set_xlim(xlim_pca)\n", 568 | "ax.set_ylim(ylim_pca)\n", 569 | "plot_utils.setup_spines(ax)\n", 570 | "\n", 571 | "# Panel E. PCA CW and CCW cyclic attractor\n", 572 | "init = 0\n", 573 | "ax = fig.add_subplots_to_figure(1, 1, *pca_attractor_panel_coords,\n", 574 | " text=\"E)\", text_offset=-0.15)[0, 0]\n", 575 | "for (i, ang_vel, col, label) in zip([11, 41], [-0.16, 0.16], [\"r\", \"b\"],\n", 576 | " [r\"$\\omega=\\frac{\\pi}{20}$\", r\"$\\omega=-\\frac{\\pi}{20}$\"]):\n", 577 | " vel_state_traj = unroll_rnn_with_fixed_vel(trajectories[i, [0], :], ang_vel, 50, step_of_prediction)\n", 578 | " pca_values = project_on_pca(vel_state_traj[:, :, hd_ordering])\n", 579 | " vels = pca_values[1:, :, :] - pca_values[:-1, :, :]\n", 580 | " alpha = 0.5\n", 581 | " for b in range(vel_state_traj.shape[1]):\n", 582 | " plt.scatter(pca_values[0, b, 0], pca_values[0, b, 1], alpha=1.0, color=col)\n", 583 | " ax.quiver(pca_values[init:-1, b, 0], pca_values[init:-1, b, 1], vels[init:, b, 0], vels[init:, b, 1],\n", 584 | " scale_units=\"xy\", scale=1.0, color=col, alpha=alpha, width=0.005, headwidth=8, label=label)\n", 585 | "\n", 586 | "ax.legend(loc=\"lower right\")\n", 587 | "ax.set_xlabel(\"PC 1\")\n", 588 | "ax.set_ylabel(\"PC 2\")\n", 589 | "ax.set_xlim(xlim_pca)\n", 590 | "ax.set_ylim(ylim_pca)\n", 591 | "plot_utils.setup_spines(ax)\n", 592 | "\n", 593 | "# Panel F. Autocorrelation plot\n", 594 | "ax = fig.add_subplots_to_figure(1, 1, *autocorr_panel_coords,\n", 595 | " text=\"F)\", text_offset=-0.15)[0, 0]\n", 596 | "\n", 597 | "for ang_vel, col, label in zip([-0.16, 0.16], [\"r\", \"b\"], [r\"$\\omega=\\frac{\\pi}{20}$\", r\"$\\omega=-\\frac{\\pi}{20}$\"]):\n", 598 | " state_traj = unroll_rnn_with_fixed_vel(trajectories[:, 0, :], ang_vel, 200, step_of_prediction)\n", 599 | " autocovs = autocovariance(state_traj)\n", 600 | " ax.plot(autocovs.mean(axis=0)[:100], linewidth=1, color=col, label=label)\n", 601 | "\n", 602 | "ax.set_xlabel(\"Steps of dynamics\")\n", 603 | "ax.set_ylabel(\"Autocovariance\")\n", 604 | "ax.legend(loc=\"lower right\")\n", 605 | "plot_utils.setup_spines(ax)\n", 606 | "\n", 607 | "# Panel G. Time to convergence to a single attractor point while correctiong visually\n", 608 | "T = 200\n", 609 | "ax = fig.add_subplots_to_figure(1, 1, *ttc_panel_coords)[0, 0]\n", 610 | "fig.add_text(ttc_panel_coords[0]-0.15, ttc_panel_coords[1]-0.30, text=\"G)\")\n", 611 | "\n", 612 | "nbins = 20\n", 613 | "ax.hist(time_to_single_attractor, bins=np.linspace(0, T, nbins))\n", 614 | "ax.bar(T, np.sum(np.isinf(time_to_single_attractor)), width=T/nbins, color=\"r\", align=\"edge\")\n", 615 | "ax.set_xlim(0, 210)\n", 616 | "ax.set_xticks([0, 50, 100, 150, 200])\n", 617 | "ax.set_xticklabels([\"0\", \"50\", \"100\", \"150\", \" \u003e200\"])\n", 618 | "\n", 619 | "# Plot the quick-convergence visual image examples\n", 620 | "im_width = 40\n", 621 | "for column, image_id in enumerate(examples_in_bin_1[:3]):\n", 622 | " im = OffsetImage(visual_inputs[\"images\"][image_id], zoom=0.8)\n", 623 | " im.image.axes = ax\n", 624 | " xy = (5, 250)\n", 625 | " xybox = (50 + im_width * column, 250)\n", 626 | " if column == 0:\n", 627 | " arrowprops = dict(arrowstyle=\"-\u003e\", color=\"k\")\n", 628 | " else:\n", 629 | " arrowprops = None\n", 630 | " ab = AnnotationBbox(im, xy,\n", 631 | " xybox=xybox,\n", 632 | " xycoords=\"data\",\n", 633 | " boxcoords=\"data\",\n", 634 | " box_alignment=(0.5, 0.5),\n", 635 | " pad=0.1,\n", 636 | " bboxprops=dict(color=\"#4C72B0\"),\n", 637 | " arrowprops=arrowprops)\n", 638 | " ax.add_artist(ab)\n", 639 | "\n", 640 | "# Plot the non-convergent visual image examples\n", 641 | "for column, image_id in enumerate(examples_in_bin_final[:3]):\n", 642 | " im = OffsetImage(visual_inputs[\"images\"][image_id], zoom=0.8)\n", 643 | " im.image.axes = ax\n", 644 | " xy = (205, 100)\n", 645 | " xybox = (150 - im_width * column, 100)\n", 646 | " if column == 0:\n", 647 | " arrowprops = dict(arrowstyle=\"-\u003e\", color=\"k\")\n", 648 | " else:\n", 649 | " arrowprops = None\n", 650 | " ab = AnnotationBbox(im, xy,\n", 651 | " xybox=xybox,\n", 652 | " xycoords=\"data\",\n", 653 | " boxcoords=\"data\",\n", 654 | " box_alignment=(0.5, 0.5),\n", 655 | " pad=0.1,\n", 656 | " bboxprops=dict(color=\"r\"),\n", 657 | " arrowprops=arrowprops)\n", 658 | " ax.add_artist(ab)\n", 659 | "\n", 660 | "plot_utils.setup_spines(ax)\n", 661 | "ax.set_xlabel(\"Time to convergence\")\n", 662 | "ax.set_ylabel(\"Proportion of images\")\n", 663 | "ax.set_ylim(0, 384)\n", 664 | "ax.set_yticks([0, 128, 256, 384])\n", 665 | "ax.set_yticklabels([0.0, 0.25, 0.5, 0.75])\n", 666 | "\n", 667 | "# Panels H and I. State trajectories (in PC-space) correcting with 3 particular images\n", 668 | "# Different colours show different initial rnn states\n", 669 | "colors = get_cmap(\"tab20b\").colors\n", 670 | "best_examples = np.concatenate((examples_in_bin_1[:2], examples_in_bin_final[:1]))\n", 671 | "for ex_i, (ex, label) in enumerate(zip(best_examples, [\"H)\", \"\", \"I)\", \"\"])):\n", 672 | " corr_att1_x = 2.7 + ex_i * 1.2\n", 673 | " ax = fig.add_subplots_to_figure(1, 1,\n", 674 | " corr_att1_x + 0.20, ttc_panel_coords[1]-0.4, 0.5, 0.5,\n", 675 | " text=label, text_offset=[-0.35, 0.1])[0, 0]\n", 676 | " ax.imshow(visual_inputs[\"images\"][ex])\n", 677 | " ax.set_axis_off()\n", 678 | " plot_utils.setup_spines(ax)\n", 679 | "\n", 680 | " ax = fig.add_subplots_to_figure(1, 1,\n", 681 | " corr_att1_x, ttc_panel_coords[1] + 0.3, 0.9, 0.9,\n", 682 | " text=\"\", text_offset=-0.15)[0, 0]\n", 683 | " B = attractor_states.shape[0]\n", 684 | " rnn_state = attractor_states\n", 685 | " correction_code_batch = np.tile(correction_code[[ex], :], (B, 1))\n", 686 | "\n", 687 | " state_traj = list()\n", 688 | " state_traj.append(rnn_state)\n", 689 | " rnn_state = (rnn_state, rnn_state)\n", 690 | " for t in range(T):\n", 691 | " if t % 1 == 0:\n", 692 | " out, rnn_state = step_of_correction(rnn_state, correction_code_batch)\n", 693 | " out, rnn_state = step_of_prediction(rnn_state, vel_inputs)\n", 694 | " state_traj.append(out)\n", 695 | " state_traj = np.asarray(state_traj)\n", 696 | "\n", 697 | " pc = project_on_pca(state_traj[:, :, hd_ordering])\n", 698 | " vels = pc[1:, :, :] - pc[:-1, :, :]\n", 699 | "\n", 700 | " for b in range(B):\n", 701 | " col = colors[b % len(colors)]\n", 702 | " plt.scatter(pc[0, b, 0], pc[0, b, 1], alpha=1.0, color=col)\n", 703 | " ax.quiver(pc[:-1, b, 0], pc[:-1, b, 1], vels[:, b, 0], vels[:, b, 1],\n", 704 | " scale_units=\"xy\", scale=1.0, color=col, width=0.005, headwidth=8)\n", 705 | " plt.scatter(pc[-1, b, 0], pc[-1, b, 1], alpha=1.0, color=\"k\", marker=\"x\")\n", 706 | "\n", 707 | " ax.set_xlabel(\"PC 1\")\n", 708 | " if ex_i == 0:\n", 709 | " ax.set_ylabel(\"PC 2\")\n", 710 | " ax.set_xlim(xlim_pca)\n", 711 | " ax.set_ylim(ylim_pca)\n", 712 | " ax.set_aspect(1.0)\n", 713 | " plot_utils.setup_spines(ax)" 714 | ] 715 | } 716 | ], 717 | "metadata": { 718 | "colab": { 719 | "collapsed_sections": [], 720 | "name": "figure_3.ipynb", 721 | "private_outputs": true, 722 | "provenance": [], 723 | "toc_visible": true 724 | }, 725 | "kernelspec": { 726 | "display_name": "Python 3", 727 | "name": "python3" 728 | } 729 | }, 730 | "nbformat": 4, 731 | "nbformat_minor": 0 732 | } 733 | -------------------------------------------------------------------------------- /requirements.in: -------------------------------------------------------------------------------- 1 | matplotlib==3.3.4 2 | numpy==1.21.5 3 | scipy==1.7.3 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with python 3.9 3 | # To update, run: 4 | # 5 | # pip-compile --generate-hashes requirements.in 6 | # 7 | cycler==0.11.0 \ 8 | --hash=sha256:3a27e95f763a428a739d2add979fa7494c912a32c17c4c38c4d5f082cad165a3 \ 9 | --hash=sha256:9c87405839a19696e837b3b818fed3f5f69f16f1eec1a1ad77e043dcea9c772f 10 | # via matplotlib 11 | kiwisolver==1.4.4 \ 12 | --hash=sha256:02f79693ec433cb4b5f51694e8477ae83b3205768a6fb48ffba60549080e295b \ 13 | --hash=sha256:03baab2d6b4a54ddbb43bba1a3a2d1627e82d205c5cf8f4c924dc49284b87166 \ 14 | --hash=sha256:1041feb4cda8708ce73bb4dcb9ce1ccf49d553bf87c3954bdfa46f0c3f77252c \ 15 | --hash=sha256:10ee06759482c78bdb864f4109886dff7b8a56529bc1609d4f1112b93fe6423c \ 16 | --hash=sha256:1d1573129aa0fd901076e2bfb4275a35f5b7aa60fbfb984499d661ec950320b0 \ 17 | --hash=sha256:283dffbf061a4ec60391d51e6155e372a1f7a4f5b15d59c8505339454f8989e4 \ 18 | --hash=sha256:28bc5b299f48150b5f822ce68624e445040595a4ac3d59251703779836eceff9 \ 19 | --hash=sha256:2a66fdfb34e05b705620dd567f5a03f239a088d5a3f321e7b6ac3239d22aa286 \ 20 | --hash=sha256:2e307eb9bd99801f82789b44bb45e9f541961831c7311521b13a6c85afc09767 \ 21 | --hash=sha256:2e407cb4bd5a13984a6c2c0fe1845e4e41e96f183e5e5cd4d77a857d9693494c \ 22 | --hash=sha256:2f5e60fabb7343a836360c4f0919b8cd0d6dbf08ad2ca6b9cf90bf0c76a3c4f6 \ 23 | --hash=sha256:36dafec3d6d6088d34e2de6b85f9d8e2324eb734162fba59d2ba9ed7a2043d5b \ 24 | --hash=sha256:3fe20f63c9ecee44560d0e7f116b3a747a5d7203376abeea292ab3152334d004 \ 25 | --hash=sha256:41dae968a94b1ef1897cb322b39360a0812661dba7c682aa45098eb8e193dbdf \ 26 | --hash=sha256:4bd472dbe5e136f96a4b18f295d159d7f26fd399136f5b17b08c4e5f498cd494 \ 27 | --hash=sha256:4ea39b0ccc4f5d803e3337dd46bcce60b702be4d86fd0b3d7531ef10fd99a1ac \ 28 | --hash=sha256:5853eb494c71e267912275e5586fe281444eb5e722de4e131cddf9d442615626 \ 29 | --hash=sha256:5bce61af018b0cb2055e0e72e7d65290d822d3feee430b7b8203d8a855e78766 \ 30 | --hash=sha256:6295ecd49304dcf3bfbfa45d9a081c96509e95f4b9d0eb7ee4ec0530c4a96514 \ 31 | --hash=sha256:62ac9cc684da4cf1778d07a89bf5f81b35834cb96ca523d3a7fb32509380cbf6 \ 32 | --hash=sha256:70e7c2e7b750585569564e2e5ca9845acfaa5da56ac46df68414f29fea97be9f \ 33 | --hash=sha256:7577c1987baa3adc4b3c62c33bd1118c3ef5c8ddef36f0f2c950ae0b199e100d \ 34 | --hash=sha256:75facbe9606748f43428fc91a43edb46c7ff68889b91fa31f53b58894503a191 \ 35 | --hash=sha256:787518a6789009c159453da4d6b683f468ef7a65bbde796bcea803ccf191058d \ 36 | --hash=sha256:78d6601aed50c74e0ef02f4204da1816147a6d3fbdc8b3872d263338a9052c51 \ 37 | --hash=sha256:7c43e1e1206cd421cd92e6b3280d4385d41d7166b3ed577ac20444b6995a445f \ 38 | --hash=sha256:81e38381b782cc7e1e46c4e14cd997ee6040768101aefc8fa3c24a4cc58e98f8 \ 39 | --hash=sha256:841293b17ad704d70c578f1f0013c890e219952169ce8a24ebc063eecf775454 \ 40 | --hash=sha256:872b8ca05c40d309ed13eb2e582cab0c5a05e81e987ab9c521bf05ad1d5cf5cb \ 41 | --hash=sha256:877272cf6b4b7e94c9614f9b10140e198d2186363728ed0f701c6eee1baec1da \ 42 | --hash=sha256:8c808594c88a025d4e322d5bb549282c93c8e1ba71b790f539567932722d7bd8 \ 43 | --hash=sha256:8ed58b8acf29798b036d347791141767ccf65eee7f26bde03a71c944449e53de \ 44 | --hash=sha256:91672bacaa030f92fc2f43b620d7b337fd9a5af28b0d6ed3f77afc43c4a64b5a \ 45 | --hash=sha256:968f44fdbf6dd757d12920d63b566eeb4d5b395fd2d00d29d7ef00a00582aac9 \ 46 | --hash=sha256:9f85003f5dfa867e86d53fac6f7e6f30c045673fa27b603c397753bebadc3008 \ 47 | --hash=sha256:a553dadda40fef6bfa1456dc4be49b113aa92c2a9a9e8711e955618cd69622e3 \ 48 | --hash=sha256:a68b62a02953b9841730db7797422f983935aeefceb1679f0fc85cbfbd311c32 \ 49 | --hash=sha256:abbe9fa13da955feb8202e215c4018f4bb57469b1b78c7a4c5c7b93001699938 \ 50 | --hash=sha256:ad881edc7ccb9d65b0224f4e4d05a1e85cf62d73aab798943df6d48ab0cd79a1 \ 51 | --hash=sha256:b1792d939ec70abe76f5054d3f36ed5656021dcad1322d1cc996d4e54165cef9 \ 52 | --hash=sha256:b428ef021242344340460fa4c9185d0b1f66fbdbfecc6c63eff4b7c29fad429d \ 53 | --hash=sha256:b533558eae785e33e8c148a8d9921692a9fe5aa516efbdff8606e7d87b9d5824 \ 54 | --hash=sha256:ba59c92039ec0a66103b1d5fe588fa546373587a7d68f5c96f743c3396afc04b \ 55 | --hash=sha256:bc8d3bd6c72b2dd9decf16ce70e20abcb3274ba01b4e1c96031e0c4067d1e7cd \ 56 | --hash=sha256:bc9db8a3efb3e403e4ecc6cd9489ea2bac94244f80c78e27c31dcc00d2790ac2 \ 57 | --hash=sha256:bf7d9fce9bcc4752ca4a1b80aabd38f6d19009ea5cbda0e0856983cf6d0023f5 \ 58 | --hash=sha256:c2dbb44c3f7e6c4d3487b31037b1bdbf424d97687c1747ce4ff2895795c9bf69 \ 59 | --hash=sha256:c79ebe8f3676a4c6630fd3f777f3cfecf9289666c84e775a67d1d358578dc2e3 \ 60 | --hash=sha256:c97528e64cb9ebeff9701e7938653a9951922f2a38bd847787d4a8e498cc83ae \ 61 | --hash=sha256:d0611a0a2a518464c05ddd5a3a1a0e856ccc10e67079bb17f265ad19ab3c7597 \ 62 | --hash=sha256:d06adcfa62a4431d404c31216f0f8ac97397d799cd53800e9d3efc2fbb3cf14e \ 63 | --hash=sha256:d41997519fcba4a1e46eb4a2fe31bc12f0ff957b2b81bac28db24744f333e955 \ 64 | --hash=sha256:d5b61785a9ce44e5a4b880272baa7cf6c8f48a5180c3e81c59553ba0cb0821ca \ 65 | --hash=sha256:da152d8cdcab0e56e4f45eb08b9aea6455845ec83172092f09b0e077ece2cf7a \ 66 | --hash=sha256:da7e547706e69e45d95e116e6939488d62174e033b763ab1496b4c29b76fabea \ 67 | --hash=sha256:db5283d90da4174865d520e7366801a93777201e91e79bacbac6e6927cbceede \ 68 | --hash=sha256:db608a6757adabb32f1cfe6066e39b3706d8c3aa69bbc353a5b61edad36a5cb4 \ 69 | --hash=sha256:e0ea21f66820452a3f5d1655f8704a60d66ba1191359b96541eaf457710a5fc6 \ 70 | --hash=sha256:e7da3fec7408813a7cebc9e4ec55afed2d0fd65c4754bc376bf03498d4e92686 \ 71 | --hash=sha256:e92a513161077b53447160b9bd8f522edfbed4bd9759e4c18ab05d7ef7e49408 \ 72 | --hash=sha256:ecb1fa0db7bf4cff9dac752abb19505a233c7f16684c5826d1f11ebd9472b871 \ 73 | --hash=sha256:efda5fc8cc1c61e4f639b8067d118e742b812c930f708e6667a5ce0d13499e29 \ 74 | --hash=sha256:f0a1dbdb5ecbef0d34eb77e56fcb3e95bbd7e50835d9782a45df81cc46949750 \ 75 | --hash=sha256:f0a71d85ecdd570ded8ac3d1c0f480842f49a40beb423bb8014539a9f32a5897 \ 76 | --hash=sha256:f4f270de01dd3e129a72efad823da90cc4d6aafb64c410c9033aba70db9f1ff0 \ 77 | --hash=sha256:f6cb459eea32a4e2cf18ba5fcece2dbdf496384413bc1bae15583f19e567f3b2 \ 78 | --hash=sha256:f8ad8285b01b0d4695102546b342b493b3ccc6781fc28c8c6a1bb63e95d22f09 \ 79 | --hash=sha256:f9f39e2f049db33a908319cf46624a569b36983c7c78318e9726a4cb8923b26c 80 | # via matplotlib 81 | matplotlib==3.3.4 \ 82 | --hash=sha256:1de0bb6cbfe460725f0e97b88daa8643bcf9571c18ba90bb8e41432aaeca91d6 \ 83 | --hash=sha256:1e850163579a8936eede29fad41e202b25923a0a8d5ffd08ce50fc0a97dcdc93 \ 84 | --hash=sha256:215e2a30a2090221a9481db58b770ce56b8ef46f13224ae33afe221b14b24dc1 \ 85 | --hash=sha256:348e6032f666ffd151b323342f9278b16b95d4a75dfacae84a11d2829a7816ae \ 86 | --hash=sha256:3d2eb9c1cc254d0ffa90bc96fde4b6005d09c2228f99dfd493a4219c1af99644 \ 87 | --hash=sha256:3e477db76c22929e4c6876c44f88d790aacdf3c3f8f3a90cb1975c0bf37825b0 \ 88 | --hash=sha256:451cc89cb33d6652c509fc6b588dc51c41d7246afdcc29b8624e256b7663ed1f \ 89 | --hash=sha256:46b1a60a04e6d884f0250d5cc8dc7bd21a9a96c584a7acdaab44698a44710bab \ 90 | --hash=sha256:5f571b92a536206f7958f7cb2d367ff6c9a1fa8229dc35020006e4cdd1ca0acd \ 91 | --hash=sha256:672960dd114e342b7c610bf32fb99d14227f29919894388b41553217457ba7ef \ 92 | --hash=sha256:7310e353a4a35477c7f032409966920197d7df3e757c7624fd842f3eeb307d3d \ 93 | --hash=sha256:746a1df55749629e26af7f977ea426817ca9370ad1569436608dc48d1069b87c \ 94 | --hash=sha256:7c155437ae4fd366e2700e2716564d1787700687443de46bcb895fe0f84b761d \ 95 | --hash=sha256:9265ae0fb35e29f9b8cc86c2ab0a2e3dcddc4dd9de4b85bf26c0f63fe5c1c2ca \ 96 | --hash=sha256:94bdd1d55c20e764d8aea9d471d2ae7a7b2c84445e0fa463f02e20f9730783e1 \ 97 | --hash=sha256:9a79e5dd7bb797aa611048f5b70588b23c5be05b63eefd8a0d152ac77c4243db \ 98 | --hash=sha256:a17f0a10604fac7627ec82820439e7db611722e80c408a726cd00d8c974c2fb3 \ 99 | --hash=sha256:a1acb72f095f1d58ecc2538ed1b8bca0b57df313b13db36ed34b8cdf1868e674 \ 100 | --hash=sha256:aa49571d8030ad0b9ac39708ee77bd2a22f87815e12bdee52ecaffece9313ed8 \ 101 | --hash=sha256:c24c05f645aef776e8b8931cb81e0f1632d229b42b6d216e30836e2e145a2b40 \ 102 | --hash=sha256:cf3a7e54eff792f0815dbbe9b85df2f13d739289c93d346925554f71d484be78 \ 103 | --hash=sha256:d738acfdfb65da34c91acbdb56abed46803db39af259b7f194dc96920360dbe4 \ 104 | --hash=sha256:e15fa23d844d54e7b3b7243afd53b7567ee71c721f592deb0727ee85e668f96a \ 105 | --hash=sha256:ed4a9e6dcacba56b17a0a9ac22ae2c72a35b7f0ef0693aa68574f0b2df607a89 \ 106 | --hash=sha256:f44149a0ef5b4991aaef12a93b8e8d66d6412e762745fea1faa61d98524e0ba9 107 | # via -r requirements.in 108 | numpy==1.21.5 \ 109 | --hash=sha256:00c9fa73a6989895b8815d98300a20ac993c49ac36c8277e8ffeaa3631c0dbbb \ 110 | --hash=sha256:025b497014bc33fc23897859350f284323f32a2fff7654697f5a5fc2a19e9939 \ 111 | --hash=sha256:08de8472d9f7571f9d51b27b75e827f5296295fa78817032e84464be8bb905bc \ 112 | --hash=sha256:1964db2d4a00348b7a60ee9d013c8cb0c566644a589eaa80995126eac3b99ced \ 113 | --hash=sha256:2a9add27d7fc0fdb572abc3b2486eb3b1395da71e0254c5552b2aad2a18b5441 \ 114 | --hash=sha256:2d8adfca843bc46ac199a4645233f13abf2011a0b2f4affc5c37cd552626f27b \ 115 | --hash=sha256:301e408a052fdcda5cdcf03021ebafc3c6ea093021bf9d1aa47c54d48bdad166 \ 116 | --hash=sha256:311283acf880cfcc20369201bd75da907909afc4666966c7895cbed6f9d2c640 \ 117 | --hash=sha256:341dddcfe3b7b6427a28a27baa59af5ad51baa59bfec3264f1ab287aa3b30b13 \ 118 | --hash=sha256:3a5098df115340fb17fc93867317a947e1dcd978c3888c5ddb118366095851f8 \ 119 | --hash=sha256:3c978544be9e04ed12016dd295a74283773149b48f507d69b36f91aa90a643e5 \ 120 | --hash=sha256:3d893b0871322eaa2f8c7072cdb552d8e2b27645b7875a70833c31e9274d4611 \ 121 | --hash=sha256:4fe6a006557b87b352c04596a6e3f12a57d6e5f401d804947bd3188e6b0e0e76 \ 122 | --hash=sha256:507c05c7a37b3683eb08a3ff993bd1ee1e6c752f77c2f275260533b265ecdb6c \ 123 | --hash=sha256:58ca1d7c8aef6e996112d0ce873ac9dfa1eaf4a1196b4ff7ff73880a09923ba7 \ 124 | --hash=sha256:61bada43d494515d5b122f4532af226fdb5ee08fe5b5918b111279843dc6836a \ 125 | --hash=sha256:69a5a8d71c308d7ef33ef72371c2388a90e3495dbb7993430e674006f94797d5 \ 126 | --hash=sha256:6a5928bc6241264dce5ed509e66f33676fc97f464e7a919edc672fb5532221ee \ 127 | --hash=sha256:7b9d6b14fc9a4864b08d1ba57d732b248f0e482c7b2ff55c313137e3ed4d8449 \ 128 | --hash=sha256:a7c4b701ca418cd39e28ec3b496e6388fe06de83f5f0cb74794fa31cfa384c02 \ 129 | --hash=sha256:a7e8f6216f180f3fd4efb73de5d1eaefb5f5a1ee5b645c67333033e39440e63a \ 130 | --hash=sha256:b545ebadaa2b878c8630e5bcdb97fc4096e779f335fc0f943547c1c91540c815 \ 131 | --hash=sha256:c293d3c0321996cd8ffe84215ffe5d269fd9d1d12c6f4ffe2b597a7c30d3e593 \ 132 | --hash=sha256:c5562bcc1a9b61960fc8950ade44d00e3de28f891af0acc96307c73613d18f6e \ 133 | --hash=sha256:ca9c23848292c6fe0a19d212790e62f398fd9609aaa838859be8459bfbe558aa \ 134 | --hash=sha256:cc1b30205d138d1005adb52087ff45708febbef0e420386f58664f984ef56954 \ 135 | --hash=sha256:dbce7adeb66b895c6aaa1fad796aaefc299ced597f6fbd9ceddb0dd735245354 \ 136 | --hash=sha256:dc4b2fb01f1b4ddbe2453468ea0719f4dbb1f5caa712c8b21bb3dd1480cd30d9 \ 137 | --hash=sha256:eed2afaa97ec33b4411995be12f8bdb95c87984eaa28d76cf628970c8a2d689a \ 138 | --hash=sha256:fc7a7d7b0ed72589fd8b8486b9b42a564f10b8762be8bd4d9df94b807af4a089 139 | # via 140 | # -r requirements.in 141 | # matplotlib 142 | # scipy 143 | pillow==9.2.0 \ 144 | --hash=sha256:0030fdbd926fb85844b8b92e2f9449ba89607231d3dd597a21ae72dc7fe26927 \ 145 | --hash=sha256:030e3460861488e249731c3e7ab59b07c7853838ff3b8e16aac9561bb345da14 \ 146 | --hash=sha256:0ed2c4ef2451de908c90436d6e8092e13a43992f1860275b4d8082667fbb2ffc \ 147 | --hash=sha256:136659638f61a251e8ed3b331fc6ccd124590eeff539de57c5f80ef3a9594e58 \ 148 | --hash=sha256:13b725463f32df1bfeacbf3dd197fb358ae8ebcd8c5548faa75126ea425ccb60 \ 149 | --hash=sha256:1536ad017a9f789430fb6b8be8bf99d2f214c76502becc196c6f2d9a75b01b76 \ 150 | --hash=sha256:15928f824870535c85dbf949c09d6ae7d3d6ac2d6efec80f3227f73eefba741c \ 151 | --hash=sha256:17d4cafe22f050b46d983b71c707162d63d796a1235cdf8b9d7a112e97b15bac \ 152 | --hash=sha256:1802f34298f5ba11d55e5bb09c31997dc0c6aed919658dfdf0198a2fe75d5490 \ 153 | --hash=sha256:1cc1d2451e8a3b4bfdb9caf745b58e6c7a77d2e469159b0d527a4554d73694d1 \ 154 | --hash=sha256:1fd6f5e3c0e4697fa7eb45b6e93996299f3feee73a3175fa451f49a74d092b9f \ 155 | --hash=sha256:254164c57bab4b459f14c64e93df11eff5ded575192c294a0c49270f22c5d93d \ 156 | --hash=sha256:2ad0d4df0f5ef2247e27fc790d5c9b5a0af8ade9ba340db4a73bb1a4a3e5fb4f \ 157 | --hash=sha256:2c58b24e3a63efd22554c676d81b0e57f80e0a7d3a5874a7e14ce90ec40d3069 \ 158 | --hash=sha256:2d33a11f601213dcd5718109c09a52c2a1c893e7461f0be2d6febc2879ec2402 \ 159 | --hash=sha256:336b9036127eab855beec9662ac3ea13a4544a523ae273cbf108b228ecac8437 \ 160 | --hash=sha256:337a74fd2f291c607d220c793a8135273c4c2ab001b03e601c36766005f36885 \ 161 | --hash=sha256:37ff6b522a26d0538b753f0b4e8e164fdada12db6c6f00f62145d732d8a3152e \ 162 | --hash=sha256:3d1f14f5f691f55e1b47f824ca4fdcb4b19b4323fe43cc7bb105988cad7496be \ 163 | --hash=sha256:4134d3f1ba5f15027ff5c04296f13328fecd46921424084516bdb1b2548e66ff \ 164 | --hash=sha256:4ad2f835e0ad81d1689f1b7e3fbac7b01bb8777d5a985c8962bedee0cc6d43da \ 165 | --hash=sha256:50dff9cc21826d2977ef2d2a205504034e3a4563ca6f5db739b0d1026658e004 \ 166 | --hash=sha256:510cef4a3f401c246cfd8227b300828715dd055463cdca6176c2e4036df8bd4f \ 167 | --hash=sha256:5aed7dde98403cd91d86a1115c78d8145c83078e864c1de1064f52e6feb61b20 \ 168 | --hash=sha256:69bd1a15d7ba3694631e00df8de65a8cb031911ca11f44929c97fe05eb9b6c1d \ 169 | --hash=sha256:6bf088c1ce160f50ea40764f825ec9b72ed9da25346216b91361eef8ad1b8f8c \ 170 | --hash=sha256:6e8c66f70fb539301e064f6478d7453e820d8a2c631da948a23384865cd95544 \ 171 | --hash=sha256:74a04183e6e64930b667d321524e3c5361094bb4af9083db5c301db64cd341f3 \ 172 | --hash=sha256:75e636fd3e0fb872693f23ccb8a5ff2cd578801251f3a4f6854c6a5d437d3c04 \ 173 | --hash=sha256:7761afe0126d046974a01e030ae7529ed0ca6a196de3ec6937c11df0df1bc91c \ 174 | --hash=sha256:7888310f6214f19ab2b6df90f3f06afa3df7ef7355fc025e78a3044737fab1f5 \ 175 | --hash=sha256:7b0554af24df2bf96618dac71ddada02420f946be943b181108cac55a7a2dcd4 \ 176 | --hash=sha256:7c7b502bc34f6e32ba022b4a209638f9e097d7a9098104ae420eb8186217ebbb \ 177 | --hash=sha256:808add66ea764ed97d44dda1ac4f2cfec4c1867d9efb16a33d158be79f32b8a4 \ 178 | --hash=sha256:831e648102c82f152e14c1a0938689dbb22480c548c8d4b8b248b3e50967b88c \ 179 | --hash=sha256:93689632949aff41199090eff5474f3990b6823404e45d66a5d44304e9cdc467 \ 180 | --hash=sha256:96b5e6874431df16aee0c1ba237574cb6dff1dcb173798faa6a9d8b399a05d0e \ 181 | --hash=sha256:9a54614049a18a2d6fe156e68e188da02a046a4a93cf24f373bffd977e943421 \ 182 | --hash=sha256:a138441e95562b3c078746a22f8fca8ff1c22c014f856278bdbdd89ca36cff1b \ 183 | --hash=sha256:a647c0d4478b995c5e54615a2e5360ccedd2f85e70ab57fbe817ca613d5e63b8 \ 184 | --hash=sha256:a9c9bc489f8ab30906d7a85afac4b4944a572a7432e00698a7239f44a44e6efb \ 185 | --hash=sha256:ad2277b185ebce47a63f4dc6302e30f05762b688f8dc3de55dbae4651872cdf3 \ 186 | --hash=sha256:adabc0bce035467fb537ef3e5e74f2847c8af217ee0be0455d4fec8adc0462fc \ 187 | --hash=sha256:b6d5e92df2b77665e07ddb2e4dbd6d644b78e4c0d2e9272a852627cdba0d75cf \ 188 | --hash=sha256:bc431b065722a5ad1dfb4df354fb9333b7a582a5ee39a90e6ffff688d72f27a1 \ 189 | --hash=sha256:bdd0de2d64688ecae88dd8935012c4a72681e5df632af903a1dca8c5e7aa871a \ 190 | --hash=sha256:c79698d4cd9318d9481d89a77e2d3fcaeff5486be641e60a4b49f3d2ecca4e28 \ 191 | --hash=sha256:cb6259196a589123d755380b65127ddc60f4c64b21fc3bb46ce3a6ea663659b0 \ 192 | --hash=sha256:d5b87da55a08acb586bad5c3aa3b86505f559b84f39035b233d5bf844b0834b1 \ 193 | --hash=sha256:dcd7b9c7139dc8258d164b55696ecd16c04607f1cc33ba7af86613881ffe4ac8 \ 194 | --hash=sha256:dfe4c1fedfde4e2fbc009d5ad420647f7730d719786388b7de0999bf32c0d9fd \ 195 | --hash=sha256:ea98f633d45f7e815db648fd7ff0f19e328302ac36427343e4432c84432e7ff4 \ 196 | --hash=sha256:ec52c351b35ca269cb1f8069d610fc45c5bd38c3e91f9ab4cbbf0aebc136d9c8 \ 197 | --hash=sha256:eef7592281f7c174d3d6cbfbb7ee5984a671fcd77e3fc78e973d492e9bf0eb3f \ 198 | --hash=sha256:f07f1f00e22b231dd3d9b9208692042e29792d6bd4f6639415d2f23158a80013 \ 199 | --hash=sha256:f3fac744f9b540148fa7715a435d2283b71f68bfb6d4aae24482a890aed18b59 \ 200 | --hash=sha256:fa768eff5f9f958270b081bb33581b4b569faabf8774726b283edb06617101dc \ 201 | --hash=sha256:fac2d65901fb0fdf20363fbd345c01958a742f2dc62a8dd4495af66e3ff502a4 202 | # via matplotlib 203 | pyparsing==3.0.9 \ 204 | --hash=sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb \ 205 | --hash=sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc 206 | # via matplotlib 207 | python-dateutil==2.8.2 \ 208 | --hash=sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86 \ 209 | --hash=sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9 210 | # via matplotlib 211 | scipy==1.7.3 \ 212 | --hash=sha256:033ce76ed4e9f62923e1f8124f7e2b0800db533828c853b402c7eec6e9465d80 \ 213 | --hash=sha256:173308efba2270dcd61cd45a30dfded6ec0085b4b6eb33b5eb11ab443005e088 \ 214 | --hash=sha256:21b66200cf44b1c3e86495e3a436fc7a26608f92b8d43d344457c54f1c024cbc \ 215 | --hash=sha256:2c56b820d304dffcadbbb6cbfbc2e2c79ee46ea291db17e288e73cd3c64fefa9 \ 216 | --hash=sha256:304dfaa7146cffdb75fbf6bb7c190fd7688795389ad060b970269c8576d038e9 \ 217 | --hash=sha256:3f78181a153fa21c018d346f595edd648344751d7f03ab94b398be2ad083ed3e \ 218 | --hash=sha256:4d242d13206ca4302d83d8a6388c9dfce49fc48fdd3c20efad89ba12f785bf9e \ 219 | --hash=sha256:5d1cc2c19afe3b5a546ede7e6a44ce1ff52e443d12b231823268019f608b9b12 \ 220 | --hash=sha256:5f2cfc359379c56b3a41b17ebd024109b2049f878badc1e454f31418c3a18436 \ 221 | --hash=sha256:65bd52bf55f9a1071398557394203d881384d27b9c2cad7df9a027170aeaef93 \ 222 | --hash=sha256:7edd9a311299a61e9919ea4192dd477395b50c014cdc1a1ac572d7c27e2207fa \ 223 | --hash=sha256:8499d9dd1459dc0d0fe68db0832c3d5fc1361ae8e13d05e6849b358dc3f2c279 \ 224 | --hash=sha256:866ada14a95b083dd727a845a764cf95dd13ba3dc69a16b99038001b05439709 \ 225 | --hash=sha256:87069cf875f0262a6e3187ab0f419f5b4280d3dcf4811ef9613c605f6e4dca95 \ 226 | --hash=sha256:93378f3d14fff07572392ce6a6a2ceb3a1f237733bd6dcb9eb6a2b29b0d19085 \ 227 | --hash=sha256:95c2d250074cfa76715d58830579c64dff7354484b284c2b8b87e5a38321672c \ 228 | --hash=sha256:ab5875facfdef77e0a47d5fd39ea178b58e60e454a4c85aa1e52fcb80db7babf \ 229 | --hash=sha256:b0e0aeb061a1d7dcd2ed59ea57ee56c9b23dd60100825f98238c06ee5cc4467e \ 230 | --hash=sha256:b78a35c5c74d336f42f44106174b9851c783184a85a3fe3e68857259b37b9ffb \ 231 | --hash=sha256:c9e04d7e9b03a8a6ac2045f7c5ef741be86727d8f49c45db45f244bdd2bcff17 \ 232 | --hash=sha256:ca36e7d9430f7481fc7d11e015ae16fbd5575615a8e9060538104778be84addf \ 233 | --hash=sha256:ceebc3c4f6a109777c0053dfa0282fddb8893eddfb0d598574acfb734a926168 \ 234 | --hash=sha256:e2c036492e673aad1b7b0d0ccdc0cb30a968353d2c4bf92ac8e73509e1bf212c \ 235 | --hash=sha256:eb326658f9b73c07081300daba90a8746543b5ea177184daed26528273157294 \ 236 | --hash=sha256:eb7ae2c4dbdb3c9247e07acc532f91077ae6dbc40ad5bd5dca0bb5a176ee9bda \ 237 | --hash=sha256:edad1cf5b2ce1912c4d8ddad20e11d333165552aba262c882e28c78bbc09dbf6 \ 238 | --hash=sha256:eef93a446114ac0193a7b714ce67659db80caf940f3232bad63f4c7a81bc18df \ 239 | --hash=sha256:f7eaea089345a35130bc9a39b89ec1ff69c208efa97b3f8b25ea5d4c41d88094 \ 240 | --hash=sha256:f99d206db1f1ae735a8192ab93bd6028f3a42f6fa08467d37a14eb96c9dd34a3 241 | # via -r requirements.in 242 | six==1.16.0 \ 243 | --hash=sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926 \ 244 | --hash=sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254 245 | # via python-dateutil 246 | -------------------------------------------------------------------------------- /src/classify_units.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 DeepMind Technologies Limited 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Classify units according to measureas used for biological cells.""" 16 | import numpy as np 17 | 18 | from spatial_memory_pipeline import scores 19 | 20 | 21 | def _make_intervals(x): 22 | """Given [0, 1, 2], return [-0.5, 0.5, 1.5, 2.5].""" 23 | d = np.diff(x) 24 | return np.concatenate([ 25 | [x[0] - d[0] / 2.0], # first interval's left bound 26 | x[:-1] + d / 2.0, # interval separations 27 | [x[-1] + d[-1] / 2.0] # last interval's right bound 28 | ]) 29 | 30 | 31 | def _rotate_distances(distances, hd): 32 | """Rotate allocentric distances to egocentric according to head direction. 33 | 34 | Args: 35 | distances: Array of shape [B, n_angles].`n_angles` the number of angles in 36 | the rat's distance sensor. The values are the distances to the closest 37 | wall for each world (allocentric) angle. The angles they correspond to are 38 | supposed to be equispaced at 2 * pi / `n_angles` rad of each other. 39 | hd: Array of shape [B]. For each distance, the corresponding allocentric 40 | head direction, in radians. 41 | 42 | Returns: 43 | Array of same shape as `distances`, each row shifted (rotated) to make 44 | the distances egocentric. 45 | Raises: 46 | ValueError: The dimensions of `distances` and/or `hd` are not as expected. 47 | """ 48 | hd = hd.squeeze() # it comes with trailing dimension typically 49 | if hd.ndim != 1: 50 | raise ValueError("Head direction should be a vector.") 51 | if distances.ndim != 2: 52 | raise ValueError("Distances should be a 2-D array.") 53 | if hd.shape[0] != distances.shape[0]: 54 | raise ValueError("Head direction should have same batch size as distances.") 55 | n_angles = distances.shape[1] 56 | shifts = np.mod(-np.round(n_angles * hd / (2 * np.pi)).astype(np.int), 57 | n_angles) 58 | r_idx, c_idx = np.ogrid[:distances.shape[0], :distances.shape[1]] 59 | c_idx = c_idx - shifts[:, None] 60 | return distances[r_idx, c_idx] 61 | 62 | 63 | def bvc_rms_egocentric(activations, world_distances, hd, distances, **kwargs): 64 | ego_distances = _rotate_distances(world_distances, hd) 65 | return bvc_rms(activations, ego_distances, distances, **kwargs) 66 | 67 | 68 | def bvc_rms_allocentric(activations, world_distances, unused_hd, distances, 69 | **kwargs): 70 | return bvc_rms(activations, world_distances, distances, **kwargs) 71 | 72 | 73 | def bvc_rms(activations, world_distances, distances, for_plotting=False): 74 | """Compute boundary vector cell (BVC) ratemaps. 75 | 76 | Computes the mean activation binned by distance and (allocentric) 77 | angle to the nearest wall. The angular binning is the same as in the 78 | `world_distances` matrix. The distance binning is the one in distances. 79 | 80 | Args: 81 | activations: Array of shape [B, n_units]. `B` is the batch size, `n_units` 82 | the size of an the RNN layer we want to compute score for. 83 | world_distances: Array of shape [B, n_angles]. `B` is the same batch size as 84 | activations, `n_angles` the number of angles in the rat's distance sensor. 85 | The values are the distances to the closest wall for each world 86 | (allocentric) angle. 87 | distances: Distance binning edges. 88 | for_plotting: Boolean that indicates whether to have a final pi angle as it 89 | makes the radar plots look better. 90 | 91 | Returns: 92 | A 3-tuple of: 93 | distances: vector of bin centers for BVC distances. 94 | angles: vector of bin centers for BVC angles. 95 | correlations: a [n_distances, n_angles, n_units] matrix 96 | with the mean activations for each distance and angle bin. 97 | """ 98 | n_angles = world_distances.shape[1] 99 | if for_plotting: 100 | angles = np.linspace(-np.pi, np.pi, n_angles + 1) 101 | else: 102 | angles = np.linspace(-np.pi, np.pi, n_angles + 1)[:-1] 103 | 104 | # Create bins of distances instead of real-values 105 | distance_edges = _make_intervals(distances) 106 | distance_bins = np.digitize(world_distances, distance_edges) 107 | 108 | bin_counts = np.apply_along_axis( 109 | np.bincount, 110 | 0, 111 | distance_bins, 112 | weights=None, 113 | minlength=len(distance_edges) + 1) 114 | n_units = activations.shape[1] 115 | rms = [] 116 | for unit_idx in range(n_units): 117 | rms.append( 118 | np.apply_along_axis( 119 | np.bincount, 120 | 0, 121 | distance_bins, 122 | weights=activations[:, unit_idx], 123 | minlength=len(distance_edges) + 1) / (bin_counts + 1e-12)) 124 | return distances, angles, np.dstack(rms)[1:-1, ...] 125 | 126 | 127 | def get_resvec_shuffled_bins_threshold(ang_rmaps, 128 | percentile=99, 129 | n_shuffles=1000): 130 | """Get the percentile of resvec length after shuffling bins. 131 | 132 | Args: 133 | ang_rmaps: angular ratemaps. 134 | percentile: percentile of resvec lengths to return. 135 | n_shuffles: number of times to shuffle each unit. 136 | 137 | Returns: 138 | The resultant vector length threshold. 139 | """ 140 | assert ang_rmaps.ndim == 2 141 | nbins, n_units = ang_rmaps.shape 142 | rv_scorer = scores.ResultantVectorHeadDirectionScorer(nbins) 143 | shuffle_rv_lens = np.asarray([ 144 | rv_scorer.resultant_vector_score( 145 | np.random.permutation(ang_rmaps[:, i % n_units])) 146 | for i in range(n_units * n_shuffles) 147 | ]).flatten() 148 | return np.percentile(shuffle_rv_lens, percentile) 149 | 150 | 151 | def get_hd_shuffled_bins_threshold(activations, 152 | hds, 153 | n_bins=20, 154 | percentile=99, 155 | n_shuffles=1000): 156 | """Calculate the resvec length threshold for HD cells. 157 | 158 | Args: 159 | activations: array of cells activations. 160 | hds: head direction of the agent. 161 | n_bins: number of head-direction bins to use. 162 | percentile: percentile of shuffled resvec lengths to return. 163 | n_shuffles: number of bin shuffles to use. 164 | 165 | Returns: 166 | The resultant vector length threshold. 167 | """ 168 | rv_scorer = scores.ResultantVectorHeadDirectionScorer(n_bins) 169 | n_units = activations.shape[-1] 170 | ang_rmaps = np.asarray([ 171 | rv_scorer.calculate_hd_ratemap(hds[:, 0], activations[:, i]) 172 | for i in range(n_units) 173 | ]).T 174 | return get_resvec_shuffled_bins_threshold( 175 | ang_rmaps, percentile=percentile, n_shuffles=n_shuffles) 176 | 177 | 178 | def get_hd_cell_parameters(acts, hds, threshold, n_bins=20): 179 | """Calculate which cells are head-direction and their preferred angle. 180 | 181 | Args: 182 | acts: array of cells activations. 183 | hds: head direction of the agent. 184 | threshold: resvec length at which a unit is considered head-direciton cell. 185 | n_bins: number of head-direction bins to use. 186 | 187 | Returns: 188 | Array of bools indicating which cells are HD cells, Array of resvec lengths, 189 | and Array of preferred head-direction angles. 190 | """ 191 | rv_scorer = scores.ResultantVectorHeadDirectionScorer(n_bins) 192 | n_units = acts.shape[-1] 193 | ang_rmaps = [rv_scorer.calculate_hd_ratemap(hds[:, 0], acts[:, i]) 194 | for i in range(n_units)] 195 | rv_lens = np.asarray([rv_scorer.resultant_vector_score(ang_rmaps[i]) 196 | for i in range(n_units)]).flatten() 197 | rv_angles = np.asarray([rv_scorer.resultant_vector_angle(ang_rmaps[i]) 198 | for i in range(n_units)]).flatten() 199 | return rv_lens > threshold, rv_lens, rv_angles 200 | 201 | 202 | def get_bvc_cell_parameters(rms_dists, 203 | rms_angs, 204 | rms_vals, 205 | threshold, 206 | unused_distance_step=2.5): 207 | """Calculate which cells are bvc and their preferred distance and angle. 208 | 209 | Args: 210 | rms_dists: Distances in the rms data. 211 | rms_angs: Angles in the rms data. 212 | rms_vals: Array of activity of shape [n_distances, n_angles, n_units]. 213 | threshold: resultant vector length threshold to consider a cell bvc. 214 | unused_distance_step: unused parameter. 215 | 216 | Returns: 217 | Array of bools indicating which cells are BVC cells, Array of preferred 218 | angles, Array of preferred distances, and array of resvec lengths. 219 | """ 220 | _, n_angles, n_units = rms_vals.shape 221 | l = rms_vals.sum(axis=0) 222 | y = np.sum(np.sin(rms_angs)[:, np.newaxis] * l, axis=0) 223 | x = np.sum(np.cos(rms_angs)[:, np.newaxis] * l, axis=0) 224 | 225 | # In order to make this consistent with the ResVec scorer used for the HD 226 | # cells, use arctan(x, y). 227 | # This makes the normal angle be pi/2 - angle returned by arctan 228 | bvc_angles = np.arctan2(x, y) 229 | 230 | bvc_orig_angles = np.arctan2(y, x) 231 | bvcbins = ( 232 | np.digitize(bvc_orig_angles, np.concatenate([rms_angs, [np.pi]])) - 1) 233 | bvc_dists = rms_dists[np.argmax( 234 | rms_vals[:, bvcbins, range(len(bvcbins))], axis=0)] 235 | rv_scorer = scores.ResultantVectorHeadDirectionScorer(n_angles) 236 | rvls = [rv_scorer.resultant_vector_score(rms_vals[..., i].sum(axis=0))[0] 237 | for i in range(n_units)] 238 | rvls = np.asarray(rvls) 239 | is_bvc = (rvls > threshold) 240 | return is_bvc, bvc_angles, bvc_dists, rvls 241 | 242 | 243 | def classify_units_into_representations(activities, hds, pos, wall_distances, 244 | n_shuffles=1000, 245 | distance_bin_size=0.025, 246 | percentile=99): 247 | """Identify which cells are HD, egoBVC or alloBVC (non-exclusive). 248 | 249 | Args: 250 | activities: array of cells activations. 251 | hds: array head-direction of the agent. 252 | pos: array of position of the agent in the enclosure. 253 | wall_distances: array of distances to walls at each time-step. 254 | n_shuffles: number of shuffles used in calculating the thresholds. 255 | distance_bin_size: size of distance bins. 256 | percentile: percentile of score in the shuffled data to use as threshold. 257 | 258 | Returns: 259 | Tuple of 260 | (whether each cell is a head direction cell, 261 | head-direction resvec length threshold, 262 | hd score of each cell, 263 | head-direction resultant-vector length of each cell, 264 | preferred head direction of each cell, 265 | whether each cell is an egocentric boundary cell, 266 | ego-bvc resvec threshold, 267 | ego-bcv score for each cell, 268 | preferred egocentric boundary distance to wall of each cell, 269 | preferred egocentric boundary angle to wall of each cell, 270 | whether each cell is an allocentric boundary cell, 271 | ego-bvc resvec threshold, 272 | ego-bcv score for each cell, 273 | preferred allocentric boundary distance to wall of each cell, 274 | preferred allocentric boundary angle to wall of each cell) 275 | """ 276 | # Calculate preferred wall distances up to half of the enclosure size 277 | max_d = (pos[:, 0].max() - pos[:, 0].min()) / 2 278 | distances = np.arange(distance_bin_size, max_d, distance_bin_size) 279 | 280 | # Identify head-direction cells 281 | hd_threshold = get_hd_shuffled_bins_threshold( 282 | activities, hds, percentile=percentile, n_shuffles=n_shuffles) 283 | is_hd, hd_rv_lens, hd_rv_angles = get_hd_cell_parameters( 284 | activities, hds, hd_threshold, n_bins=20) 285 | hd_score = hd_rv_lens 286 | 287 | # Identify egocentric-boundary cells 288 | erms_dists, erms_angs, erms_vals = bvc_rms_egocentric( 289 | activities, wall_distances, hds, distances) 290 | ego_threshold = get_resvec_shuffled_bins_threshold( 291 | erms_vals.sum(axis=0), percentile=percentile, n_shuffles=n_shuffles) 292 | is_ego, ego_angle, ego_dist, ego_score = get_bvc_cell_parameters( 293 | erms_dists, erms_angs, erms_vals, ego_threshold) 294 | 295 | # Identify allocentric boundary cells 296 | arms_dists, arms_angs, arms_vals = bvc_rms_allocentric( 297 | activities, wall_distances, hds, distances) 298 | allo_threshold = get_resvec_shuffled_bins_threshold( 299 | arms_vals.sum(axis=0), percentile=percentile, n_shuffles=n_shuffles) 300 | is_allo, allo_angle, allo_dist, allo_score = get_bvc_cell_parameters( 301 | arms_dists, arms_angs, arms_vals, allo_threshold) 302 | 303 | return (is_hd, hd_threshold, hd_score, hd_rv_lens, hd_rv_angles, 304 | is_ego, ego_threshold, ego_score, ego_dist, ego_angle, 305 | is_allo, allo_threshold, allo_score, allo_dist, allo_angle) 306 | -------------------------------------------------------------------------------- /src/dataset.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 DeepMind Technologies Limited 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Load datasets used in the figures.""" 16 | import pickle 17 | import shutil 18 | import subprocess 19 | import numpy as np 20 | import requests 21 | import tree 22 | 23 | 24 | BUCKET_PATH = 'https://storage.googleapis.com/dm_spatial_memory_pipeline/' 25 | FIG2_FILES = ['trajectories.pickle'] 26 | FIG3_FILES = ['hd_stats.pickle', 'parameters.pickle', 'visual_inputs.pickle'] 27 | 28 | LOCAL_PATH = 'spatial_memory_pipeline_data' 29 | 30 | FIG2_TRAJECTORIES_PATH = f'./{LOCAL_PATH}/trajectories.pickle' 31 | FIG3_PARAMETERS_PATH = f'./{LOCAL_PATH}/parameters.pickle' 32 | FIG3_VISUAL_INPUTS_PATH = f'./{LOCAL_PATH}/visual_inputs.pickle' 33 | FIG3_HD_STATS_PATH = f'./{LOCAL_PATH}/hd_stats.pickle' 34 | 35 | 36 | def _download_files(filenames): 37 | subprocess.check_call(['mkdir', '-p', f'{LOCAL_PATH}']) 38 | for fname in filenames: 39 | url = f'{BUCKET_PATH}{fname}' 40 | dest = f'{LOCAL_PATH}/{fname}' 41 | print(f'Downloading: {url}') 42 | with requests.get(url, stream=True) as r, open(dest, 'wb') as w: 43 | r.raise_for_status() 44 | shutil.copyfileobj(r.raw, w) 45 | 46 | 47 | def download_figure2_files(): 48 | _download_files(FIG2_FILES) 49 | 50 | 51 | def download_figure3_files(): 52 | _download_files(FIG3_FILES) 53 | 54 | 55 | def load_figure_2_trajectories(): 56 | with open(FIG2_TRAJECTORIES_PATH, 'rb') as fh: 57 | trajectories = pickle.load(fh) 58 | return trajectories 59 | 60 | 61 | def load_figure_3_parameters(): 62 | with open(FIG3_PARAMETERS_PATH, 'rb') as fh: 63 | parameters = pickle.load(fh) 64 | return parameters 65 | 66 | 67 | def load_figure_3_hd_stats(): 68 | with open(FIG3_HD_STATS_PATH, 'rb') as fh: 69 | hd_stats = pickle.load(fh) 70 | return hd_stats 71 | 72 | 73 | def load_figure_3_visual_inputs(): 74 | with open(FIG3_VISUAL_INPUTS_PATH, 'rb') as fh: 75 | visual_inputs = pickle.load(fh) 76 | return visual_inputs 77 | 78 | 79 | def flatten_trajectories(traj_ds): 80 | """Turn a trajectory dataset into a sample dataset, and add a time field.""" 81 | def _flatten(x): 82 | """Flatten the first 2 dims of fields with > 2 dims.""" 83 | if isinstance(x, np.ndarray) and x.ndim > 2: 84 | return np.reshape(x, (-1,) + x.shape[2:]) 85 | else: 86 | return x 87 | ds = tree.map_structure(_flatten, traj_ds) 88 | return ds 89 | 90 | 91 | def description(x): 92 | if isinstance(x, dict): 93 | return '\n'.join([f'{k}: {description(v)}' for k, v in sorted(x.items())]) 94 | if isinstance(x, np.ndarray): 95 | return f'array{x.shape}' 96 | elif isinstance(x, list): 97 | return f'list({", ".join([description(k) for k in x])})' 98 | -------------------------------------------------------------------------------- /src/plot_utils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 DeepMind Technologies Limited 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Plotting utils.""" 16 | import matplotlib 17 | import matplotlib.pyplot as plt 18 | import numpy as np 19 | 20 | 21 | def octant_grid(rms, rms_octants): 22 | """Put main rms and the 8 octant rmss in a single figure. 23 | 24 | Args: 25 | rms: H x W array. 26 | rms_octants: H x W x 8 array, assuming the i-th 3D slice corresponds to the 27 | i-th octant (0=octant centered at 0 degrees, 1 octant centered at 45 28 | degrees, etc.) 29 | 30 | Returns: 31 | (3H + padding) x (3W + padding) array with the individual rms in correct 32 | order to be plotted. 33 | """ 34 | 35 | all_rms = np.dstack((rms_octants, rms)) 36 | padded_rms = np.zeros((all_rms.shape[0] + 2, all_rms.shape[1] + 2, 9)) 37 | padded_rms[1:-1, 1:-1, :] = all_rms 38 | h, w = padded_rms.shape[:2] 39 | display_order = [[5, 4, 3], [6, 8, 2], [7, 0, 1]] 40 | grid = padded_rms[..., display_order] # H x W x 3 x 3 41 | grid = np.rollaxis(grid, 2, 0) # 3 x H x W x 3 42 | grid = np.rollaxis(grid, 3, 2) # 3 x H x 3 x W 43 | return grid.reshape(3 * h, 3 * w) 44 | 45 | 46 | def setup_spines(ax, lw=1.5): 47 | for sp in ax.spines.values(): 48 | sp.set_linewidth(lw) 49 | sp.set_color("#333333") 50 | 51 | 52 | def imshow(ax, image): 53 | ax.imshow(image, origin="lower", interpolation="none") 54 | ax.set_axis_off() 55 | 56 | 57 | def prop_hist(ax, data, bins, polar=False, **kwargs): 58 | hist = np.histogram(data, bins=bins)[0] 59 | hist = hist / len(data) 60 | # For polar plots we want the *area* to be determined 61 | # by the proportion, not the radius 62 | if polar: 63 | hist = np.sqrt(hist) 64 | w = (bins.max() - bins.min()) / (len(bins) - 1) 65 | ax.bar(bins[:-1] + w/2, hist, width=w, **kwargs) 66 | 67 | 68 | def octant_ratemap_to_rgb(rms, per_octant, min_perc=0, max_perc=100, 69 | cmap="jet"): 70 | """Produce an rgb image from per-octant ratemaps. 71 | 72 | Normally we would let plt.imshow normalize values automatically when 73 | it applies the colormap, but since we can have nans and we may want to 74 | make a grid of octants (where the values between the octants would be 75 | meaninglessly color-mapped) we have to convert the ratemap to rgb color 76 | before we do imshow, so we normalize it manually. 77 | 78 | Args: 79 | rms: a 2-tuple with (H x W, H x W x 8) global and per-octant ratemaps. 80 | per_octant: (bool) If True, we'll return a per-octant rgb grid, otherwise 81 | just the normalized RGB global ratemap. 82 | min_perc: (float, default 0) Percentile of the range of ratemap values 83 | to use as the bottom of the color scale. 84 | max_perc: (float, default 100) Percentile of the range of ratemap values 85 | to use as the top of the color scale. 86 | cmap: (str) Name of the colormap to use. 87 | Returns: 88 | A single RGB image with the ratemap or the 9 per-octant + global grid. 89 | """ 90 | data = np.ravel(rms[0]) 91 | if per_octant: 92 | data = np.concatenate((data, np.ravel(rms[1]))) 93 | lims = np.nanpercentile(data, [min_perc, max_perc]) 94 | center_rms = (rms[0] - lims[0]) / (lims[1] - lims[0] + 1e-16) 95 | the_rims = None 96 | if per_octant: 97 | side_rms = (rms[1] - lims[0]) / (lims[1] - lims[0] + 1e-16) 98 | center_rms = octant_grid(center_rms + 1, side_rms + 1) 99 | the_rims = center_rms == 0 100 | center_rms -= 1 101 | center_rms[the_rims] = 0 102 | 103 | rms = center_rms 104 | nans = np.isnan(rms) 105 | rms[nans] = lims[0] 106 | rms = matplotlib.cm.get_cmap(cmap)(rms)[..., :3] # to rgb, discard alpha 107 | rms[nans] = 1.0 108 | if the_rims is not None: 109 | rms[the_rims] = 1.0 110 | return rms 111 | 112 | 113 | class SuperFigure(object): 114 | """Plotting figures with lettered subpanels.""" 115 | 116 | def __init__(self, width_inches, height_inches, dpi=200, **kwargs): 117 | self._dpi = dpi 118 | self._wi = width_inches 119 | self._hi = height_inches 120 | kwargs["figsize"] = (width_inches * dpi / 72, height_inches * dpi / 72) 121 | kwargs["dpi"] = 72 122 | self._fig, self._allax = plt.subplots(1, 1, **kwargs) 123 | self._allax.set_axis_off() 124 | self.label_letter = "A" 125 | self.label_suffix = ")" 126 | 127 | def next_label(self): 128 | curr = self.label_letter 129 | self.label_letter = chr(ord(self.label_letter) + 1) 130 | return curr + self.label_suffix 131 | 132 | def add_subplots_to_figure(self, n_rows, n_cols, pos_x, pos_y, width, height, 133 | hspace=0.1, vspace=0.1, text=None, text_offset=0.0, 134 | **subplot_kw): 135 | """Add a grid of subplots. 136 | 137 | Args: 138 | n_rows: Number of rows of subplots to add. 139 | n_cols: Number of columns of subplots to add. 140 | pos_x: x position in the figure of the top-left subplot. 141 | pos_y: y position in the figure of the top-left subplot. 142 | width: width of each subplot. 143 | height: height of each subplot. 144 | hspace: horizontal space between subplot columns. 145 | vspace: vertical space between subplot rows. 146 | text: text next to the top-left subplot for referring to the panel. 147 | text_offset: x offset of the text for fine-tuning the look. 148 | **subplot_kw: dictionary of extra parameters in subplot creation. 149 | 150 | Returns: 151 | An array of matplotlib axes. 152 | """ 153 | try: 154 | text_offset = np.asarray(text_offset).reshape([2]) 155 | except ValueError: 156 | text_offset = np.asarray([text_offset, 0]).reshape([2]) 157 | if text is not None: 158 | self.add_text(pos_x + text_offset[0], pos_y + text_offset[1], text, 159 | fontsize=9) 160 | 161 | size_inches = self._fig.get_size_inches() / (self._dpi / 72.0) 162 | # Inches to relative 163 | pos_x /= size_inches[0] 164 | pos_y /= size_inches[1] 165 | width /= size_inches[0] 166 | height /= size_inches[1] 167 | hspace /= size_inches[0] 168 | vspace /= size_inches[1] 169 | 170 | # Use distance in inches from the top, not from the bottom 171 | pos_y = 1 - (pos_y + height * n_rows + vspace * (n_rows - 1)) 172 | 173 | axs = np.empty((n_rows, n_cols), dtype=object) 174 | for row in range(n_rows): 175 | for col in range(n_cols): 176 | axs[row, col] = self._fig.add_axes((pos_x + col * (hspace + width), 177 | pos_y - row * (vspace + height), 178 | width, height), **subplot_kw) 179 | return axs 180 | 181 | def add_text(self, pos_x, pos_y, text, fontsize=9): 182 | if text == "auto": 183 | text = self.next_label() 184 | size_inches = self._fig.get_size_inches() / (self._dpi / 72.0) 185 | pos_x /= size_inches[0] 186 | pos_y /= size_inches[1] 187 | pos_y = 1 - pos_y 188 | self._fig.text( 189 | pos_x, 190 | pos_y, 191 | text, 192 | horizontalalignment="right", 193 | verticalalignment="bottom", 194 | fontsize=fontsize * self._dpi / 72) 195 | 196 | def show(self): 197 | return self._fig 198 | 199 | -------------------------------------------------------------------------------- /src/scores.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 DeepMind Technologies Limited 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Cell-type score calculations.""" 16 | import matplotlib.pyplot as plt 17 | import numpy as np 18 | import scipy.signal 19 | import scipy.spatial 20 | import scipy.stats 21 | 22 | 23 | def positional_correlations_manipulation(pos, hds, acts, pos_b, hds_b, acts_b): 24 | """Positional correlation between two datasets.""" 25 | pos_corr = list() 26 | for unit in range(acts.shape[1]): 27 | ratemap_a = calculate_ratemap( 28 | pos[:, 0], pos[:, 1], acts[:, unit], 29 | hd=hds[:])[0][0].reshape([1, -1]) 30 | ratemap_b = calculate_ratemap( 31 | pos_b[:, 0], pos_b[:, 1], acts_b[:, unit], 32 | hd=hds_b[:])[0][0].reshape([1, -1]) 33 | not_nan = np.logical_and(np.isfinite(ratemap_a), np.isfinite(ratemap_b)) 34 | cc = np.corrcoef(ratemap_a[not_nan], ratemap_b[not_nan])[0, 1] 35 | pos_corr.append(cc) 36 | return np.asarray(pos_corr) 37 | 38 | 39 | def positional_correlations(pos, hds, acts): 40 | """Spatial stability as the correlation between two halves of data.""" 41 | half = pos.shape[0] // 2 42 | return positional_correlations_manipulation(pos[:half, ...], 43 | hds[:half], 44 | acts[:half, ...], 45 | pos[half:, ...], 46 | hds[half:], 47 | acts[half:, ...]) 48 | 49 | 50 | def calculate_ratemap(xs, 51 | ys, 52 | activations, 53 | bin_size=0.14, # to divide 2.2 meters into 16 bins 54 | coords_range=None, 55 | statistic="mean", 56 | hd=None): 57 | """Calculate 2D arrays of activations binned by spatial location. 58 | 59 | Args: 60 | xs: vector of length B with the x position of the agent. 61 | ys: vector of length B with the y position of the agent. 62 | activations: vector of length B with the activation of one cell at each 63 | position. 64 | bin_size: In distance units, for binning across both dimensions. 65 | coords_range: A pair of tuples ((xmin, xmax), (ymin, ymax)). If not given, 66 | the `xs` and `ys` ranges are used. 67 | statistic: What to compute over activations in each bin. 68 | hd: Optional. The head directions corresponding to each position. 69 | If given, not one but 9 ratemaps will be computed: the general 70 | one and one for each head-direction octant. 71 | Returns: 72 | A 3-tuple: 73 | The first element is the 2d ratemap if `hd` is None. If `hd` 74 | is given, it will be a 2-tuple, where the first one is the 75 | normal ratemap and second is a H x W x 8 per-octant ratemap, octants 76 | being [-pi/8, pi/8], [pi/8, 3pi/8], [3pi/8, 5pi/8], [5pi/8, 7pi/8], 77 | [-7pi/8, -7pi/8], [-7pi/8, -5pi/8], [-5pi/8, -3pi/8], and 78 | [-3pi/8, -pi/8]. 79 | The second and third elements are the x and y edges used for binning. 80 | """ 81 | def _get_edges(min_v, max_v): 82 | v_range = max_v - min_v 83 | n_bins = np.ceil(v_range / bin_size).astype(int) 84 | pad = (n_bins * bin_size - v_range) / 2 85 | return np.linspace(min_v - pad / 2, max_v + pad / 2, n_bins + 1) 86 | 87 | if coords_range is None: 88 | coords_range = ((xs.min(), xs.max()), (ys.min(), ys.max())) 89 | x_edges = _get_edges(coords_range[0][0], coords_range[0][1]) 90 | y_edges = _get_edges(coords_range[1][0], coords_range[1][1]) 91 | rms = scipy.stats.binned_statistic_2d( 92 | xs, ys, activations, bins=(x_edges, y_edges), statistic=statistic)[0] 93 | if hd is not None: 94 | octants = np.mod(np.round(np.squeeze(hd) / (np.pi / 4)), 8) 95 | octant_edges = np.linspace(-0.5, 7.5, 9) 96 | octant_rms = scipy.stats.binned_statistic_dd( 97 | (xs, ys, octants), activations, 98 | bins=(x_edges, y_edges, octant_edges), 99 | statistic=statistic)[0] 100 | rms = (rms, octant_rms) 101 | 102 | return rms, x_edges, y_edges 103 | 104 | 105 | class ResultantVectorHeadDirectionScorer(object): 106 | """Class for scoring correlation between activation and head-direction.""" 107 | 108 | def __init__(self, nbins): 109 | """Constructor. 110 | 111 | Args: 112 | nbins: Number of bins for the angle. 113 | """ 114 | self._bins = np.linspace(-np.pi, np.pi, nbins + 1) 115 | self._bin_centers = 0.5 * self._bins[:-1] + 0.5 * self._bins[1:] 116 | self._bin_vectors = np.asarray( 117 | [np.cos(self._bin_centers), 118 | np.sin(self._bin_centers)]).T # n_bins x 2 119 | 120 | def calculate_hd_ratemap(self, hds, activations, statistic="mean"): 121 | hds = np.arctan2(np.sin(hds), np.cos(hds)) 122 | total_bin_act = scipy.stats.binned_statistic( 123 | hds, 124 | activations, 125 | bins=self._bins, 126 | statistic=statistic, 127 | range=(-np.pi, np.pi))[0] 128 | return total_bin_act 129 | 130 | def resultant_vector(self, ratemaps): 131 | if ratemaps.ndim == 1: 132 | ratemaps = ratemaps[np.newaxis, :] 133 | resv = (np.matmul(ratemaps, self._bin_vectors) / 134 | (np.sum(ratemaps, axis=1)[:, np.newaxis] + 1e-5)) 135 | return resv 136 | 137 | def resultant_vector_score(self, ratemaps): 138 | resv = self.resultant_vector(ratemaps) 139 | return np.hypot(resv[:, 0], resv[:, 1]) 140 | 141 | def resultant_vector_angle(self, ratemaps): 142 | resv = self.resultant_vector(ratemaps) 143 | return np.arctan2(resv[:, 0], resv[:, 1]) 144 | 145 | def plot_polarplot(self, 146 | ratemaps, 147 | ax=None, 148 | title=None, 149 | relative=False, 150 | positive_lobe_color="b", 151 | negative_lobe_color="r", 152 | **kwargs): 153 | """ratemaps: list of ratemaps.""" 154 | if isinstance(ratemaps, list): 155 | ratemaps = np.asarray(ratemaps, dtype=np.float32) 156 | if ax is None: 157 | ax = plt.gca() 158 | # Plot the ratemap 159 | for i in range(ratemaps.shape[0]): 160 | ang = np.append(self._bin_centers, [self._bin_centers[0]], axis=0) 161 | pos_rm = ratemaps[i] * (ratemaps[i] > 0) 162 | pos_lens = np.append(pos_rm, [pos_rm[0]], axis=0) 163 | neg_rm = -ratemaps[i] * (ratemaps[i] < 0) 164 | neg_lens = np.append(neg_rm, [neg_rm[0]], axis=0) 165 | if relative: 166 | pos_lens /= pos_lens.sum() 167 | neg_lens /= neg_lens.sum() 168 | # Our ratemap convention is first coordinate positive up, second 169 | # coordinate positive right. To have the same orientation in polar 170 | # plots we do pi/2 - angle 171 | ax.plot(np.pi / 2 - ang, pos_lens, color=positive_lobe_color, **kwargs) 172 | ax.plot(np.pi / 2 - ang, neg_lens, color=negative_lobe_color, **kwargs) 173 | if title is not None: 174 | ax.set_title(title) 175 | --------------------------------------------------------------------------------