{
"cells": [
{
"cell_type": "markdown",
"id": "55b6d6cf-92e9-495e-914e-c88389983b45",
"metadata": {},
"source": [
"# Connecting the Dots with Optimal Transport - Particle Colocalization\n",
"\n",
"In [a previous notebook](), we have looked at a method of finding out whether two types of molecules are attracted to each other. This problem is common in chemistry or molecular biology, where these connections are studied. We quantify what it means for molecule clouds to be close together, and infer an attraction for images of particularly 'close clouds'.\n",
"\n",
"We found that for really sharp images, a pixel based approach is not satisfactory. But today's microscopes are [getting to very high resolutions](https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.128.223901) at even small scales - let's look at a method that utilizes this and treats molecules as points. The method we look at lets us study the attraction between any number of molecule types, not just two."
]
},
{
"cell_type": "markdown",
"id": "5ba1364a-01cb-4750-85e1-960e2d0dd362",
"metadata": {},
"source": [
"## Subgraph Recovery\n",
"\n",
"### Generating Data\n",
"First, we need some data to work on, we'll generate it ourselves. We assume that some molecules are connected by a chemical bond. Therefore, they will be close together on an image taken of them. This might mean that their relative position is normally distributed with a small variance - or a small spread. A large spread, conversely, implies a weak bond.\n",
"\n",
"What we now do is traverse a tree structure of chemical bonds that we want to simulate existing. So if molecule $A$, $B$ and $C$ are all attracted to each other, we might find $A$ attached to $B$ and $B$ attached to $C$. Each branch of the tree is a draw out of a two-dimensional normal distribution, which models the random relative observed positioning of the two particles at the edges.\n",
"\n",
"Even if attraction between molecule types exists, however, we might not capture every particle cleanly. In practice, a fluorescent marker substance is attached to the molecules of interest, which might be a point of failure in multiple different ways. In any case, we have to deal with seeing only part of the tree of connected molecules. What we want to simulate is some particles being in a whole connection cluster, like $\\{A, B, C\\}$, some in a subset of the possible connections, like $\\{A, C\\}$, and some being all alone - $\\{A\\}$. This is why we specify a number of pairing clusters to be generated. \n",
"\n",
"The generated points can also be thought of as having a mass, which in this implementation is uniformly equal to $1$ for every one. As you might know, optimal transport is built on measure theory, so formally the transport plans push measures onto other measures. Here, the particle clouds are (probability) measures on $\\mathbb R^2$ describing how much its points inside a certain section $A \\subset \\mathbb R ^2$ weigh. Because of this, the weights should sum to 1.\n",
"\n",
"Let's look at this is action:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a1caa54d",
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"try:\n",
" if \"pyodide\" in sys.modules:\n",
" import piplite\n",
" await piplite.install('ipywidgets == 7.7')\n",
"except:\n",
" print(\"piplite not found, ignore this if you are not using Jupyterlite\")"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "330a5c3a-6cdb-4a97-b2e5-3f9d869db75f",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "0091be05fb9d49299bdb0e84a234ccd6",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(FloatSlider(value=0.1, continuous_update=False, description='Spread', max=0.25, min=0.05, step=…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "64a4ae672b1e4e8f961349eba6f9d90d",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import scipy\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib as mpl\n",
"import assets.ot as ot\n",
"from ipywidgets import interactive, FloatSlider, IntSlider, BoundedIntText, FloatLogSlider, Checkbox, widgets\n",
"from IPython.display import display\n",
"\n",
"# These are the possible bonds\n",
"edges = [(0,1), (1,2), (1,3)]\n",
"\n",
"spread = 0.01\n",
"\n",
"# The number of generated pairing clusters. We want to know exactly which molecules connect in which combination.\n",
"species = {(0,1,2,3) : 30, (0,1,2) : 20, (0,2,3) : 20, (2,3) : 10, (0,) : 10, (1,) : 20, (3,) : 10}\n",
"\n",
"def plot_clouds(ax, clouds, mu, scale=2):\n",
" colors = ['midnightblue', 'mediumvioletred', 'lightpink', 'dodgerblue', 'teal', 'deeppink']\n",
" j = 0\n",
" \n",
" for i, c in enumerate(clouds):\n",
" ax.scatter(c[:,0], c[:,1], s=mu[i]*4*scale**2 , c=colors[j], marker='.', alpha=0.75)\n",
" j += 1 \n",
"\n",
"def plot_interactive(spread, show_connections, seed=1):\n",
" mu, dists, X, true_coupling, edg_lines = ot.make_sample2d_s(seed=seed, \n",
" edges=edges, \n",
" spread=[spread/10 for _ in edges],\n",
" species=species,\n",
" add_ghost_copies=True)\n",
" fig = plt.figure(figsize=(8,8), dpi=200)\n",
" ax = plt.gca()\n",
"\n",
" ax.set_xticks([])\n",
" ax.set_yticks([])\n",
" ax.set_axis_off()\n",
"\n",
" plot_clouds(ax, X, mu, scale=4)\n",
" \n",
" if show_connections:\n",
" lc = mpl.collections.LineCollection(edg_lines, linewidths=1, zorder=0, linestyles=(0,(1,1)), color=\"hotpink\")\n",
" ax.add_collection(lc)\n",
"\n",
" plt.tight_layout()\n",
" plt.show()\n",
"\n",
"\n",
"# Creating widgets for interactive visualization\n",
"spread_widget = FloatSlider(description='Spread', \n",
" min=0.05, max=0.25, \n",
" step=0.01, value=0.1,\n",
" continuous_update=False)\n",
"\n",
"seed_widget = BoundedIntText(description='Seed', \n",
" value=1,min=0)\n",
"connection_widget = Checkbox(description=\"Show Tree Structure\",\n",
" value = True)\n",
"\n",
"ui = widgets.VBox([spread_widget, connection_widget, seed_widget])\n",
"widget = interactive(plot_interactive, spread=0.1, show_connections=True)\n",
"out = widgets.interactive_output(plot_interactive, {'spread': spread_widget, 'show_connections': connection_widget, 'seed': seed_widget})\n",
"\n",
"display(ui, out)"
]
},
{
"cell_type": "markdown",
"id": "cefd4af8-c3d5-4da8-91e9-8b0d48c9e6fd",
"metadata": {},
"source": [
"## Getting back what's lost\n",
"\n",
"Now, we use an algorithm utilizing optimal transport to guess the dotted trees in the picture above. What's important here is not that the exact trees as above are found, but only that the result reflects how close the generated particles originally were to each other, their colocalization. For a spread small enough however, it will turn out that we often find exactly which particles came from the same tree. In an application on measurements however, is no such original. The algorithm can, in any case, only see the dots and tries to optimally construct weighted graphs that match this input. A high weight on a connection means that the algorithm is sure that there is a connection.\n",
"\n",
"For any set of graphs (or the stochastic couplings on them, to be exact) connecting the points, the solver can judge how good of a solution it is by applying a cost function. This is necessary in order for optimal transport to work, in fact the very word *optimal* stands for 'minimizing a cost function'. For this, the solver takes the following aspects into account:\n",
"\n",
"- Dots connected by a branch should not be farther apart than a fixed distance $d_{\\text{max}}$. This would be an upper bound for a reasonable molecular interaction distance in practice. The default value is the $0.99$-quantile of a $\\chi$-distribution for 2 dimensions, according to which the euclidean norm of normally distributed 2D points are distributed. This describes the length of our brances, so on average, this will cover $99\\%$ of the generated connections. The slider below simply multiplies a constant to this default.\n",
"- As few points as possible should remain without a graph. That is, there is a parameter $\\lambda$ for unmatched points. The higher, the more enthusiastically points are associated with each other.\n",
"- As little mass as possible should be imaginarily added to the input. We will discuss what this means below.\n",
"\n",
"Further, in order to help the algorithm converge at all, a method called entropic regularization is used. For practical purposes this means that we introduce an indecisiveness parameter $\\epsilon$; if $\\epsilon$ is high, a point of type $A$ being about equally close to two points of type $B$ will be matched to both of them equally. If $\\epsilon$ is low however, it is decided that whichever $B$ is closer, by however narrow a margin, gets connected to $A$ and the other point $B$ will have to look for another cluster to be part of. Note that this also influences the speed of convergence.\n",
"\n",
"Below, you can see code that executes all this. The red connection lines on the left are the generated connections, the ones on the right are where the algorithm guessed there was a connection.\n",
"\n",
"(The following code takes a while to run, so patience is needed to try different parameters.)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "1b674959-48ff-4252-8f2d-28de8db39fce",
"metadata": {},
"outputs": [],
"source": [
"# A seed for reproducing the same graph with different parameters. \n",
"# You can rerun this cell to see different configurations.\n",
"\n",
"seed = np.random.randint(2**31)"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "175fe6a6-3d06-4c94-bc69-3b9efeb8e519",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "82517d7c075f4fb392152e68c8f91a24",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(FloatSlider(value=1.0, continuous_update=False, description='$d_{max}$', max=3.0, min=0.5, step…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "37703fabb55e47e88f7d324a4f70a32a",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"from scipy.stats import chi\n",
"\n",
"# Here, we fix the properties of the generated graphs\n",
"edges = [(0,1), (1,2), (1,3)]\n",
"\n",
"spread = 0.01\n",
"# Feel free to change the values in this dictionary or add your own keys to change the generated configurations!\n",
"species = {(0,1,2,3) : 20, (0,1,2) : 15, (0,2,3) : 10, (2,3) : 5, (0,) : 5, (1,) : 5, (3,) : 5}\n",
"\n",
"mu, dists, X, true_coupling, edg_lines = ot.make_sample2d_s(seed=seed, \n",
" edges=edges, \n",
" spread=[spread for _ in edges],\n",
" species=species,\n",
" add_ghost_copies=True)\n",
"\n",
"def plot_primal(ax, clouds, mu, edges, plans, scale=2, threshold=1e-3):\n",
" plot_clouds(ax, clouds, mu, scale)\n",
"\n",
" for k in range(len(edges)):\n",
" X1 = clouds[edges[k][0]]\n",
" X2 = clouds[edges[k][1]]\n",
" n1 = plans[k].shape[0]\n",
" n2 = plans[k].shape[1]\n",
"\n",
" # Drawing trees which have been found by the algorithm\n",
" l = mpl.collections.LineCollection(\n",
" [(X1[i], X2[j]) for i in range(n1) for j in range(n2) if plans[k][i,j] > threshold],\n",
" linewidths=[scale * plans[k][i,j] for i in range(n1) for j in range(n2) if plans[k][i,j] > threshold],\n",
" zorder=-1, color=\"red\", linestyles=\"-\", capstyle=\"round\")\n",
"\n",
" ax.add_collection(l)\n",
"\n",
"def plot_interactive(d, epsi):\n",
" # These are parameters for the Optimal Transport solver, adjusted by slider values\n",
" d_max = spread * chi.ppf(0.99, 2) * d\n",
" lamp = d_max * 10\n",
" lam = lamp * 10\n",
" costs = [d + lam * (d > d_max) for d in dists]\n",
" sigmas = [np.ones_like(c) for c in costs]\n",
" \n",
" # This runs the solver\n",
" p = ot.partial_multi_L1(mu, edges, costs, sigmas, epsi, lam, lamp, False)\n",
" res = p.run_epsi_scale(min_step_size=1e-4)\n",
" \n",
" # plotting\n",
" fontsize = 16\n",
" fig, axs = plt.subplots(1, 2, figsize=(16,8), dpi=200)\n",
"\n",
" margin = max(0 - min(0, np.min(X)), max(1, np.max(X)) - 1) + .05\n",
" \n",
" axs[0].set_title(\"Generated Coupling\", fontsize=fontsize)\n",
" axs[0].set_aspect(1)\n",
" axs[0].set_xlim(-margin, 1 + margin)\n",
" axs[0].set_ylim(-margin, 1 + margin)\n",
" plot_primal(axs[0], X, mu, edges, true_coupling, scale=3.5)\n",
"\n",
" lc = mpl.collections.LineCollection(edg_lines, linewidths=1, zorder=0, linestyles=(0,(1,1)), color=\"red\")\n",
" axs[0].add_collection(lc)\n",
" axs[0].set_xticks([])\n",
" axs[0].set_yticks([])\n",
"\n",
" axs[1].set_title(\"Calculated Coupling\", fontsize=fontsize)\n",
" axs[1].set_aspect(1)\n",
" axs[1].set_xlim(-margin, 1 + margin)\n",
" axs[1].set_ylim(-margin, 1 + margin)\n",
" plot_primal(axs[1], X, mu, edges, p.get_primal(), scale=3.5)\n",
" axs[1].set_xticks([])\n",
" axs[1].set_yticks([])\n",
"\n",
" # fig.canvas.draw()\n",
" plt.show()\n",
" \n",
"# Creating widgets for interactive visualization\n",
"maximal_distance_widget = FloatSlider(description='$d_{max}$', \n",
" min=0.5, max=3, \n",
" step=0.01, value=1,\n",
" continuous_update=False)\n",
"epsilon_widget = FloatLogSlider(description='$\\epsilon$', \n",
" min=-8, max=-1,\n",
" step=0.01, value=5e-5,\n",
" continuous_update=False)\n",
"ui = widgets.VBox([maximal_distance_widget, epsilon_widget])\n",
"widget = interactive(plot_interactive, d=1, epsi=1e-5)\n",
"out = widgets.interactive_output(plot_interactive, {'d': maximal_distance_widget, 'epsi': epsilon_widget})\n",
"\n",
"display(ui, out)"
]
},
{
"cell_type": "markdown",
"id": "36b53bb3-2fff-443b-859d-ab0ad52260af",
"metadata": {},
"source": [
"## Evaluation\n",
"\n",
"Next, we can quantitatively assess the colocalization and see how it compares to the original trees. The above recovered graphs may already give a visual notion of how close the points are to each other, but in the end we simply want a statistic of how likely it is that the molecules are attracted to each other - not yet another picture. Here, since we know how many point clusters $\\{A\\}, \\{A,B,C,D\\}, ...$ were generated, we can graph that next to the number of guessed clusters to gauge the algorithm's accuracy. Note that when the spread is too large, we can't fault the solver for matching points which weren't generated together, so this is a more approximate way to gauge its performance."
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "3efdef10-864f-4ea1-8dd8-246ca77e9abe",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "82517d7c075f4fb392152e68c8f91a24",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"VBox(children=(FloatSlider(value=1.0, continuous_update=False, description='$d_{max}$', max=3.0, min=0.5, step…"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "33c1d58643824e32b009e6959b4d2d7f",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Output()"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Here, we fix the properties of the generated graphs\n",
"edges = [(0,1), (1,2), (1,3)]\n",
"spread = 0.01\n",
"# Feel free to change the values in this dictionary or add your own keys to change the generated configurations!\n",
"species = {(0,1,2,3) : 15, (0,1,2) : 5, (0,2,3) : 20, (1,2,3) : 10, (2,3) : 10, (0,) : 5, (1,) : 5, (3,) : 5}\n",
"\n",
"mu, dists, X, true_coupling, edg_lines = ot.make_sample2d_s(seed=seed, \n",
" edges=edges, \n",
" spread=[spread for _ in edges],\n",
" species=species,\n",
" add_ghost_copies=True)\n",
"\n",
"def plot_interactive(d, epsi):\n",
" # These are parameters for the Optimal Transport solver, adjusted by slider values\n",
" d_max = spread * chi.ppf(0.99, 2) * d\n",
" lamp = d_max * 10\n",
" lam = lamp * 10\n",
" costs = [d + lam * (d > d_max) for d in dists]\n",
" sigmas = [np.ones_like(c) for c in costs]\n",
" \n",
" # This runs the solver\n",
" p = ot.partial_multi_L1(mu, edges, costs, sigmas, epsi, lam, lamp, False)\n",
" res = p.run_epsi_scale(min_step_size=1e-4)\n",
" pi = p.get_primal()\n",
" \n",
" # Counting match numbers\n",
" match_cnts, match_str, deltas = p.get_match_counts()\n",
"\n",
" fig = plt.figure(figsize=(16,8), dpi=200)\n",
"\n",
" fontsize=16\n",
" plt.title(\"Recovery of (partial) Tuple Counts\", fontsize=fontsize)\n",
"\n",
" plt.bar(np.arange(len(deltas)) - 0.2, match_cnts.ravel(), width=0.4, color=\"purple\")\n",
" \n",
" n = len(edges) + 1\n",
" def ctos(c):\n",
" a = np.zeros(n, dtype=int)\n",
" a[list(c)] = 1\n",
" return \"\".join([(chr(ord('A') + j) if a[j] == 1 else \"_\") for j in range(n)])\n",
"\n",
" true_x = list(map(match_str.index, list(map(ctos, species.keys()))))\n",
" true_y = list(species.values())\n",
" true_vals = np.zeros(len(deltas), dtype=int)\n",
" true_vals[true_x] = true_y\n",
" plt.bar(np.array(true_x) + 0.2, true_y, width=0.4, color=\"deeppink\")\n",
"\n",
" plt.tight_layout()\n",
" plt.xticks(range(len(deltas)), match_str, fontsize=fontsize, rotation=45)\n",
" plt.yticks(fontsize=fontsize)\n",
"\n",
" for x in range(len(deltas)):\n",
" mc = match_cnts.ravel()[x]\n",
" if mc > 0.01:\n",
" plt.text(x - 0.2, mc + 0.5, str(round(mc, 2)), ha=\"center\")\n",
" if true_vals[x] > 0:\n",
" plt.text(x + 0.2, true_vals[x] + 0.5, str(true_vals[x]), ha=\"center\")\n",
"\n",
" plt.legend([\"Number of calculated Clusters\", \"Number of generated Clusters\"], fontsize=fontsize)\n",
" # fig.canvas.draw()\n",
" plt.show()\n",
"\n",
"widget = interactive(plot_interactive, d=1, epsi=5e-5)\n",
"out = widgets.interactive_output(plot_interactive, {'d': maximal_distance_widget, 'epsi': epsilon_widget})\n",
"\n",
"display(ui, out)"
]
},
{
"cell_type": "markdown",
"id": "dd4184ac-a588-4a4f-a358-8eb180892c2d",
"metadata": {
"tags": []
},
"source": [
"So for the default parameters and most seeds, it seems like it's doing quite well. If we were to run the program on experimental data and get this result, we would conclude that there is a strong interaction between molecules $C$ and $D$, or that the interaction $\\{A, C, D\\}$ is particularly likely.\n",
"\n",
"### Phantom Points\n",
"\n",
"In an implementation of a tree based optimal transport approach to this problem, there is one key difficulty we have not touched on yet. The solver needs as a formal constraint that all the vertices from the original tree structure are present. However, as we looked at, we can also include subsets of this. So how was this done?\n",
"\n",
"Now is a good time to introduce Thilo Stier, who wrote a Bachelor's thesis on the topic and the code at the heart of this notebook. (On a side note, don't hesitate to write an email to `thilodaniel.stier AT stud DOT uni-goettingen.de` if you have questions about this implementation.) His solution was to add phantom particles to the generated point clouds:\n",
"\n",
"A phantom particle is a point with zero mass, not part of the point cloud that originally needs to be connected. If there is a point $A$ and we want to find trees with particles $\\{A, B, C\\}$, let's say, hovering right above $A$ are phantom points $B$ and $C$. If there aren't any real $B$s or $C$s anywhere near, the algorithm may choose a phantom point as a substitute. But because finding a whole graph is better than just a part of it, doing this has a cost\n",
"\n",
"## Conclusion\n",
"\n",
"The field of optimal transport and its numerics is full of methods like the ones we looked at here - being discovered just now. Try a search for 'multi particle colocalization' - what you are looking at in this notebook is already the cutting edge, more or less!\n",
"\n",
"If you want to be part of this research, too, the place this notebook comes from might be just what you're looking for. You can find the University of Göttingen's optimal transport group [here](https://ot.cs.uni-goettingen.de/) and the Collaborative Research Center here. A notebook just like this one about researching Alzheimer's disease with optimal transport is avaiable [here](Optimal_Transport_and_X-ray_Tomography.ipynb). Thank you for reading!\n",
"\n",
"****\n",
"\n",
"_Written by Thilo Stier and Lennart Finke. Published under the [MIT](https://mit-license.org/) license._"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.8.10 64-bit",
"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.8.10"
},
"vscode": {
"interpreter": {
"hash": "916dbcbb3f70747c44a77c7bcd40155683ae19c65e1c03b4aa3499c5328201f1"
}
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 5
}