{ "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 }