File size: 11,912 Bytes
e11c92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "713d155f",
   "metadata": {},
   "source": [
    "# Visualisations of MARBLE embeddings\n",
    "\n",
    "This notebook visualises the MARBLE latent representations of the macaque arm-reaching data obtained from binned spike counts with 20ms bin size.\n",
    "\n",
    "We would like to thank the authors of LFADS for making this data accessible and answering our questions about the data!\n",
    "\n",
    "### Note: the notebook relies on plotly, which may not work on all browsers. If you encounter issues on one browser (e.g., Chrome), just change to another (e.g., Firefox)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f439545",
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "    \n",
    "!pip install plotly\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "import matplotlib.pylab as pl\n",
    "import matplotlib.pyplot as plt\n",
    "import plotly\n",
    "import plotly.graph_objs as go\n",
    "from sklearn.decomposition import PCA\n",
    "\n",
    "import pickle\n",
    "\n",
    "from sklearn.metrics import pairwise_distances\n",
    "import torch.nn as nn\n",
    "import torch\n",
    "\n",
    "from MARBLE import geometry "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78f3d637",
   "metadata": {},
   "source": [
    "## Load data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed5d3773",
   "metadata": {},
   "outputs": [],
   "source": [
    "# insert the pickle file of results that you want to visualise\n",
    "!mkdir data\n",
    "!wget -nc https://dataverse.harvard.edu/api/access/datafile/7062022 -O data/marble_embeddings_out3_pca10_100ms.pkl\n",
    "\n",
    "with open('./data/marble_embeddings_out3_pca10_100ms.pkl', 'rb') as handle:\n",
    "    data = pickle.load(handle)\n",
    "    \n",
    "distance_matrices = data[0]\n",
    "embeddings = data[1]\n",
    "timepoints = data[2]\n",
    "labels = data[3]\n",
    "sample_inds = data[4]\n",
    "trial_ids = data[5]\n",
    "\n",
    "# condition labels\n",
    "conditions=['DownLeft','Left','UpLeft','Up','UpRight','Right','DownRight']\n",
    "\n",
    "# load kinematics\n",
    "!wget -nc https://dataverse.harvard.edu/api/access/datafile/6969885 -O data/kinematics.pkl\n",
    "\n",
    "with open('data/kinematics.pkl', 'rb') as handle:\n",
    "    kinematic_data =  pickle.load(handle)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e1ed943",
   "metadata": {},
   "source": [
    "# Generate 3D plots for a selection of sessions\n",
    "\n",
    "Lets first do this for the MARBLE data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8ce5b649",
   "metadata": {},
   "outputs": [],
   "source": [
    "colors = pl.cm.viridis(np.linspace(0,1,7))\n",
    "\n",
    "# Configure Plotly to be rendered inline in the notebook.\n",
    "plotly.offline.init_notebook_mode()\n",
    "\n",
    "# looping over 10 different sessions\n",
    "examples = [5,6,8,11,14,15,18,23,26,32] # these sessions were used in Figure S7\n",
    "for d, i in enumerate(examples):\n",
    "    emb = embeddings[d]\n",
    "    label = labels[d]\n",
    "    time = np.hstack(timepoints[d])\n",
    "    # Configure the trace.\n",
    "    data = []\n",
    "\n",
    "    for i in range(7):\n",
    "        trace = go.Scatter3d(\n",
    "            x=emb[label==i,0],  \n",
    "            y=emb[label==i,1],  \n",
    "            z=emb[label==i,2],  \n",
    "            mode='markers',\n",
    "            marker={\n",
    "                'size': 1,\n",
    "                'opacity': 1,\n",
    "                'color':'rgb({},{},{})'.format(colors[i,0],colors[i,1],colors[i,2]),  # set color to an array/list of desired values\n",
    "            },\n",
    "        )\n",
    "        data.append(trace)\n",
    "\n",
    "    # Configure the layout.\n",
    "    layout = go.Layout(\n",
    "        paper_bgcolor='rgba(0,0,0,0)',\n",
    "        plot_bgcolor='rgba(0,0,0,0)',\n",
    "        xaxis=dict(showgrid=False,showline=False),\n",
    "        yaxis=dict(showgrid=False,showline=False)\n",
    "    )\n",
    "\n",
    "    plot_figure = go.Figure(data=data, layout=layout)\n",
    "    plot_figure.update_scenes(xaxis_visible=False, yaxis_visible=False,zaxis_visible=False )\n",
    "\n",
    "    # Render the plot.\n",
    "    plot_figure.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aded605d",
   "metadata": {},
   "source": [
    "Lets now compare this with the LFADS embeddings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "633c32e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "colors = pl.cm.viridis(np.linspace(0,1,7))\n",
    "\n",
    "# Configure Plotly to be rendered inline in the notebook.\n",
    "plotly.offline.init_notebook_mode()\n",
    "\n",
    "for i in range(len(examples)):\n",
    "    d = examples[i]\n",
    "    \n",
    "    \n",
    "    lfads_data = [[] for cond in conditions]\n",
    "    all_data = []\n",
    "    for c,cond in enumerate(conditions):   \n",
    "        for t in kinematic_data[d].keys():\n",
    "            if kinematic_data[d][t]['condition']==cond:\n",
    "                meh = kinematic_data[d][t]['lfads_factors']\n",
    "                lfads_data[c].append(meh)\n",
    "                all_data.append(meh)\n",
    "\n",
    "    lfads_data = [np.hstack(u) for u in lfads_data]\n",
    "    all_data = np.hstack(all_data)            \n",
    "\n",
    "    # need to PCA high dimension lfads data\n",
    "    pca = PCA(n_components=3)\n",
    "    pca.fit(all_data.T)  \n",
    "    \n",
    "    \n",
    "    # Configure the trace.\n",
    "    data = []\n",
    "\n",
    "    for i in range(7):\n",
    "        emb = pca.transform(lfads_data[i].T)\n",
    "        trace = go.Scatter3d(\n",
    "            x=emb[:,0],  \n",
    "            y=emb[:,1],  \n",
    "            z=emb[:,2],  \n",
    "            mode='markers',\n",
    "            marker={\n",
    "                'size': 1,\n",
    "                'opacity': 1,\n",
    "                'color':'rgb({},{},{})'.format(colors[i,0],colors[i,1],colors[i,2]),  # set color to an array/list of desired values\n",
    "            },\n",
    "        )\n",
    "        data.append(trace)\n",
    "\n",
    "    # Configure the layout.\n",
    "    layout = go.Layout(\n",
    "        paper_bgcolor='rgba(0,0,0,0)',\n",
    "        plot_bgcolor='rgba(0,0,0,0)',\n",
    "        xaxis=dict(showgrid=False,showline=False),\n",
    "        yaxis=dict(showgrid=False,showline=False)\n",
    "    )\n",
    "\n",
    "    plot_figure = go.Figure(data=data, layout=layout)\n",
    "    plot_figure.update_scenes(xaxis_visible=False, yaxis_visible=False,zaxis_visible=False )\n",
    "    \n",
    "    # Render the plot.\n",
    "    plot_figure.show()\n",
    "    #plotly.offline.iplot(plot_figure)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a6bd5db",
   "metadata": {},
   "source": [
    "# Average distance matrix across sessions "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92385113",
   "metadata": {},
   "source": [
    "Lets see what the average distance matrix looks like across sessions for MARBLE."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7901f815",
   "metadata": {},
   "outputs": [],
   "source": [
    "# plot average distance matrix based on clustering\n",
    "plt.figure()\n",
    "plt.imshow(np.mean(np.dstack(distance_matrices),2)); plt.colorbar()  \n",
    "\n",
    "emb_MDS, _ = geometry.embed(np.mean(np.dstack(distance_matrices),2), embed_typ = 'MDS')\n",
    "plt.figure()\n",
    "plt.scatter(emb_MDS[:,0],emb_MDS[:,1],c=np.linspace(0,6,7))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24ee2248",
   "metadata": {},
   "source": [
    "how does this compare with LFADS?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "506ec87d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# we first need to compute distance matrices for lfads \n",
    "\n",
    "distance_matrices_lfads = []\n",
    "\n",
    "# loop over sessions and compute distance matrices\n",
    "for d in range(len(embeddings)):\n",
    "    \n",
    "    lfads_data = [[] for cond in conditions]\n",
    "    for t in kinematic_data[d].keys():\n",
    "        for c,cond in enumerate(conditions):   \n",
    "            if kinematic_data[d][t]['condition'] == cond:\n",
    "                meh = kinematic_data[d][t]['lfads_factors']\n",
    "                lfads_data[c].append(meh)\n",
    "    \n",
    "    lfads_data = [np.hstack(u).T for u in lfads_data]\n",
    "    \n",
    "    distances = np.zeros([len(conditions), len(conditions)])\n",
    "    for i in range(len(conditions)):\n",
    "        for j in range(len(conditions)):\n",
    "            if i == j:\n",
    "                distances[i,j] = 0\n",
    "            else:\n",
    "                distances[i,j] = pairwise_distances(lfads_data[i], lfads_data[j]).mean()\n",
    "                \n",
    "    distances = distances/np.std(distances)\n",
    "    distance_matrices_lfads.append(distances)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d8afa280",
   "metadata": {},
   "outputs": [],
   "source": [
    "# plot average distance matrix based on clustering\n",
    "plt.figure()\n",
    "plt.imshow(np.mean(np.dstack(distance_matrices_lfads),2))\n",
    "plt.colorbar()  \n",
    "\n",
    "emb_MDS, _ = geometry.embed(np.mean(np.dstack(distance_matrices_lfads),2), embed_typ='MDS')\n",
    "plt.figure()\n",
    "plt.scatter(emb_MDS[:,0], emb_MDS[:,1], c=np.linspace(0,6,7))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fc8ab5d4",
   "metadata": {},
   "source": [
    "Both are pretty good in terms of their average embeddings!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4bd33cf",
   "metadata": {},
   "source": [
    "# Plotting individual session embeddings\n",
    "\n",
    "Here we just want to plot the distance matrix for individual sessions (Fig S7)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad42d324",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "fig, axs = plt.subplots(4,len(examples),figsize=(15,5))\n",
    "\n",
    "# loop over example sessions\n",
    "for i,idx in enumerate(examples):\n",
    "    \n",
    "    # plot distance matrix for marble\n",
    "    axs[0, i].imshow(distance_matrices[idx])\n",
    "    \n",
    "    # plot distance matrix for LFADS\n",
    "    axs[1, i].imshow(distance_matrices_lfads[idx])    \n",
    "\n",
    "    # plot MDS embedding of MARBLE distance matrix\n",
    "    emb_MDS, _ = geometry.embed(distance_matrices[idx], embed_typ = 'MDS')\n",
    "    axs[2, i].scatter(emb_MDS[:,0],emb_MDS[:,1],c=np.linspace(0,6,7))\n",
    "    \n",
    "    # plot MDS embedding of LFADS distance matrix\n",
    "    emb_MDS, _ = geometry.embed(distance_matrices_lfads[idx], embed_typ = 'MDS')\n",
    "    axs[3, i].scatter(emb_MDS[:,0],emb_MDS[:,1],c=np.linspace(0,6,7))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1bf65406-eeef-4c64-9786-1b54993caf45",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}