<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ford Combs on Medium]]></title>
        <description><![CDATA[Stories by Ford Combs on Medium]]></description>
        <link>https://medium.com/@fordcombs?source=rss-bb50b09eee87------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*qFZbF8CZVK5_lk2SDyoqaA.jpeg</url>
            <title>Stories by Ford Combs on Medium</title>
            <link>https://medium.com/@fordcombs?source=rss-bb50b09eee87------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 01:14:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fordcombs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Animating viral spread in Python]]></title>
            <link>https://medium.com/data-science/animating-viral-spread-in-python-b4a5b5dfbf6e?source=rss-bb50b09eee87------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4a5b5dfbf6e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coronavirus]]></category>
            <dc:creator><![CDATA[Ford Combs]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 16:16:07 GMT</pubDate>
            <atom:updated>2022-02-16T16:16:07.695Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using matplotlib’s FuncAnimation to easily make informative data visualization GIFs — part 1 of 2</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*HU0ybseWcuYdHeD0XFGkmg.gif" /><figcaption>Image by author.</figcaption></figure><h3>Motivation</h3><p>In this work, I want to show how easy it is to make animations using matplotlib. In the past, I’ve searched for tutorials and information on this topic and I always came up short. When I did find examples, I had a difficult time interpreting them and nothing seemed to stick. So, I decided to make a set of tutorial in the hopes that others can learn how to make matplotlib GIFs quickly and effectively. To that end, I chose SARS-CoV-2 as my case study topic since there is so much coronavirus data available these days.</p><h3>Background</h3><p>Over the last two years the term <em>R-naught — </em>aka<em> R₀ </em>or <em>reproductive number— </em>appears all over the media whenever a new strain comes into existence. I bet we all have an idea of what it means at this point, but the <a href="https://academic.oup.com/jtm/article/28/7/taab124/6346388">definition</a> is the average number of people an infected person infects in the absence of vaccines, masks, or other protective measures. It’s a difficult number to measure and many values have been proposed. Early on, in the spring of 2020, people made many <a href="https://www.weforum.org/agenda/2020/05/covid-19-what-is-the-r-number/">estimates</a> about the R₀ of the ancestral strain that ranged from 2 to 6+; now we think it is around <a href="https://academic.oup.com/jtm/article/28/7/taab124/6346388">2.5</a> [1]. The Delta variant seems to have an R₀ of about <a href="https://academic.oup.com/jtm/article/28/7/taab124/6346388">5</a> and while we are still in the early days of Omicron, it is estimated to have an R₀ of about <a href="https://www.thelancet.com/journals/lanres/article/PIIS2213-2600(21)00559-2/fulltext">10</a> [2].</p><p>There is clearly a large difference in infectivity, but how can we visualize it? In <a href="https://towardsdatascience.com/chord-diagrams-of-protein-interaction-networks-in-python-9589affc8b91">previous posts</a>, I’ve described how humans are excellent pattern finders when it comes to visual data. It’s far easier for us to interpret images than strings of numbers. With that in mind, I will explain how visualize these differences in R₀ using <a href="https://matplotlib.org/stable/index.html">matplotlib</a>. Here, I will show you how to use <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html">FuncAnimation()</a> to generate GIFs of viral spread. First, we will look at how to create an animated line graph and how to set up a basic, point-based simulation for viral spread. In the next article, we will see how we can improve this basic setup and create more complex animations.</p><p>Here are the imports you’ll need:</p><pre>from matplotlib import pyplot as plt<br>from matplotlib.animation import FuncAnimation<br>from matplotlib.collections import PatchCollection<br>from matplotlib.patches import Rectangle<br>import random<br>import numpy as np<br>from scipy.spatial import Delaunay<br>from matplotlib.lines import Line2D</pre><h3>Line graph visualization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6AftHzQWIWrZZOqN30cJBw.png" /><figcaption>Figure 1. Early line graph from 1712 by Francis Hauksbee [3]</figcaption></figure><p>It is interesting to look at the history of data visualization and Figure 1 shows a couple of very early line graphs, indicated above as <em>Fig. 6</em> and <em>Fig. 7</em>. These graphs depict the capillary action of water between two panes of glass. That’s a little vague, so here are two other examples of this experiment: <a href="http://physicsexperiments.eu/2080/capillary-action-between-two-glass-plates">1</a> and <a href="https://aapt.scitation.org/doi/abs/10.1119/1.2343547?journalCode=pte">2</a>. Line graphs can be used to display a number of types of relationships, but here we can use them to display change in number of infections over time.</p><p>When creating visualizations of the growth in number of infections over time, we can use the following code to generate plausible line trajectories. First, we can create a function called calc_y() that takes in a number of steps (n) and an R₀ value (r). Instead of using the same R₀ at each step, we can use the np.random.normal() function to return a value from a normal distribution with a mean of R₀. This is better because the reproduction number is an <strong>average</strong>, so will be different for every infected individual.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2de97414cee6fd921fb7e0055e51ae78/href">https://medium.com/media/2de97414cee6fd921fb7e0055e51ae78/href</a></iframe><p>Next, we can create the animation. The following code uses FuncAnimation() which allows us to pass in a custom function to generate animations. The code below is fairly simple. All thatanimation_func() does is iterate from 0 up to 45, the frames argument from FuncAnimation() , and draw lines based on the code described above. Since different values R₀ lead to dramatically different number of infections over time, I wrote the function to draw the lines in three stages, one for each R₀, as the value of i increases. The first 15 lines will correspond to an R₀ of 1, the next 15 to an R₀ of 2, and the final 15 to an R₀ of 10.</p><blockquote>Note that I’m using imagemagick to write the figure to a GIF. If you are working in google colab, you can run !apt-get install imagemagick to install it in your runtime, otherwise you will need to make sure you have it installed in your system.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d32f2658dc27d3f73db6892bf0469a6/href">https://medium.com/media/8d32f2658dc27d3f73db6892bf0469a6/href</a></iframe><p>The above code was used to generate the GIF below. We can see there are fifteen lines drawn for each R₀ of 1, 2, and 10. It is amazing but unsurprising to see how rapidly the lines of the larger R₀’s grow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*Z_r_CZW9B1h88EJaAsYdQQ.gif" /><figcaption>Line graph animation. Image by Author.</figcaption></figure><p>Uncommenting line 10 transforms the y-axis to a log scale, which further illustrates the dramatic increase in number of infections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*MsNXQoSRsalkwo4nVuUM9A.gif" /><figcaption>Line graph animation with log scale y axis. Image by Author.</figcaption></figure><h3>Simulation Visualization</h3><p>These line graphs illustrate the rapid increase in infections over time by a virus with an R₀ of 10. But, does that information really stick? Notice that the y-scale of the previous plot is set to a log scale and that the purple lines reaches values of ~10 million. Intuitively that makes sense. Since R₀ =10 means that each person infects on average 10 people, we would expect to growth in multiples of 10. But what would that <em>look </em>like in large room of people milling about? Say, at a superspreading event like the <a href="https://www.science.org/doi/10.1126/science.abe3261">Biogen conference</a>.</p><p>Back in March 2020, an <a href="https://www.washingtonpost.com/graphics/2020/world/corona-simulator/">article</a> in The Washington Post was released that showed several simulations akin to what I described above. They were designed to illustrate how activities like quarantining and social distancing can slow the spread. R₀ was not factored into the WP simulations at all; a point was infected simply by coming in contact with an infected point.<strong> </strong>I encourage you to check the article out because those simulations were the inspiration for this tutorial. While the visualizations do a good job of illustrating how to reduce spread, we have a different goal: we want to simulate different the spread of strains with different R₀’s. Now that we have estimates of this value for different strains, we can visualize what the real world impacts of infectiousness might be.</p><h4>First attempt</h4><p>The question is, how do we simulate viral spread under different values of R₀? My first plan was to initialize a plane with a bunch of points that each have a small velocity and a state, which is either healthy or infected. One of these points would be randomly chosen to be infected at time 0. To simulate spread, the number of points that this infected point would infect was randomly selected from a normal distribution with a mean of R₀, similar to the process described above. The stats of these points was then changed from healthy to infected. By selecting number of infections for an infected point from a normal distribution around R₀, we ensure that on average, R₀ points are infected by each infected point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*EiiPdVD6Kj7FK6dosJWygw.gif" /><figcaption>This basic simulation setup has 75 points, 1 of which is infected (red) and 74 of which are healthy (blue). Image by Author.</figcaption></figure><p>The method described above turned out to be the wrong approach. The main issue was that at each time increment ~R₀ points are infected and those points are selected as the closest points to an infected point. That doesn’t mean that they are actually close though. More importantly, determining R₀ <em>a priori </em>is not elegant. A better solution is to design the simulation environment to produce the desired R₀, and that’s what I did next. Nevertheless, the animation of the simulation was effective and the code use to produce the GIF is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/803959b504a603618301224b7321b673/href">https://medium.com/media/803959b504a603618301224b7321b673/href</a></iframe><h3>Next Steps</h3><p>In this article, I showed how to generate two different type of animations using matplotlib and FuncAnimation. In the next one, I will go take a deeper dive into improving the second simulation. Make sure to follow me so you don’t miss it! If you liked this work, please check out my other <a href="https://fordcombs.medium.com/">articles</a>, <a href="https://fordcombs.medium.com/subscribe">sign up</a> to receive notifications, and join <a href="https://fordcombs.medium.com/membership">Medium</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTgAx9ix6MYaBnK_OxVNnA.jpeg" /><figcaption>Image from <a href="https://pixabay.com/photos/coronavirus-virus-pandemic-china-4810201/">pixabay</a> with no attribution required</figcaption></figure><h4>References</h4><p>1. Ying Liu, Joacim Rocklöv, The reproductive number of the Delta variant of SARS-CoV-2 is far higher compared to the ancestral SARS-CoV-2 virus, <em>Journal of Travel Medicine</em>, Volume 28, Issue 7, October 2021, taab124, <a href="https://doi.org/10.1093/jtm/taab124">https://doi.org/10.1093/jtm/taab124</a></p><p>2. Talha Khan Burki, Omicron variant and booster COVID-19 vaccines,<br><em>The Lancet Respiratory Medicine</em>, Volume 10, Issue 2, 2022, Page e17,<br>ISSN 2213–2600, <a href="https://doi.org/10.1016/S2213-2600(21)00559-2.">https://doi.org/10.1016/S2213-2600(21)00559-2.</a><br>(<a href="https://www.sciencedirect.com/science/article/pii/S2213260021005592">https://www.sciencedirect.com/science/article/pii/S2213260021005592</a>)</p><p>3. Hauksbee, Francis. “An Account of an Experiment Touching the Ascent of Water between Two Glass Planes, in an Hyperbolick Figure. By Mr. Francis Hauksbee, F. R. S.” <em>Philosophical Transactions (1683–1775)</em>, vol. 27, The Royal Society, 1710, pp. 539–40, <a href="http://www.jstor.org/stable/103171.">http://www.jstor.org/stable/103171.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4a5b5dfbf6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/animating-viral-spread-in-python-b4a5b5dfbf6e">Animating viral spread in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chord diagrams of protein interaction networks in Python]]></title>
            <link>https://medium.com/data-science/chord-diagrams-of-protein-interaction-networks-in-python-9589affc8b91?source=rss-bb50b09eee87------2</link>
            <guid isPermaLink="false">https://medium.com/p/9589affc8b91</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[biology]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ford Combs]]></dc:creator>
            <pubDate>Thu, 17 Dec 2020 00:16:32 GMT</pubDate>
            <atom:updated>2020-12-23T22:35:47.466Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using nxviz to create alluring and informative circos plots</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_lIM4nXJnRNmMh6CHZSrUQ.png" /><figcaption>Protein interaction network visualized using nxviz. Image by author.</figcaption></figure><p>Humans are g<a href="https://news.mit.edu/1996/visualprocessing">reat at interpreting graphic displays </a>of data. We can identify patterns in visual displays quickly and easily as compared to tabular displays. There are <a href="https://www.seyens.com/humans-are-visual-creatures/">many reasons</a> for this, e.g., <a href="https://www.discovermagazine.com/mind/the-vision-thing-mainly-in-the-brain">about 30%</a> of the cortex contains neurons dedicated to visual processing. This is why data visualization is extremely important for both understanding and communicating information. In a previous <a href="https://towardsdatascience.com/visualizing-protein-networks-in-python-58a9b51be9d5">post</a>, I described how NetworkX can be used to build informative and attractive graphic displays of protein network data. Here, I will show how the same data can be displayed as a Circos-style, chord diagram using <a href="https://nxviz.readthedocs.io/en/latest/index.html">nxviz</a><em>.</em></p><h4>Chord Diagrams</h4><p>Chord diagrams are circular plots that are great for displaying relationships between objects of a set, such as nodes and connections in a network. A basic chord diagram has a ring of objects connected by chords that indicate relationships. In Python, you can create these types of plots with nxviz, a package designed for use with <a href="https://networkx.org/documentation/stable/index.html">NetworkX</a> graphs. If you want to learn more about NetworkX, check out my previous <a href="https://towardsdatascience.com/visualizing-protein-networks-in-python-58a9b51be9d5">story</a>. The original <a href="http://circos.ca/documentation/">Circos</a> software that helped popularize chord diagrams is written in Perl and was introduced in a <a href="https://genome.cshlp.org/content/early/2009/06/15/gr.092759.109.abstract">paper</a> published in 2009. The software is well-documented and there are great tutorials that show you how to build beautiful plots that display multiple layers of information. Currently, nxviz is one of the few Python libraries that can be used to create plots in this style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*TjW8S30yqhFYZo0MLX_WqA.png" /><figcaption>Figure 3 from McGraw, Lisa A et al. “A genetic linkage map and comparative mapping of the prairie vole (Microtus ochrogaster) genome.” <em>BMC genetics</em> vol. 12 60. 7 Jul. 2011, doi:10.1186/1471–2156–12–60</figcaption></figure><pre>### The required libraries and packages ###<br>import networkx as nx<br>import requests<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br># from matplotlib import cm<br>from nxviz.plots import CircosPlot</pre><h4>Gather the data</h4><p>The network we are going to visualize contains protein interaction data. The following code takes a list of proteins and uses the Python requests library to collect data from the <a href="https://string-db.org/cgi/network?pollingId=biiYX0Uq4ddU&amp;sessionId=buyoWxcZfiOh">STRING</a> database of protein interactions. You can learn more about this process <a href="https://towardsdatascience.com/visualizing-protein-networks-in-python-58a9b51be9d5">here</a>, but the end result is a data frame in which each row contains a pair of proteins and the interaction score between them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9136852b6b267bfcc7506f76de345061/href">https://medium.com/media/9136852b6b267bfcc7506f76de345061/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd6a4ac13048a6a587e8476c79678fb3/href">https://medium.com/media/fd6a4ac13048a6a587e8476c79678fb3/href</a></iframe><p>The next code chunk can be used to build the graph using NetworkX. The code below is the same as described <a href="https://towardsdatascience.com/visualizing-protein-networks-in-python-58a9b51be9d5">previously</a>, except for one optional modification: only high scoring interactions are used as weighted edges. This will reduce clutter in the simplified visualization. For the more advanced graph, you can keep all the edges by uncommenting the designated line below and commenting out the last two lines.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/824e8cc505afa9194c04c97b5c1774e5/href">https://medium.com/media/824e8cc505afa9194c04c97b5c1774e5/href</a></iframe><h4>Draw a simple plot</h4><p>Now that the NetworkX graph has been created, a Circos-style plot can be generated very quickly with just three lines of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/842d72fd4e452d9cf91b775ebf159726/href">https://medium.com/media/842d72fd4e452d9cf91b775ebf159726/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*c8JHQx8dw4EMcuzdKMBRKQ.png" /><figcaption>Image by author</figcaption></figure><p>The above plot shows displays important, basic information about the network. For example, it is easy to see which nodes have relatively higher or lower <em>degree</em>. Recall that the degree of a node is the number of edges that connect to it. For example, the node HTR1A<em> </em>has a high degree; it has more connections compared to other proteins in the graph. This suggests that HTR1A is involved in many different processes. MAOA, on the other hand, has a low degree; only one edge connects it to another node. This suggests that it has a more specific role.</p><h4>More informative plots</h4><p>The graph above is useful, but more information can be displayed in these types of plots. Nxviz allows for the nodes and edges to be colored and sized based on user-defined characteristics. The code below shows how a nodelist and edgelist can be generated from graph G and used to build a new graph g. This new graph is identical to old graph, except that it has a [&quot;class&quot;] attribute for each node that stores its degree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f75c76c8cad56bce91a6891afd1e5b8/href">https://medium.com/media/3f75c76c8cad56bce91a6891afd1e5b8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd5f382dd3aff3e8b5c473063dbece1a/href">https://medium.com/media/fd5f382dd3aff3e8b5c473063dbece1a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*kNOaULNLy8pnzm9h2aqRIw.png" /><figcaption>Plot of the protein interaction network that includes only high scoring edges. Image by author</figcaption></figure><p>The above plot includes both the edge weight and node degree information. Note that the nodes are colored based on their degree. The proteins with the most interactions are pink and purple while the lower degree proteins are red. Also, note that the widths of the edges indicate the score of the interaction; the wider the edge, the higher the score.</p><p>This display can be improved further by making two alterations to the code. First, all edges can be kept by uncommenting the designated line in the create_graph_circos gist. Normally, this would result in a lot of clutter, but the widths are adjusted with one more change: the uncommenting of the alternate method in the improved_circos.py gist. This rescales the edge widths more dramatically so that high scoring interactions are much wider than low scoring interactions. Because of this dramatic change in the edge widths, it is possible to display all the edges without the graph becoming crowded and difficult to interpret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*tOIhv9hwxXF6x9whv_hnbQ.png" /><figcaption>Plot of the protein interaction network that includes all edges. Image by author</figcaption></figure><h4>Final thoughts</h4><p>The plots included in this article are effective for the visualization of protein interaction networks. The final plot does a particularly good job of displaying lots of details about the network. The node color helps indicate groups of nodes that have similar degree and the edge widths show which interactions have higher scores. This is useful in the analysis of networks, because high scoring edges likely indicate more tightly linked interactions. And, high scoring interactions linked to nodes of high degree, can indicate particularly important interactions in the network.</p><p>The proteins used in this example are related, but they were arbitrarily chosen as a proof of concept. Novel research would require more care in the creation of the protein set and in the design of the edge weights through the utilization of other scores and data. Also, improvements in chord diagram implementations in Python need to be developed. There are currently excellent options for drawing these plots in <a href="https://www.r-graph-gallery.com/chord-diagram.html">R</a>. Stay tuned, as I hope to take a stab at a Python version soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9589affc8b91" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/chord-diagrams-of-protein-interaction-networks-in-python-9589affc8b91">Chord diagrams of protein interaction networks in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing protein networks in Python]]></title>
            <link>https://medium.com/data-science/visualizing-protein-networks-in-python-58a9b51be9d5?source=rss-bb50b09eee87------2</link>
            <guid isPermaLink="false">https://medium.com/p/58a9b51be9d5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ford Combs]]></dc:creator>
            <pubDate>Thu, 10 Dec 2020 18:47:31 GMT</pubDate>
            <atom:updated>2020-12-11T13:26:47.796Z</atom:updated>
            <content:encoded><![CDATA[<h3>Visualizing protein interaction networks in Python</h3><h4>From data to beautiful graphs with NetworkX</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SiPyDa0OCNKmxmHDHU4Yxw.png" /><figcaption>Minimum spanning tree for protein network containing TPH1 and SERT proteins. Image by Author</figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Protein%E2%80%93protein_interaction#:~:text=Protein%E2%80%93protein%20interactions%20(PPIs),bonding%20and%20the%20hydrophobic%20effect.">Protein interaction</a> data is incredibly important. It describes the interplay between the biomolecules encoded by genes. It allows us to understand the complexities of cellular function and even predict potential therapeutics. There are many databases that contain protein interaction data, but <a href="https://string-db.org/cgi/about?footer_active_subpage=references">STRING</a> is one of the best. It contains <a href="https://string-db.org/cgi/about?sessionId=bRJVMkM0z6Jg&amp;footer_active_subpage=statistics">3,123,056,667 total interactions</a> at the moment of this writing. These interactions involve over 20,000,000 proteins in over 5,000 organisms, combining to form. In this article, I’m going to show you how to download protein interaction data from the STRING API and how to create graphs and visualizations of that data using <a href="https://networkx.org/documentation/stable/citing.html">NetworkX</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yVGVR6PzgXkR4YE-60iCug.jpeg" /><figcaption><a href="https://www.flickr.com/photos/posk/4795063476/in/photolist-8iHXjd-2ZrZx-2hM7Q9V-uz9C8x-cbTs2U-7A6Z2b-2k5m7d7-Nk5aY8-2jGY2dD-UKhrd5-2k1tQqW-74w5K7-2jBpPVU-2hbdED4-q5YnB-2j1e6Ab-2iYKXqy-2iZjkg4-2hMakw7-FM6CzA-2j1QQLX-6N7wEz-nLBHpD-2kLRD-qxCfQm-4HuGm4-op1m6J-8iHXfG-eySJE2-545pPC-oHKkHX-8BeYBe-yv8SH7-7hB7jC-3yEtxR-aCptz-8aBBx6-8aEWVs-6uRjfa-AGMUoh-s8hSXG-8JQJFR-bCG5sh-2hM7U3b-VZGUaZ-EH7bs4-qxwqzx-8kmf6v-5LivxC-8aBBpM">Photo </a>by <a href="https://www.flickr.com/photos/posk/">Art Poskanzer</a> on <a href="https://www.flickr.com/">flickr</a> shared via <a href="https://creativecommons.org/licenses/by/2.0/">CC by 2.0</a></figcaption></figure><pre>### The required libraries and packages ###<br>import networkx as nx<br>import requests<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from matplotlib import cm</pre><h4>Collecting and Preparing the Data</h4><p>Our data set will contain pairwise interactions for a handful of proteins that are involved in serotonin pathways. There are a number of ways these interactions can be found in STRING. We could go to the STRING website with a list of proteins and use the <a href="https://string-db.org/cgi/input?sessionId=bIeslg95qjt0&amp;input_page_active_form=multiple_identifiers">multiple proteins search</a>, but here we want to do everything using Python. The <a href="https://requests.readthedocs.io/en/master/">requests</a> library allows us to easily use HTTP requests to gather the data. The STRING <a href="https://string-db.org/cgi/help?sessionId=bbzQfhU4eZmR">documentation</a> gives details about using the REST API and has lots of examples, but the basic call for gathering network information for multiple proteins looks like this:</p><pre>https://string-db.org/api/[output-format]/network?identifiers=[your_identifiers]&amp;[optional_parameters]</pre><p>The details about output-format, identifiers, and optional parameters can all be found in the documentation. We will use the tsv (tab separated values) output format, a list of protein identifiers separated by %0d’s, and one optional parameter: species. The code to convert the list of proteins into the correct URL is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9136852b6b267bfcc7506f76de345061/href">https://medium.com/media/9136852b6b267bfcc7506f76de345061/href</a></iframe><p>The list of proteins was selected from a larger set of human proteins related to serotonin. One thing to note is the &amp;species=9606 optional parameter. 9606 is the species number for humans. You can select different species by using the <a href="https://string-db.org/cgi/input?sessionId=bIeslg95qjt0&amp;input_page_active_form=organisms">organism search</a>. Next, the data can be converted to a pandas data frame which will be used to create the network.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd6a4ac13048a6a587e8476c79678fb3/href">https://medium.com/media/fd6a4ac13048a6a587e8476c79678fb3/href</a></iframe><h4>Creating the Network</h4><p><a href="https://networkx.org/documentation/stable/index.html">NetworkX</a> includes <a href="https://networkx.org/documentation/stable/reference/classes/index.html#basic-graph-types">several classes of graph</a>. In this case, we will build an <strong>undirected</strong>, <strong>weighted </strong>graph. The graph is undirected because the interaction between protein A and protein B is the same as the interaction between protein B and protein A. The graph is weighted because the edges will have weights based on the interaction score.</p><p>The interactions data frame has one row for each interaction that contains the two interacting proteins and the score of the interaction. The following code shows how that data can be used to build the graph with NetworkX. Each node represents a protein, each edge represents an interaction between two proteins, and each edge is weighted by the score.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/574b28d1604f359d1b9b6900225c5101/href">https://medium.com/media/574b28d1604f359d1b9b6900225c5101/href</a></iframe><p>Here is some basic information about the graph using nx.info(G) :</p><pre>Name: Protein Interaction Graph<br>Type: Graph<br>Number of nodes: 20<br>Number of edges: 128<br>Average degree:  12.8000</pre><p>The graph contains 20 nodes (proteins) with 128 edges (interactions). The <strong>degree </strong>of a node is the number of edges connected to that node. In this graph, the average degree is 12.8. We can create a simple visualization of this graph using the following code. Note the use of nx.spring_layout, which is one of <a href="https://networkx.org/documentation/stable/reference/drawing.html">NetworkX’s node positioning algorithms</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e89a54baa56e4e7f5b078b076380a25/href">https://medium.com/media/3e89a54baa56e4e7f5b078b076380a25/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*FGLNpIVcQw2cznukFnvn-Q.png" /><figcaption>Simple visualization of the protein interaction network. Image by Author</figcaption></figure><p>The simple visualization shown above can be enhanced to include more information about the graph. I already mentioned degree, which is the number of edges connected to a node. Another measure we can include is <a href="https://en.wikipedia.org/wiki/Betweenness_centrality"><strong>betweenness centrality</strong></a>. Each pair of nodes in the graph is connected by one shortest path. In an unweighted graph, the shortest path consists of the smallest set of edges that connect two nodes. In a weighted graph, like we have here, the shortest path consists of the set of edges with the smallest sum of weights. The betweenness centrality of a given node is the measure of the number of shortest paths that pass through that node out of all of the shortest paths. The following code uses the degree and betweenness centrality of each node to determine its color and size and uses the edge weights to determine the color and size of the edges.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d93f7880bfd27777a35e87cda659d38/href">https://medium.com/media/4d93f7880bfd27777a35e87cda659d38/href</a></iframe><p>We can use these color mappings to create an enhanced visualization with this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d169916d3ebea84a55002d5b570c5bd/href">https://medium.com/media/5d169916d3ebea84a55002d5b570c5bd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E22xz5qsvrSQAXyh8bTi_w.png" /><figcaption>Full protein interaction network. Image by Author</figcaption></figure><p>There is a lot more information displayed in this graph. The color range goes from dark purple to bright yellow. The yellower the node, the higher the degree. The larger the node, the greater the betweenness centrality. The yellower and wider the edge, the greater the interaction score.</p><p>One final useful visualization is the <a href="https://en.wikipedia.org/wiki/Minimum_spanning_tree">minimum spanning tree</a>, which is the subset of edges that connect all the nodes with the lowest possible weight:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca7ab12da585c94ff97beb19c9547cd5/href">https://medium.com/media/ca7ab12da585c94ff97beb19c9547cd5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfE535o_pg8mg7xu8sO9fg.png" /><figcaption>Minimum spanning tree for protein interaction network. Image by Author</figcaption></figure><p>Research in the field of <a href="https://www.sas.com/en_us/insights/big-data/data-visualization.html">data visualization</a> has repeatedly shown that humans are particularly <a href="https://www.empiricaldata.org/dataladyblog/6-lessons-from-human-psychology-for-effective-data-visualization">good at finding patterns</a> in visual data. It takes less time and less brain power to <a href="https://hbr.org/2016/06/visualizations-that-really-work">understand a graph</a> that to gather the same information from a table. Visualizations like those described here are great tools for examining and demonstrating any kind of network data. I hope you enjoyed this tutorial and gained some useful techniques that you can employ on your own projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58a9b51be9d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/visualizing-protein-networks-in-python-58a9b51be9d5">Visualizing protein networks in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COVID-19 confirmed cases — an interactive web app]]></title>
            <link>https://medium.com/data-science/covid-19-confirmed-cases-an-interactive-web-app-d5d6de3c0ad3?source=rss-bb50b09eee87------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5d6de3c0ad3</guid>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ford Combs]]></dc:creator>
            <pubDate>Tue, 04 Aug 2020 14:48:11 GMT</pubDate>
            <atom:updated>2020-08-04T22:42:40.004Z</atom:updated>
            <content:encoded><![CDATA[<h3>COVID-19 confirmed cases — an interactive web app</h3><h4>How I used Dash to make the chart I wanted to see</h4><p>News about COVID-19 spikes and surges are all over the internet and data is readily available. The <a href="https://www.cdc.gov/covid-data-tracker/#cases">CDC</a>, <a href="https://usafacts.org/visualizations/coronavirus-covid-19-spread-map/">USAFacts</a>, <a href="https://www.worldometers.info/coronavirus/country/us/">Worldometer</a>, and others all have great data visualizations, but sometimes they don’t have exactly what you are looking for. I wanted to see a line graph of COVID-19 cases for each state, so I made it myself using <a href="https://dash.plotly.com/introduction">Dash</a>. In this article, I’ll walk through the process of building and deploying a Dash app and you can check out my app <a href="https://bystate-covid-app.herokuapp.com/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SVMH4LUh1xg8Tu5imYvPzA.gif" /><figcaption>Choose individual states to add their data to the chart</figcaption></figure><h3>Dash</h3><p>Dash is an easy-to-use web application framework. It allows you to write simple programs in Python that generate beautiful, interactive data visualizations. Dash apps have main two parts: 1) the app layout and 2) the callbacks. First let’s get some boilerplate out of the way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8334a292c28a9381662656fdea6a23f5/href">https://medium.com/media/8334a292c28a9381662656fdea6a23f5/href</a></iframe><p>The #Data prep code here for my app is shown below. The data, which can be downloaded <a href="https://usafacts.org/visualizations/coronavirus-covid-19-spread-map/">here</a>, are read in and a few columns are dropped. The dataframe contains confirmed COVID-19 cases at the county level, so the by_state.groupby code consolidates these data into states counts. Finally, the state ID’s are stored in a list to be used later. There are also a couple of style settings that are used to change the button color, but more on that later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26fc872ae222f88c200e8c2494fec66f/href">https://medium.com/media/26fc872ae222f88c200e8c2494fec66f/href</a></iframe><h4>Layout</h4><p>This is where you add in all the different parts of your app. Using dash_html_components, you can add in HTML components like headings, paragraphs, and divs. Using dash_core_components, you can add in dropdown menus, buttons, graphs, etc. Make sure to check out the documentation for <a href="https://dash.plotly.com/dash-html-components">html</a> and <a href="https://dash.plotly.com/dash-core-components">core</a> components so you can add exactly what you need. For my app, the three most important, interactive components are a checklist for selecting states, a button to select all states, and a date picker for choosing the date range. You can see the code for the app layout below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/283e43a76ed8186d59bbfad8ee7df400/href">https://medium.com/media/283e43a76ed8186d59bbfad8ee7df400/href</a></iframe><p>The dcc.Checklist component allows a user to select which states they want to see in the chart. It’s ID is state-select. The options come from the list of state ID’s described above and value=[&#39;NY&#39;,&#39;TX&#39; is an initial value. The labelStyle keeps the check boxes and associated state ID’s together, otherwise they can get separated as the browser window is adjusted. The html.Button has display text, an ID, the number of times it’s been clicked, and a style variable. The dcc.DatePickerRange allows a user to select the dates they want to see. It has min and max allowed dates and initial start and end dates. The initial visible month determines what calendar month appears when you go to change the range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5PAUphLeKQwAs03APTOvng.gif" /><figcaption>Select a date range using the interactive calendar</figcaption></figure><p>The graph is very simple; it is declared with thedcc.Graph component. It’s ID is &#39;lines&#39; and the config= part removes a mode bar.</p><h4>Callbacks</h4><p>The second part of a Dash app contains callback functions. This is the part that gives an app interactivity. It has a simple format: there is a decorator followed by a function. The inputs and outputs of the app are declared after the @app.callback decorator. Each input and output follows the format (component-id,component-property), where the ids and properties refer back the the app layout code.</p><p>The Outputs and Inputs are both lists. There are four inputs in my app, each comes from one of the interactive components described in the layout. These inputs are then passed to the update_graph callback function. The value from the state-select input is passed into grpnames , the n_clicks from the button is passed into clicks, and so on. For my app, there are two outputs both of which are returned from the update_graph callback function. The Output(&#39;lines&#39;,&#39;figure&#39;) sends the plot to the dcc.Graph component and the Output(&#39;button&#39;,&#39;style&#39;) component sends the style to the html.Button component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5213a1ef01f6d07a778ad765eb1038b7/href">https://medium.com/media/5213a1ef01f6d07a778ad765eb1038b7/href</a></iframe><p>There are a few steps in the update_graph function. First, the number of clicks of the button is used to determine if ‘All States’ has been selected. If the number is odd, then the style variable is set to bl. Next the dates from the dcc.DatePickerRange are reformatted to agree with the downloaded data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8rW9n_14usfIpL5YXyijRw.gif" /><figcaption>Click the ‘All States’ button to visualize the data for every state</figcaption></figure><p>The plot the data segment creates a copy of the dataframe and transforms it from a wide format to a narrow format using the melt function. This allows for easy plotting and you can learn more about that transformation <a href="https://en.wikipedia.org/wiki/Wide_and_narrow_data">here</a>. The if/else code determines if ‘All States’ has been selected and returns a subset of the data, accordingly. Finally, the data are culled to contain the relevant dates selected with the dcc.DataPickerRange.</p><p>Plotly.express is used to plot the data with date on the x-axis, number of confirmed cases on the y-axis, and colored by state. Note that x=&#39;variable&#39; and y=&#39;value&#39; refer to the column names generated by the melt function. Plot and style are returned from the callback and sent to the layout components, as declared in the output statements.</p><h4>Deploying with Heroku</h4><p><a href="https://devcenter.heroku.com/">Heroku</a> is cloud platform where you can deploy all sorts of web applications. It has great documentation, is simple to use, and support python apps. To deploy a Dash app, you can follow the simple instructions <a href="https://dash.plotly.com/deployment">here</a>. Here are the steps I took to deploy my app using <a href="https://ubuntu.com/wsl">WSL</a> to run an Ubuntu terminal inside of Windows.</p><pre>#Step 1<br>mkdir covid_app<br>cd covid_app</pre><p>Now that you have created your directory and cd’ed to it, you need to setup a virutal environment and install the necessary libraries.</p><pre>#Step 2<br>git init<br>virtualenv venv<br>source venv/bin/activate<br>pip install dash<br>pip install plotly<br>pip install gunicorn</pre><p>At a minimum you need four files in your directory: 1) app.py, 2) .gitignore, 3) Procfile, and 4) requirements.txt. app.py is your Dash app, which contains the code described above. The .gitignore file should look like this:</p><pre>venv<br>*.pyc<br>.DS_Store<br>.env</pre><p>The Procfile has <strong>no file extension</strong> and contains one simple line:</p><pre>web: gunicorn app:server</pre><p>You can generate requirements.txt with this command: pip freeze &gt; requirements.txt. Now you can deploy your app with heroku as follows:</p><pre>heroku create my-dash-app<br>git add .<br>git commit -m &#39;Initial commit&#39;<br>git push heroku master <br>heroku ps:scale web=1</pre><h4>Odds and Ends</h4><p>You can check out the app described above <a href="https://bystate-covid-app.herokuapp.com/">here</a>. It’s a simple interactive graph, which performs the visualization that I was curious to see. I may extended the project to contain other visualizations and will try to write about any additions I make. That said, when you start on your own Dash app projects, there are a few other topics you might want to be aware of. One of these is the assets directory. If you create one of these in your app directory, you can include css and JavaScript files to style and add functionality to your app. You can learn more about that <a href="https://dash.plotly.com/external-resources">here</a>. There is even a <a href="https://dash.plotly.com/dash-bio">Dash Bio</a> suite designed specifically for bioinformatics. I’m currently working on a PhD in Bioinformatics, so I will definitely explore that functionality and write about it in future articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5d6de3c0ad3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/covid-19-confirmed-cases-an-interactive-web-app-d5d6de3c0ad3">COVID-19 confirmed cases — an interactive web app</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protein Music with Python (Part 3)- Applying  a Recursive Neural Net]]></title>
            <link>https://medium.com/data-science/protein-music-with-python-part-3-applying-a-recursive-neural-net-c841aee25126?source=rss-bb50b09eee87------2</link>
            <guid isPermaLink="false">https://medium.com/p/c841aee25126</guid>
            <category><![CDATA[sonification]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[biology]]></category>
            <dc:creator><![CDATA[Ford Combs]]></dc:creator>
            <pubDate>Tue, 19 May 2020 15:38:13 GMT</pubDate>
            <atom:updated>2020-05-20T15:26:44.667Z</atom:updated>
            <content:encoded><![CDATA[<h3>Turning a Protein into Music (Part 3) — Recursive Neural Network</h3><h4>Creating music from protein sequences generated by an RNN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*v1ZR4vzKgeFLXwmhCpCiSA.png" /><figcaption>Image created by author with <a href="http://alexlenail.me/NN-SVG/index.html">NN SVG</a></figcaption></figure><p>In two previous articles, I demonstrated how to convert proteins into music. The <a href="https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-ba655c694097">first article</a> explained how the molecular vibrations of individual amino acids, the molecules that make up proteins, can be turned into musical notes. The <a href="https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-part-2-harmony-a3c2ffa748be">second article</a> introduced harmony and rhythm; the amino acid neighbors in the protein structure can be played together to produce chords and the secondary structure classification of an amino acid can determine its note length. Here, I show how to create a <em>genre</em> of protein music by training an RNN on a set of similar proteins and then using it to generate new sequences, which can be converted into music.</p><p><strong>Protein Sonification Background</strong></p><p>A <a href="https://pubs.acs.org/doi/10.1021/acsnano.9b02180">paper</a> from <a href="http://cee.mit.edu/people_individual/markus-j-buehler/">Markus Buehler’s</a> <a href="http://lamm.mit.edu/">Laboratory for Atomistic and Molecular Mechanics</a> at MIT was my introduction to protein sonification. The authors sonified proteins, using the techniques I describe in my previous articles, and then trained a <a href="https://en.wikipedia.org/wiki/Recurrent_neural_network#Long_short-term_memory">recurrent neural network</a> (RNN) on the resulting musical sequences. Once trained, the RNN was used to generate new musical sequences. <strong>Importantly, these new sequences will contain characteristics of the sequences used in training.</strong> This has interesting implications when applied to protein structure research. To understand why, it is useful to understand the basics of RNNs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*na-o15g9BJyH0mmz4X9IXw.jpeg" /><figcaption>Image by author</figcaption></figure><p><strong>Recurrent Neural Networks</strong></p><p>RNNs are one of the many types of neural network architectures. They are typically used with sequential information because they have a form of memory, <em>i.e.</em>, they can look back at previous information while performing calculations<em>. </em>In the case of sequences, this means RNNs predict the next character in a sequence by considering what precedes it. There are many ways this can be implemented and I recommend reading this <a href="https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21">excellent article</a> by Michael Phi to learn more. The authors of the Buehler paper used the <a href="https://magenta.tensorflow.org/">Magenta</a> library, which is powered by TensorFlow, to build their RNN that included an LSTM and an attention layers. I based my model on a model for generating text by <a href="https://www.tensorflow.org/">TensorFlow</a>.</p><p><strong>The Data Set</strong></p><p>The function of a protein is determined by its structure, which is determined by its sequence. Proteins perform many functions like transporting molecules, identifying antigens, or signalling responses and these different functions are made possible by different structures. It follows that there are classes of protein structures that have similar functions. In order for an RNN to generate <em>interesting </em>sequences, it needs to be trained on some class of information. <strong>By interesting, I mean that the generated sequences contain some information or characteristics that are present in the training data.</strong> This is the potential of RNNs for studying protein sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mQ6tVueTcPdDWAEYZwZKVg.gif" /><figcaption><a href="https://pdb101.rcsb.org/learn/videos/coronavirus-main-protease">SARS-CoV-2</a> main protease with inhibitor N3 (white stick representation) [1]</figcaption></figure><p>These are the resources I used to build my data set:</p><ul><li><a href="https://www.uniprot.org/">UniProt</a>[2] is a database that contains protein sequences and functional information. It currently contains 560,000 manually reviewed sequences as of May 15, 2020.</li><li>The <a href="https://www.rcsb.org/">Protein Data Bank</a> (PDB)[3] is a database that contains protein structures. It currently contains about 160,000 as of May 15, 2020.</li><li><a href="https://blast.ncbi.nlm.nih.gov/Blast.cgi">BLAST</a>[4] is a tool that is used to find similar biological sequences. Protein BLAST (<a href="https://blast.ncbi.nlm.nih.gov/Blast.cgi?PROGRAM=blastp&amp;PAGE_TYPE=BlastSearch&amp;LINK_LOC=blasthome">blastp</a>) is the version of this tool used for protein sequences.</li></ul><p>I needed a set of similar protein structures to train the RNN. I chose the SARS coronavirus main protease, <a href="https://www.rcsb.org/structure/1Q2W">PDB ID 1Q2W</a>, as my starting point. I used blasp to search PDB for similar structures and my training data contained 26 protein structures.</p><p><strong>Preparing the Data</strong></p><p>I previously described how amino acid neighbors in the 3D space of a protein structure can be used to build harmonies in protein music. For the purposes of making music, that works well, but for training an RNN, that produces a problem. An amino acid in a protein typically has ~8 neighbors as defined by <a href="https://en.wikipedia.org/wiki/Delaunay_triangulation">Delaunay Tessellation</a>. Since there are 20 standard amino acids, that means that there are 20⁸, over 25 billion, possible combinations of neighbors. Rather than scrap the harmonic information, I wanted to find a way to characterize the group of neighbors as a whole. This is where <em>hydrophobicity </em>enters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e56f5c9488d553784f9ed3252a6ef00/href">https://medium.com/media/2e56f5c9488d553784f9ed3252a6ef00/href</a></iframe><p>A molecule that is attracted to water is known as hydrophilic and one that is repelled is known as hydrophobic. Each of the 20 amino acids has a different affinity toward water and there are different scales for measuring this. The <a href="https://web.expasy.org/protscale/pscale/Hphob.Doolittle.html">Kyte and Doolittle</a> [5] scale assigns a number for each amino acid. On this scale, the more positive the number, the more hydrophobic, and the more negative the number, the more hydrophilic. Using the Kyte and Doolittle scale, a sum of the hydrophobicity scores for each neighbor can be calculated. <strong>This sum holds information about the neighbor set, <em>e.g.</em>, if it is very positive, then most of the neighbors are hydrophobic.</strong> To further simplify this score, the following transformation function was used; it defines the neighbor set hydrophobicity score as either -1, 0, or 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*nlgUIXTRnJf1u9PmQqH_cA.gif" /><figcaption>Neighbor Set Hydrophobicity Scores transformation function</figcaption></figure><h3>Python Code to Prepare Data</h3><h4>Data Collection</h4><p>I chose the protein 1Q2W, the SARS coronavirus main protease, as the target protein for my data set and used <a href="https://blast.ncbi.nlm.nih.gov/Blast.cgi?PAGE=Proteins">blastp</a>[4] to find similar proteins. Below are a few lines of the results of the blastp results. The bold text contains the PDB IDs for similar proteins.</p><pre>1Q2W:A|PDBID|CHAIN|SEQUENCE <strong>4RSP_A </strong>51.792 307 140 4 3 ... 67.75<br>1Q2W:A|PDBID|CHAIN|SEQUENCE <strong>4YLU_A </strong>51.792 307 140 4 3 ... 67.75<br>1Q2W:A|PDBID|CHAIN|SEQUENCE <strong>5WKJ_A </strong>51.792 307 140 4 3 ... 67.75</pre><p>In order to build the data set, the PDB files for the similar proteins were downloaded. The following code accomplishes that in two steps. First, it pulls out the similar protein IDs from the blastp results and, then, it downloads the PDB files for those proteins.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c40dee0f21d1d46a09702b7c77f52272/href">https://medium.com/media/c40dee0f21d1d46a09702b7c77f52272/href</a></iframe><p>Next, the protein sequences, coordinates, and secondary structure classifications can be retrieved. This data is stored in specific lines and positions in PDB files. You can learn more about the PDB format <a href="http://www.wwpdb.org/documentation/file-format-content/format33/v3.3.html">here</a>, but the following code pulls out the relevant data. First, the protein ID is obtained from the HEADER line and, then, secondary structure information is collected. The HELIX and SHEET lines contain the starting and ending positions of all the secondary structure elements. So, for each HELIX or SHEET line, the code fills in the internal positions of each element and adds all the positions to helices and sheets, respectively. Next, the sequence position and coordinates of each atom are pulled from the ATOM lines. In this case, the coordinates for the c-alpha carbon are used for each amino acid. Finally, each position is checked to see if it exists in either helices or sheets. If it does, then an <em>H</em>, helix, or <em>E</em>, sheet, is added to the secondary structure (SS) sequence. If no, then a <em>C</em>, coil, is added. The code below stores this information in the data dictionary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e5a829444c6c64cc5210ec695640d0d/href">https://medium.com/media/9e5a829444c6c64cc5210ec695640d0d/href</a></iframe><p>Below is a function to define amino acid neighbors by Delaunay Tessellation. It takes in the a set of coordinates, in this case the positions of the c-alpha carbon for each amino acid in the protein, and returns a dictionary where each key is a position in the sequence and each value is the set of neighbors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ab1445c87568ac144b5a03b1d34c7d0/href">https://medium.com/media/5ab1445c87568ac144b5a03b1d34c7d0/href</a></iframe><p>The final part of data collection is to create a long sequence that contains all the relevant information for the proteins in the data set. The following code goes through each protein and creates an entry for each position in the sequence. entry contains a string composed of three elements. The first is the amino acid one-letter symbol. Next, is the secondary structure classification. The final part is the neighbor set hydrophobicity score, as described above. All of the sequence entries for each protein are added together to form one long sequence.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4dbe9b2995945600ac45362f3d60a25/href">https://medium.com/media/e4dbe9b2995945600ac45362f3d60a25/href</a></iframe><h4>Data Preparation</h4><p>With sequence, we can now build and train the RNN. I used the model described in this <a href="https://www.tensorflow.org/tutorials/text/text_generation">tutorial</a> as my template. First we define alphabet as the unique entries in sequence. Then we create a mapping for each entry in the sequence to a unique integer and use this mapping to create int_sequence, which contains the sequence in integer form.</p><p>For training, sequence needs to be broken down into smaller sequences. I chose seq_length of 100 arbitrarily, but the best value can be determined through experimentation. Using this length, the data set can be split in input examples and targets. First the data is split into chunk of length seq_length + 1. <strong>Input examples will contain the first 100 entries and the target will contain entries from 1 to 101.</strong> Given an input example, the RNN tries to predict the next entry.</p><p>Next, the training data is lumped into batches. The batch size determines how many training examples to feed the RNN before updating the weights. Updating the weights based on multiple training examples makes the training process more stable. You can learn more about this concept <a href="https://towardsdatascience.com/all-you-need-to-know-about-rnns-e514f0b00c7c">here</a> and there is a nice visualization <a href="https://stats.stackexchange.com/questions/153531/what-is-batch-size-in-neural-network">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abaa906d819d56b42b2cd1dbe41001a4/href">https://medium.com/media/abaa906d819d56b42b2cd1dbe41001a4/href</a></iframe><h4>Model Architecture</h4><p>Now we can construct the RNN. I used the architecture presented <a href="https://www.tensorflow.org/tutorials/text/text_generation">here</a>, which has three layers. There is an <strong>embedding layer</strong> that creates a dense vector of a given size for each entry in the alphabet. The concept of embeddings can be difficult to grasp at first. I find it helpful to consider that an embedding maps each entry to a location in N-dimensional space, where N is your chosen size of the vector. This is useful because in this N-dimensional space, you can calculate relationships between entries using <a href="https://en.wikipedia.org/wiki/Cosine_similarity">cosine similarity</a> or <a href="https://en.wikipedia.org/wiki/Euclidean_distance">euclidean distance</a>. You can learn more about the topic <a href="https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21">here</a> or by studying the <a href="https://pathmind.com/wiki/word2vec">word2vec </a>model, of which embeddings are the core concept.</p><p>The<strong> GRU layer </strong>is what makes this network an RNN. It provides the network with a short term memory. There is an excellent article on GRUs and a similar architecture, called LSTMs, <a href="https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21">here</a>. Finally there is the <strong>dense layer</strong>; this<strong> </strong>is the output layer of the model. It is the layer which generates a vector the size of the alphabet, which contains logits, or the prediction probabilities. The following code is a handy function for building a network.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/668d651ae4523ee24b8545a93e158805/href">https://medium.com/media/668d651ae4523ee24b8545a93e158805/href</a></iframe><p>The following code uses the above function to build the model. The first few lines are the parameters of the model, except for batch_size, which was defined earlier. In order to train, the model needs a loss function and an optimizer. The loss function compares the prediction to the true value and calculates the severity of the error. Here, <a href="https://cwiki.apache.org/confluence/display/MXNET/Multi-hot+Sparse+Categorical+Cross-entropy">sparse categorical cross entropy</a> is used. Adam is used to optimize the learning rate. You can read more about the Adam optimizer in the authors’ <a href="https://arxiv.org/pdf/1412.6980.pdf">paper</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fafa34270b16167d70d19804dd7206db/href">https://medium.com/media/fafa34270b16167d70d19804dd7206db/href</a></iframe><p>The last step before training is to tell the model where to save checkpoints. These are used to load the model weights from different points in the training process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c344b6c7345a627cbc41e528e651e9be/href">https://medium.com/media/c344b6c7345a627cbc41e528e651e9be/href</a></iframe><h4>Train the Model</h4><p>I trained the model for 100 epochs, which took under an hour and generated surprisingly good results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60439fd19ecb2c1d75c22ce1069b178f/href">https://medium.com/media/60439fd19ecb2c1d75c22ce1069b178f/href</a></iframe><h4>Generate Sequences</h4><p>The following code is a function to generate sequences; it is based on the TensorFlow function described <a href="https://www.tensorflow.org/tutorials/text/text_generation#generate_text">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37270947d19d7927fb682edc99037774/href">https://medium.com/media/37270947d19d7927fb682edc99037774/href</a></iframe><p>With the above function, we can prepare the model for sequence generation. The model is rebuilt with the same architecture, except with the batch size set to 1, and the weights from the last checkpoint are loaded.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3744220b03e46ef72ba9f58536bb4180/href">https://medium.com/media/3744220b03e46ef72ba9f58536bb4180/href</a></iframe><p>Now, the RNN can be used to generate new sequences. In the following code, a seed sequence is chosen randomly and then fed into the network.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e43b116dd1c92fbe1ad1dff0a485e584/href">https://medium.com/media/e43b116dd1c92fbe1ad1dff0a485e584/href</a></iframe><h3><strong>Results</strong></h3><p>Here are two amino acid sequences generated by the RNN:</p><ol><li>VKMSHPSGDVEACMVQVTCGSMTLNGLWLDNTVWCPRHVMCCPADQLSDPNYDALLISMTNHSFSVQQKHIGAPANLRVVGHAMQGTLLKKLTVDVANPTTVNLVLKVNQVNPNTPEHKFKSVRPGESFNILACYEGCCPGSVYGVNMRSQGTIKGSFIAGTCGSVGYVLENGTLYFVYMHHLELGNGSHVGSNLEGEMYGGYEDQPSMQLEGTNVMSSDNVVAFLYAALINGERWFVTNTSMSLESYNT</li><li>GLRWGDVEKFNGYTSVSSVDAFSYLAAKTGVSVEQMLGVKGLRKMAQPSGVVEPCIVRVAYGNNVLNGLWLGDEVICPRHVIASDTSRVINYENELSSVRLHNFSIAKNNAFLGVVSAKYKGVNLVLKVNQVNPNTPEHKFKSVRPGESFNILACYEGCPGSVYGVNMRSQGTIKGSFIAGACGSPGYNINNGTVEFCYLHQLELGSGCHVGSDLDGVMYGGYEDQPTLQVEGASSLFTENVLAFLYAAL</li></ol><h4>Proteins Similar to Generated Sequences</h4><p>To see if the RNN learned characteristics about the proteins in the data set, I ran blastp on the generated sequences. Most of the top hits for both sequences were for viral proteases or proteinases. And, about 90 of the top 100 hits were for coronavirus proteins<strong>. </strong>Recall that the RNN was trained on the SARS coronavirus main protease, <strong>so these results suggest that the network did learn key characteristics of coronavirus protease.</strong></p><h4>Protein Structure Prediction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*efY8qnJI2iYmhAPnIAONXg.gif" /><figcaption>The <a href="https://swissmodel.expasy.org/">SWISS-MODEL</a>[6] protein structure prediction for generated sequences 1.</figcaption></figure><p>This idea is further support by protein structure prediction modeling. The first sequence reported above was modeled using <a href="https://swissmodel.expasy.org/">SWISS-MODEL</a> [6], which uses the technique of <a href="https://en.wikipedia.org/wiki/Homology_modeling">homology modeling</a>. In this process, a target sequence is submitted to the server, and SWISS-MODEL compares that sequences to a databases of other sequences of proteins with <em>known structure</em>. It is key that the database contains proteins structures, because once a set of similar sequences is found, the structures associated with those sequences can be used as <em>templates. </em>A template is used to construct a structure prediction for the submitted sequence. The SWISS-MODEL prediction for the first generated sequence and the second can be seen above and below, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*TXwtYTSwwmvwVcysaIlh-w.gif" /><figcaption>The <a href="https://swissmodel.expasy.org/">SWISS-MODEL</a>[6] protein structure prediction for generated sequence 2.</figcaption></figure><p>The similarity between the above structures and the structure of the SARS-CoV-2 main protease, shown at the top of the article, is visible. This further supports that the RNN captured sequence characteristics of viral proteases. There are tools like <a href="http://fatcat.godziklab.org/">FATCAT</a> that can be used to quantitatively compare these structure, but I will save that for another article.</p><h4>Protein Music and Future Work</h4><p>I downloaded the PDB files for the generated structures and used the techniques I previously described to create protein music. You can listen to the melodies, harmonies, and combination of the two below. I have two goals for future work. The first goal is to create a much larger data set of similar proteins to be used in training; here the data set was small, but much larger families of proteins could be used. The second goal concerns the type of data used and generated. Here, I used protein sequence data for training and converted the generated sequences into music. In the future, I’m planning to add one more layer of abstraction; I want to use <a href="https://magenta.tensorflow.org/">Magenta</a> and train an RNN directly on protein music, so that the output is music. Stay tuned and clap if you enjoyed my work!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Fplaylists%252F1053643705%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fford-combs%2Fsets%2Fprotein-music-part-3&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/52ff01f088a5204ecdc4e461e976bfde/href">https://medium.com/media/52ff01f088a5204ecdc4e461e976bfde/href</a></iframe><h4>References</h4><ol><li>Illustration from PDB-101 by David S. Goodsell and RCSB PDB</li><li>The UniProt Consortium<br><strong>UniProt: a worldwide hub of protein knowledge</strong><br><a href="https://doi.org/10.1093/nar/gky1049">Nucleic Acids Res. 47: D506–515 (2019)</a></li><li>H.M. Berman, J. Westbrook, Z. Feng, G. Gilliland, T.N. Bhat, H. Weissig, I.N. Shindyalov, P.E. Bourne.<br>(2000) The Protein Data Bank <a href="http://dx.doi.org/10.1093/nar/28.1.235"><em>Nucleic Acids Research</em>, 28: 235–242.</a></li><li>Altschul, S.F., Gish, W., Miller, W., Myers, E.W. &amp; Lipman, D.J. (1990) “Basic local alignment search tool.” J. Mol. Biol. 215:403–410. <a href="https://www.ncbi.nlm.nih.gov/pubmed/2231712?dopt=Citation">PubMed</a></li><li>J. Mol. Biol. 157:105–132(1982)</li><li>SWISS-MODEL references:</li></ol><ul><li><strong>SWISS-MODEL Workspace/ GMQE</strong><br>Waterhouse, A., Bertoni, M., Bienert, S., Studer, G., Tauriello, G., Gumienny, R., Heer, F.T., de Beer, T.A.P., Rempfer, C., Bordoli, L., Lepore, R., Schwede, T. SWISS-MODEL: homology modelling of protein structures and complexes. Nucleic Acids Res. 46, W296-W303 (2018).</li><li><strong>SWISS-MODEL Repository</strong><br>Bienert, S., Waterhouse, A., de Beer, T.A.P., Tauriello, G., Studer, G., Bordoli, L., Schwede, T. The SWISS-MODEL Repository — new features and functionality. Nucleic Acids Res. 45, D313-D319 (2017).</li><li><strong>Swiss-PdbViewer/ DeepView project mode</strong><br>Guex, N., Peitsch, M.C., Schwede, T. Automated comparative protein structure modeling with SWISS-MODEL and Swiss-PdbViewer: A historical perspective. Electrophoresis 30, S162-S173 (2009).</li><li><strong>QMEANDisCo</strong><br>Studer, G., Rempfer, C., Waterhouse, A.M., Gumienny, G., Haas, J., Schwede, T. QMEANDisCo — distance constraints applied on model quality estimation. Bioinformatics 36, 1765–1771 (2020).</li><li><strong>QMEAN</strong><br>Benkert, P., Biasini, M., Schwede, T. Toward the estimation of the absolute quality of individual protein structure models. Bioinformatics 27, 343–350 (2011).</li><li><strong>Quaternary Structure Prediction/ QSQE</strong><br>Bertoni, M., Kiefer, F., Biasini, M., Bordoli, L., Schwede, T. Modeling protein quaternary structure of homo- and hetero-oligomers beyond binary interactions by homology. Scientific Reports 7 (2017).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c841aee25126" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/protein-music-with-python-part-3-applying-a-recursive-neural-net-c841aee25126">Protein Music with Python (Part 3)- Applying  a Recursive Neural Net</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning a Protein into Music with Python (Part 2) — Harmony]]></title>
            <link>https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-part-2-harmony-a3c2ffa748be?source=rss-bb50b09eee87------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3c2ffa748be</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[bioinformatics]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ford Combs]]></dc:creator>
            <pubDate>Mon, 04 May 2020 18:33:32 GMT</pubDate>
            <atom:updated>2020-05-22T12:56:19.714Z</atom:updated>
            <content:encoded><![CDATA[<h3>Turning a Protein into Music with Python (Part 2) — Harmony</h3><p>Proteins can be turned into music by converting their molecular vibrations into sound waves. I have presented a simple <a href="https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-ba655c694097?source=friends_link&amp;sk=54426e7c7a62bd7eb89e0dd008895775">Python implementation</a> that takes a sequence of amino acids and produces a melody, but music can be more than just melody. The <a href="https://pubs.acs.org/doi/10.1021/acsnano.9b02180?__cf_chl_jschl_tk__=c25b1ad8cf4674b202bdd90af9c7aa2fd48d6889-1586897343-0-AcQi-NxWRr5uZsR7WgQGa_HG7bw2_JVK4GVXeh39HUMVRCLwCOrqo2lyeZRdR6DB3UaM5GbL8UQWs_xCzFqpn2fRZRoqeFkj_UfGRmlD229p2NTmC58h5MdsOtkZyqUGI9ekHrfRhWtQM8-689ucrYP-v1aR-Ef1lIw3fYVVZw-aRfpXOH4Lfo2GyQA4D10jZAPXdStZXGkeTRGQMLDddO_wWc4QwiPSqF7UOPz9VV--YDplR3YRxiDb3MSngsHRqLev98yePv6p6kLzA9zEKkB94aJus69gCbpsPcW396himRBln-KiPvPhMUJS92tX3A">paper</a> which inspired this research presented a method of protein sonification that produces rhythmic, melodic music. This article shows how to extend that method to include harmonies<strong>.</strong></p><p><strong>Melody and Harmony</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*WzoLVy3yfN9EjrwWVnVzbA.jpeg" /><figcaption>The combination of sound waves at different frequencies produces harmonies.</figcaption></figure><p>A simple definition of melody is a succession of notes that are perceived as one musical line. Examples of melodies were produced in the <a href="https://medium.com/swlh/turning-a-protein-into-music-with-python-ba655c694097">first part of this series</a>. While these examples were interesting, most pieces of music include harmony, or sets of notes played simultaneously. Notes played simultaneously can be either pleasant sounding, known as consonant, or tense and discordant, known as dissonant. Our musical tastes determine our definitions of consonance and dissonance, but these opposing concepts exist in all music.</p><p><strong>Protein Harmony</strong></p><p>The major difference between sonification and music composition is that the former is objective and the latter is subjective. Here, the conversion of non-auditory information into sound is a tool to observe the information from a different perspective. The choices made in determining the conversion method can be considered creative and subjective, but these choices cannot come at the price of lost information. In <a href="https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-ba655c694097">part one</a>, protein sequences were converted into melodies by converting the molecular vibrations of each amino acid in the sequence into a note. Harmony can be created by defining a consistent method that identifies groups of notes to play together.</p><p>Proteins are 3D biomolecules. Each amino acid in the protein sequence has neighbors in the 3D space of the protein structure. These neighbors can include amino acids from many different parts of the sequence. <strong>Using this concept, melodic sequences can be accompanied by harmonies composed of the notes of neighboring amino acids .</strong></p><p><strong>Tessellation</strong></p><p>Given a set of points in 3D, there are many ways to define neighbors of a particular point. One simple method is to come up with an arbitrary distance and include all points that fall within that distance from a central point. A more interesting method is to apply the topological concept of tessellation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*RpU-DA6Q7PQpIzGlhAz9gw.gif" /><figcaption>Figure 1. The simplified structure of protein 1SFS.</figcaption></figure><p>Figure 1 displays a simplified structure of the protein 1SFS. Each amino acid in the protein sequence is represented by a single point. This point is positioned according to the x, y, and z coordinates found in the associated PDB file. The lines connecting these points represent the protein backbone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*WydoZNtTTADfsuQy8BaNdA.gif" /><figcaption>Figure 2. The Delaunay tessellation of the 1SFS.</figcaption></figure><p>Figure 2 shows the Delaunay Tessellation (DT) of the set of points described above. You can learn more about the DT <a href="https://www.ti.inf.ethz.ch/ew/Lehre/CG13/lecture/Chapter%206.pdf">here</a>, but the important concept is that each point in the DT is part of one or more <em>simplices, </em>which are collections of four points. <strong>The four points in a simplex are natural neighbors.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*ge70dRkCtaR3JqJRiDSPZg.gif" /><figcaption>Figure 3. The neighbors (gold) of residue 28 (red) as define by the tessellation.</figcaption></figure><p>The DT of a protein can be used to identify all the neighbors of each amino acid in the protein backbone. Figure 3 shows all the neighbors in gold of the residue 28 as defined by the DT. Note that the neighbors come from different regions of the protein backbone.</p><p><strong>DT Neighbors as Harmony</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*P46UQpA_JWyQ0iQNhth94Q.png" /><figcaption>Two different views of the neighbors of the first ten residues of protein 1SFS. 1) shows the amino acids by their 1-letter symbol and 2) shows the corresponding positions in the sequence. The bottom row of both shows the first ten residues of the protein sequence. The columns show all the neighbors at each position.</figcaption></figure><p>Harmony is the foundation upon which a melody rests; it gives support and context to the melody. <strong>Therefore, the harmony that supports a melodic amino acid note can be built out of the neighbors of that note, as defined by the DT.</strong> The figure above shows how both the number of neighbors and positions of the neighbors can vary. In the following sections, I will show you how to implement this technique in Python.</p><blockquote>Please review <a href="https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-ba655c694097">Part 1</a> to learn how to build amino acid notes and convert protein sequences into melody.</blockquote><h3>Python Code</h3><p><strong>Gather Protein Coordinates</strong></p><p>The coordinates for proteins with known structure can be downloaded from the Protein Data Bank (<a href="https://www.rcsb.org/">PDB</a>). Each protein file contains general information about the protein such as the organism of origin, experimental information, and secondary structure classifications. For this technique, we are only interested in the c-alpha coordinates for each amino acid in the chain. You can learn about the PDB file format <a href="http://www.wwpdb.org/documentation/file-format">here</a>. The following code can be used to download a PDB file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a3ec2073cd137d3c56dfd096a67191b/href">https://medium.com/media/9a3ec2073cd137d3c56dfd096a67191b/href</a></iframe><p>This next bit of code will extract the c-alpha atom coordinates for each amino acid in the protein sequence.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fa4e66b2409f52b1c2296cf26fdd1a8/href">https://medium.com/media/2fa4e66b2409f52b1c2296cf26fdd1a8/href</a></iframe><p><strong>Tessellate and Collect Neighbors</strong></p><p>Now that we have the coordinates we can perform the DT. To get a list of neighbors for each amino acid, we can iterate through the list of simplices in the DT and add each simplex to a dictionary, where each key is a position along the backbone and each value is the unique list of neighbors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5cc3f20ebe01a11113c2db0cb277408/href">https://medium.com/media/a5cc3f20ebe01a11113c2db0cb277408/href</a></iframe><p><strong>Determining Harmonies</strong></p><p>A blank matrix of size (20 x length of the sequence) is created to hold the harmonic information. Each row is associated with one of the twenty amino acids. Each column is associated with one position along the protein chain. The matrix is populated by iterating through each set of neighbors in the neighbor dictionary. Each set of neighbors corresponds to one position in the sequence and is associated with one column. A ‘1’ is place in each row if the amino acid associated with that row is found in the set of neighbors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc56e208aefa2a3114b19ad91178cb4c/href">https://medium.com/media/cc56e208aefa2a3114b19ad91178cb4c/href</a></iframe><p>The following code goes through each row and converts strings of 1’s into their sum. For example, [0,0,1,1,1,0,1,1,0] would become [0,0,3,0,0,0,2,0]. This simple conversion allows the harmony to be much more complex. It allows for amino acids that are neighbors of sequential positions along the backbone to be converted into longer lasting notes. So, an amino acid that is the neighbor of three sequential positions along the backbone will become a note that lasts the length of those three melody notes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d59aaa201dafdeda188e90047b834b2/href">https://medium.com/media/1d59aaa201dafdeda188e90047b834b2/href</a></iframe><p><strong>Secondary Structure as Rhythm</strong></p><p>The melodies produced in <a href="https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-ba655c694097">part one</a> were arrythmic, every note had the same duration. The <a href="https://pubs.acs.org/doi/10.1021/acsnano.9b02180?__cf_chl_jschl_tk__=c25b1ad8cf4674b202bdd90af9c7aa2fd48d6889-1586897343-0-AcQi-NxWRr5uZsR7WgQGa_HG7bw2_JVK4GVXeh39HUMVRCLwCOrqo2lyeZRdR6DB3UaM5GbL8UQWs_xCzFqpn2fRZRoqeFkj_UfGRmlD229p2NTmC58h5MdsOtkZyqUGI9ekHrfRhWtQM8-689ucrYP-v1aR-Ef1lIw3fYVVZw-aRfpXOH4Lfo2GyQA4D10jZAPXdStZXGkeTRGQMLDddO_wWc4QwiPSqF7UOPz9VV--YDplR3YRxiDb3MSngsHRqLev98yePv6p6kLzA9zEKkB94aJus69gCbpsPcW396himRBln-KiPvPhMUJS92tX3A">paper</a> that inspired this work used secondary structure (SS) classification to determine note duration. SS refers to local structures found in a protein and there are three main types: helix, strand, and coil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*HBNQVnUeWLdv_4G6UhFW-A.png" /><figcaption>Protein 1SFS colored according to secondary structure: helix (pink), strand (yellow), and coil (white).</figcaption></figure><p>The SS classification for each residue in the protein backbone can be downloaded from PDB in the ‘Sequence’ tab of a given protein entry. Or, you can submit the PDB file to a server like <a href="https://www3.cmbi.umcn.nl/xssp/">DSSP</a>.</p><p><strong>Building Harmonies</strong></p><p>Harmonies are notes played simultaneously. This is accomplished in the following code by building a <em>track </em>for each residue and then combining all the tracks together. The timing and duration of each note is held in the music matrix, so iterating through the rows allows us to building harmonies one amino acid at a time. As we go through each row, first we check for the SS class of that position to determine duration. If the column holds a zero, then a note of zero volume is created. If the column holds a value greater than zero, then a note is created. The total length of the note is calculated by determining the SS at each position and modifying the duration accordingly. Then, a wave of the total length is made and an envelope is applied. Finally, we jump to the column that marks the end of that note length and continue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f485b4d729be908486dbb4a90e3434b/href">https://medium.com/media/5f485b4d729be908486dbb4a90e3434b/href</a></iframe><p>The last part of the above code combines each note sequentially by adding them on top of each other. Wherever multiple notes are sounding, harmonies are created. This idea is displayed he first image of this article.</p><p><strong>Create the Melody</strong></p><p>The following code is used to create the melody in the same manner as <a href="https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-ba655c694097">part one</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a23c5a4d37a924537cd0c99ecd366f2e/href">https://medium.com/media/a23c5a4d37a924537cd0c99ecd366f2e/href</a></iframe><p>With the harmonies and the melodies created, they can be combined and scaled to within the range [-1,1] to prevent audio clipping.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d628391afe484675b48f174e8beca3b8/href">https://medium.com/media/d628391afe484675b48f174e8beca3b8/href</a></iframe><p><strong>Musical Samples</strong></p><p>The complete music can be played in the manner described in <a href="https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-ba655c694097">part one</a> using the <strong>synthesizer</strong> library by <a href="https://github.com/yuma-m/synthesizer">Yuma Mihira</a>. Here are some samples of harmonic protein music:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Fplaylists%252F1043424802%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fford-combs%2Fsets%2Fprotein-music-part-2&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a8a547f9e86cee5b3d8aaad7dd5c1f5/href">https://medium.com/media/4a8a547f9e86cee5b3d8aaad7dd5c1f5/href</a></iframe><p>Make sure to check out <a href="https://towardsdatascience.com/protein-music-with-python-part-3-applying-a-recursive-neural-net-c841aee25126">Part 3</a>, where I apply a recursive neural network.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3c2ffa748be" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-part-2-harmony-a3c2ffa748be">Turning a Protein into Music with Python (Part 2) — Harmony</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning a Protein into Music with Python]]></title>
            <link>https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-ba655c694097?source=rss-bb50b09eee87------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba655c694097</guid>
            <category><![CDATA[protein-structure]]></category>
            <category><![CDATA[bioinformatics]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[sonification]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Ford Combs]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 17:45:18 GMT</pubDate>
            <atom:updated>2020-05-22T12:57:10.252Z</atom:updated>
            <content:encoded><![CDATA[<h3>Turning a Protein into Music with Python (Part 1) — Melody</h3><p>Sonification is the conversion of information into non-speech audio. The classic example is the Geiger counter, which produces a clicking sound whose rate indicates the level of ionizing radiation present. This technique can be applied to pretty much any type of information and a fascinating application was presented in a <a href="https://pubs.acs.org/doi/10.1021/acsnano.9b02180?__cf_chl_jschl_tk__=c25b1ad8cf4674b202bdd90af9c7aa2fd48d6889-1586897343-0-AcQi-NxWRr5uZsR7WgQGa_HG7bw2_JVK4GVXeh39HUMVRCLwCOrqo2lyeZRdR6DB3UaM5GbL8UQWs_xCzFqpn2fRZRoqeFkj_UfGRmlD229p2NTmC58h5MdsOtkZyqUGI9ekHrfRhWtQM8-689ucrYP-v1aR-Ef1lIw3fYVVZw-aRfpXOH4Lfo2GyQA4D10jZAPXdStZXGkeTRGQMLDddO_wWc4QwiPSqF7UOPz9VV--YDplR3YRxiDb3MSngsHRqLev98yePv6p6kLzA9zEKkB94aJus69gCbpsPcW396himRBln-KiPvPhMUJS92tX3A">paper</a> published in June of 2019. It describes a method to convert proteins into music. This conversion is not purely for the sake of art, though. The music is fed into an RNN which can be used to generate new musical sequences. <strong>If proteins of a specific quality are sonified and used to train the neural network, then the musical output will also have that quality. </strong>This has interesting implications in the study of protein structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*7N76KTtMxyGPEkkIopoSxw.png" /><figcaption>Slice of the sound wave for the amino acid Leucine.</figcaption></figure><h4>What exactly are proteins?</h4><p>Proteins are biomolecules that are vital to life. They perform all sort of tasks from transcribing DNA to carrying oxygen in the blood. Proteins form through the <em>folding </em>of a chain of molecules, called amino acids, encoded by a segment of DNA. There are only twenty amino acids used in protein synthesis and all have the same core structure but differ by their <em>side chains</em>. This can be seen in the figure below, which shows the chemical structure of two amino acids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*mUT-rYJ-UllWHtu1oCegrg.png" /><figcaption>Two examples of amino acids: Isoleucine (left) and Leucine (right). The right side of each molecule is the same but the left portion, called the side chain, differs between the two by placement of the methyl group.</figcaption></figure><p>The function of a protein is directly related to its structure and its structure is directly related to its sequence.<strong> </strong>You can learn more about the relationship between sequence and structure <a href="http://www.fordcombs.com/protein_modeling/">here</a>, but the important idea is that the sequence of amino acids determines the structure. Despite our understanding of this relationship, we are still unable to predict the structure of a protein given only its sequence of amino acids.</p><p>This field of <a href="https://en.wikipedia.org/wiki/Protein_structure_prediction">protein structure prediction</a> is constantly advancing and there are many easy-to-use servers available for you to try out. Check out <a href="https://swissmodel.expasy.org/">Swiss-Model</a> and <a href="http://www.sbg.bio.ic.ac.uk/~phyre2/html/page.cgi?id=index">Phyre2</a>, for example. We know the structure of a protein is encoded in its sequence as shown below, but we cannot predict that structure with complete confidence. The sonification of proteins give us a different perspective on the information hidden the amino acid chain and could lead to new advances in the field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*YQ08PV6wSKpThqrpq1Mo-g.png" /><figcaption>By NHGRI — Courtesy: National Human Genome Research Institute, Public Domain, <a href="https://commons.wikimedia.org/w/index.php?curid=1318488">https://commons.wikimedia.org/w/index.php?curid=1318488</a></figcaption></figure><p><strong>Amino Acids as Musical Notes</strong></p><p>A musical note has two basic qualities: pitch and duration. In the simplest terms, the pitch of a note is its frequency in Hz. Whether you play an A4 on the piano or on the guitar, you hear the similar sound of a 440 Hz vibration. The difference between the sounds is known as timbre. When you play a note on any musical instrument, you actually create more than one vibration. You trigger vibrations at whole number multiples of the fundamental vibration; these are known as <a href="https://en.wikipedia.org/wiki/Harmonic#Partials,_overtones,_and_harmonics">harmonics</a> or overtones. The physical qualities of instruments enhance some of these harmonics more than others and this leads to different sonic qualities. <strong>The key concept is that there are many vibrations superposed onto each other. </strong>This can be seen in the sound spectrum of a flute below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*gbX_sgwUxwvyuxq-SKeLzA.gif" /><figcaption><a href="https://newt.phys.unsw.edu.au/music/flute/modernB/A4.html">https://newt.phys.unsw.edu.au/music/flute/modernB/A4.html</a></figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Molecular_vibration"><strong>Molecules vibrate</strong>.</a> The bonds between the atoms can stretch, twist, rock, and make several other motions. These movements are known as vibrational frequencies and they have been measured for the <a href="https://www.sciencedirect.com/science/article/pii/S1044030506007094">amino acids used in protein synthesis</a>. <strong>The novel idea presented in the 2019 paper is that these vibrational modes can be treated as if there were musical overtones. </strong>In the following sections I will show you how you can use this technique to convert proteins into music using python.</p><p><strong>Get the Frequencies</strong></p><p>Here is a dictionary which makes it easy to convert three-letter to one-letter amino acid symbols:</p><pre># Dictionary to be used for converting amino acid abbreviations<br>aa_3to1 = {&#39;CYS&#39;: &#39;C&#39;, &#39;ASP&#39;: &#39;D&#39;, &#39;SER&#39;: &#39;S&#39;,<br>&#39;GLN&#39;: &#39;Q&#39;, &#39;LYS&#39;:&#39;K&#39;,&#39;ILE&#39;: &#39;I&#39;, &#39;PRO&#39;: &#39;P&#39;,<br> &#39;THR&#39;: &#39;T&#39;, &#39;PHE&#39;: &#39;F&#39;, &#39;ASN&#39;: &#39;N&#39;, &#39;GLY&#39;: &#39;G&#39;,<br> &#39;HIS&#39;: &#39;H&#39;, &#39;LEU&#39;: &#39;L&#39;, &#39;ARG&#39;: &#39;R&#39;, &#39;TRP&#39;: &#39;W&#39;,<br> &#39;ALA&#39;: &#39;A&#39;, &#39;VAL&#39;:&#39;V&#39;, &#39;GLU&#39;: &#39;E&#39;, &#39;TYR&#39;: &#39;Y&#39;, &#39;MET&#39;: &#39;M&#39;}</pre><p>You can download a table of the amino acid frequencies from my github <a href="https://github.com/frodoCombs/Amino_Acid_Frequencies">here</a>.</p><pre># Collect amino acid vibrational frequencies as wavenumbers<br># nu refers to the greek letter Nu, used for wavenumbers</pre><pre>import pandas as pd<br>nu_df = pd.read_csv(&#39;path/to/aa_freq.csv&#39;, sep=&#39;,&#39;,header=0)<br># replace NA&#39;s with 0&#39;s<br>nu_df.fillna(0,inplace=True)</pre><p>Note that these are wavenumber frequencies measured in number of cycles per unit distance. Musical frequencies are typically measured in Hz or number of cycles per second, so we need to do the following conversion: frequency = speed of light / (1/wavenumber). This is accomplished below.</p><pre>from scipy.constants import speed_of_light as speedlight<br>#convert to np array<br>nu = nu_df.values<br>for ro in range(nu.shape[0]):<br>    for co in range(nu.shape[1]):<br>        if co == 0:<br>        #Convert amino acid code from 3 letter to 1 letter<br>            aa = nu[ro][co]<br>            aa = aa[0:3].upper()<br>            nu[ro][co]= aa_3to1[aa]<br>        else:<br>        # Convert from wavenumber to frequency<br>        # wavelength = 1/wavenumber<br>        # frequency = speed of light / wavelength<br>            if nu[ro][co] &gt; 0:<br>                freq = speedlight / (1/nu[ro][co])</pre><p>Now we need to scale these frequencies to the human hearing range, which is about 20 to 20,000 Hz. In the code below, the first column from the frequency table, which contains the amino acid one-letter code, is removed and stored in aa_list. Then the table is scaled to the human hearing range.</p><pre>aa_list = nu[:,0]      # list of amino acids<br>nu = nu[:,1:]          # remove first column                <br>max_freq = nu.max()    # max and min <br>min_freq = nu.min()    # need to exclude first column</pre><pre>human_range = 20000 - 20<br>for ro in range(nu.shape[0]):<br>    for co in range(nu.shape[1]):<br>        if nu[ro][co] &gt; 0:<br>            # First scale to 0 to 1<br>            nu[ro][co] = (nu[ro][co] - min_freq)/ max_freq - min_freq<br>            # Scale to human hearing range 20 - 20000 Hz<br>            nu[ro][co] = (nu[ro][co] * human_range) + 20</pre><p><strong>Use Frequencies to Build Musical Notes</strong></p><p>Using the concept of overtones, we can build musical notes for each amino acid by adding the frequencies on top of each other. In a typical musical instrument, the overtones get quieter as they increase in frequency, so I have applied that concept here. There is no correct way to do this. I recommend you experiment by adding the overtones in different ways and listening to the sound that is produced. The following code snippet shows a function to produce an “amino acid note” of a given length.</p><pre>def aa_note(aa,length)<br>    row = np.where(aa_list == aa)[0][0]<br>    wave = np.zeros(int(44100 * float(length)))<br>    harm = 0<br> <br>    for freq in nu[row]:<br>        if freq == 0:<br>            break<br>        else:<br>            volume = np.exp(-harm)<br>            phases = np.cumsum(2.0 * np.pi * freq / 44100 * np.ones(int(44100 * float(length))))<br>            wave += np.sin(phases) * volume<br>            harm += 1<br>    # scale wave to values between 1 and -1<br>    wave = 2.*(wave - wave.min())/np.ptp(wave)-1<br>    return wave</pre><p>The function takes in an amino acid letter and a length, in seconds. The amino acid letter is then used to find the associated row of frequencies in the frequency table. Then an empty wave is initialized with 44100 samples per second and the harmonic counter is initialized to 0. Then a wave is built by going through each frequency in the table. The volume of the frequency is reduced as the harmonic counter increases using an exponential function. Each element in the phases array holds the value of the number of radians the wave has cycled through at a given sample. The phases are then fed into np.sin() to generate the wave which is multiplied by the volume and added to the existing wave. In this way the harmonics are added together at decreasing volumes to create a note of a given length. Finally, this wave is then scaled to a range of [-1,1] to stop the speakers from clipping during playback.</p><p><strong>Making Music</strong></p><p>Now we can make some music using the really cool synthesizer library from <a href="# https://github.com/yuma-m/synthesizer">Yuma Mihira</a>. First we open a player like this:</p><pre>from synthesizer import Player, Synthesizer,<br>player = Player()<br>player.open_stream()</pre><p>Then we create our musical sequence like this:</p><pre># a sample protein sequence<br>protein_sequence = &#39;GIWGVDSAQVVT&#39;</pre><pre>unit_length = 0.5<br>melodic_sequence = []<br>for residue in protein_sequence:<br>    sound_wave = aa_note(residue,unit_length)<br>    melodic_sequence = melodic_sequence + sound_wave.tolist()</pre><pre>melody = np.asarray(melodic_sequence)<br>melody = 2*(melody - melody.min())/np.ptp(melody)-1</pre><p>I’ve include a sample protein sequence, but you can download real sequences from <a href="https://www.uniprot.org/">UniProt</a>. I used a constant unit_length of 0.5 seconds, but you could vary the length creatively. And finally we can play our music.</p><pre>player.play_wave(melody)</pre><p><strong>Music Samples</strong></p><p>Here are some simple examples of well known proteins. Each amino acid note is played for duration of 0.3 seconds with a simple envelope to reduce clipping and some reverb to make it more interesting.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Fplaylists%252F1039116142%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fford-combs%2Fsets%2Fprotein-music&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3a8487bcb4ca79a3e238354a045628b/href">https://medium.com/media/e3a8487bcb4ca79a3e238354a045628b/href</a></iframe><p><strong>Future work</strong></p><p>Using the methods described above, proteins can be converted into musical sequences. On the creative front, several modification to the musical note creation can be played with. Instead of using only sine waves, other types of waves like square or sawtooth waves or combinations of several waveforms could be used. The change in volume with increasing harmonic frequencing could also be varied. Other ideas include the creation of an ADSR envelope to improve the sound quality and some form of note length control to vary the melodic patterns.</p><p>There are two other aspects of the <a href="https://pubs.acs.org/doi/10.1021/acsnano.9b02180?__cf_chl_jschl_tk__=c25b1ad8cf4674b202bdd90af9c7aa2fd48d6889-1586897343-0-AcQi-NxWRr5uZsR7WgQGa_HG7bw2_JVK4GVXeh39HUMVRCLwCOrqo2lyeZRdR6DB3UaM5GbL8UQWs_xCzFqpn2fRZRoqeFkj_UfGRmlD229p2NTmC58h5MdsOtkZyqUGI9ekHrfRhWtQM8-689ucrYP-v1aR-Ef1lIw3fYVVZw-aRfpXOH4Lfo2GyQA4D10jZAPXdStZXGkeTRGQMLDddO_wWc4QwiPSqF7UOPz9VV--YDplR3YRxiDb3MSngsHRqLev98yePv6p6kLzA9zEKkB94aJus69gCbpsPcW396himRBln-KiPvPhMUJS92tX3A">2019 paper</a> that I am working to recreate and publish: i) the application of the music21 library to create scores in traditional western music notation and ii) the training of an RNN so that new music can be created from data sets of similar proteins.</p><p>Make sure to check out <a href="https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-part-2-harmony-a3c2ffa748be">Part 2 (Harmony)</a> and <a href="https://towardsdatascience.com/protein-music-with-python-part-3-applying-a-recursive-neural-net-c841aee25126">Part 3 (RNN)</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba655c694097" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/turning-a-protein-into-music-with-python-ba655c694097">Turning a Protein into Music with Python</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SVM from scratch: step by step in Python]]></title>
            <link>https://fordcombs.medium.com/svm-from-scratch-step-by-step-in-python-f1e2d5b9c5be?source=rss-bb50b09eee87------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1e2d5b9c5be</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ford Combs]]></dc:creator>
            <pubDate>Mon, 16 Dec 2019 18:44:11 GMT</pubDate>
            <atom:updated>2020-05-23T17:22:28.866Z</atom:updated>
            <content:encoded><![CDATA[<p>How to build a support vector machine using the Pegasos algorithm for stochastic gradient descent.</p><p><em>All of the code can be found here: </em><a href="https://github.com/frodoCombs/SVM_tutorials">https://github.com/frodoCombs/SVM_tutorials</a></p><h3>1 What are SVMs?</h3><p>SVMs date back to the early 1960s when Vladimir Vapnik introduced the <em>Generalized Portrait Algorithm </em>(GPA) while working on pattern recognition [1,2]. Over the ensuing years kernels, large margin hyperplanes, and slack variables were developed and some site 1979 as the birth of SVMs with Vapnik’s paper on statistical learning [3]. But what exactly is an SVM?</p><p>Formally, an SVM consists of a maximally separating hyperplane that can be used to classify data. While SVMs can exist in any number of dimensions, a simple two-dimensional model will be used as an example here because it is easy to visualize. In this data set, the samples have two features so each can be plotted in the XY plane as shown below.The sample classes are represented by the color of the point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*UfshnL4ZEU2aOLjc5RJWzQ.png" /><figcaption>Figure 1. A 40-sample, 2-feature, and 2-class data set plotted in the plane. Feature 1 is shown on the X axis and Feature 2 on the Y axis. The class is shown by the color (green for Group 1 and purple for Group 2). Potential hyperplanes (lines in two dimensions) are shown in red, blue and purple.</figcaption></figure><blockquote><strong>The main idea of the SVM is to find the maximally separating hyperplane.</strong></blockquote><p><strong>Figure 1 </strong>shows the 40-sample data set with two features (used as X and Y coordinates) and two classes (represented by color). The three lines represent hypothetical SVMs, where a new data point would be classified based on whether it resides on the side of the line containing purple samples or the side of the line containing green samples.</p><p>In <strong>Figure 1</strong>, each line would classify new data points differently. Line 3 gives a larger area to the green class so a new point, say (0,-2), would be classified as green even though it was closer to the purple cluster. The main idea of the SVM is to find the <strong>maximally separating hyperplane</strong>. In our example, that line might be Line 1, which seems to lie equally far away from each of the cluster. But how do we find the best hyperplane? <strong>Figure 2</strong> shows the output we are aiming for with our SVM. The classifier has created regions for each of the two classes and will classify new points based on which side of the line it occupies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9W1u5dv-tYZFaPoySSAblA.jpeg" /><figcaption>Figure 2. This figure shows the training data points and the regions as classified by the SVM.</figcaption></figure><h3>2 SVM Objective</h3><p>A training set, <em>S</em>, for an SVM is comprised of <em>m </em>samples. The features, <strong><em>x</em></strong>, consist of real numbers and the classifications, <em>y</em>, must be -1 or 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*BxYe29rh_IMQeSar2DcEqQ.gif" /></figure><p>The SVM hyperlane is defined by the weight vector, <em>w</em>, and the bias, <em>b</em>, and is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*SdNh2QQ81ALEuIhrqQP19g.gif" /></figure><p><strong><em>The incorporation of the bias is further explained in section 4.</em></strong></p><p>In the 2-feature example, this can be rewritten as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*r0NlDZ-WB1pxUD0M8mHeGg.gif" /></figure><p>One <strong>important</strong> aspect of SVMs can be seen in <strong>Figure 2. </strong>The black line represents the line described by the equation above, where the weights dotted with the sample equal 0. This should be compared with the colored regions begin, where the weights dotted with the samples are equal or greater than 1 or -1.</p><p>This leads us to the test of correct classification used in training. A correct classification occurs when the weights dotted with the samples multiplied by the classification is greater than 1. Remember that classes must be 1 or -1, so if the SVM has the correct weights then:</p><ol><li>In the case of a sample with the true class of 1, the dot product of the weights and the sample should be positive, and a positive times 1 is positive.</li><li>In the case of a sample with the true class of -1, the dot product of the weights and the sample should be negative, and a negative times -1 is positive.</li></ol><p>So, if the true class multiplied by the weights dotted with the sample is positive, the SVM has correctly classified the sample.</p><h3>3 Pegasos Algorithm</h3><p>There are many methods to find the optimal weight vector and one particularly common one is Sequential Minimal Optimization (SMO) [4]. The SMO algorithm breaks the quadratic programming optimization problem into smaller problems and is very effective at solving SVMs. But, SMO is rather complicated and this example strives for simplicity. The Pegasos algorithm [5] is much simpler and uses stochastic gradient descent (SGD) with a variable step size. SGD is not described here, but there are many good tutorials readily available on the internet. The Pegasos algorithm is shown below in <strong>Figure 3.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*R1GhsOV0UuMbnTwx8A47Zw.jpeg" /><figcaption>Figure 3. The Pegasos algorithm as described in pseudocode [5].</figcaption></figure><h3>4 Step by Step in Python</h3><p><em>All of the code can be found here: </em><a href="https://github.com/frodoCombs/SVM_tutorials">https://github.com/frodoCombs/SVM_tutorials</a></p><p>For this example, the data set was created using the make_blobs function from sklearn as shown below. It creates an X and Y, where the X contains the features and the Y contains the classifications. The function outputs classifications of 0 and 1. These classes need to be converted to -1’s and 1’s. The rest of the code block below is basically used for plotting and drawing <strong>Figure 1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*SmpdhUbDerUR9Mc4OBlOjQ.jpeg" /></figure><blockquote><strong>To incorporate the bias a new feature is added; its value is 1 for every sample.</strong></blockquote><p>The code below splits the data set into testing and training sets and initializes the weight vector. Each sample in the data set initially has two features and a class. But, a feature of value 1 is added to every sample regardless of class. Since the data set now contains 3 features, the weight vector also needs three values. When the weight vector is dotted with the feature vector, since the third feature value is always 1, the third weight will become the intercept, often called the <em>bias</em>. If this is not done, the hyperplane will always go through the origin, and this is unlikely to be the maximally separating hyperplane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*ZFfGIJ2mkF5VQDfdy8wDGA.jpeg" /></figure><p>The justification for adding a feature vector of 1’s to the data set is explained again below. Since the third feature is always 1, the third weight value becomes the bias also known as the intercept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*yfhwk6_CZkK-e_84XHssEg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*zaSAfXO3n3knyAQiQxbohg.gif" /></figure><blockquote><strong>If this is not done, the hyperplane will always go through the origin, and this is unlikely to be the maximally separating hyperplane.</strong></blockquote><p>Below, is the code for the Pegasos algorithm [5]. The learning rate is 0.001 and held in the variable <em>lam. </em>The margin_current and margin_previous keeps track of the size of the margin (<em>remember SVMs want to maximize the margin</em>). The pos_support_vectors and neg_support_vectors variables will keep track of the number of support vectors found. In 2D, there will be at least two support vectors. (<em>Support vectors are the samples the lie directly on the margin, so a maximally wide margin will touch at least one of each class</em>). The variable <em>t</em> will hold the time step and the other variables are self explanatory.</p><p>At each iteration of the loop, the margin and time step are updated and the number of support vectors at that iteration are set to zero. Recall the pseudocode in <strong>Figure 3</strong>, next the update value is calculated. Eta or η in <strong>Figure 3 </strong>is equal to one over lamda times t. Then <em>fac </em>is computed; it holds the full update, (1-ηλ)<strong>w</strong>, as seen in <strong>Figure 3</strong>. It is computed outside of the inner loop to save computational time. Then before entering the inner loop, the data set is shuffled, this isn’t really necessary in this case, but in the <em>online</em> Pegasos algorithm only one sample is used for the update at each time step and should be chosen randomly. Here all the samples are looped over. In the inner loop, each sample is checked to see if it is a support vector, then checked to see if it is correctly classified by the current weight vector. The weight vector update is different for misclassifications. Finally, there is a little part of code that I inserted to check for <em>convergence. </em>In this case, I just check if an arbitrary amount of time steps have pass, if the margin has changed only by a small amount, and if there are at least one of each support vectors. If so, then the algorithm is done and the weight vector has been computed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*1F59g0EyQN9ee0rkYxMFyA.jpeg" /></figure><p>For printing out figures that display the SVM, I like to create a grid and color each point based on its classification. All of this can be seen in the code that is linked above. In <strong>Figure 4</strong>, it can be seen that the SVM correctly classified every sample, and the margins can be seen as green and purple regions. In <strong>Figure 5</strong>, it can be seen that every sample in the test set was also correctly classified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*-U-4Wq_PGl2mzlaOe1gKpQ.jpeg" /><figcaption>Figure 4. Training data set classification by SVM.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*7xNSBiPqMp_2CeN_DWkWag.jpeg" /><figcaption>Figure 5. Test data set classification by SVM.</figcaption></figure><h3>References</h3><ol><li>VAPNIK, V., and A. LERNER, 1963. Pattern recognition using generalized portrait method. <em>Automation and Remote Control</em>, <strong>24</strong>, 774–780.</li><li>VAPNIK, V., and A. CHERVONENKIS, 1964. A note on one class of perceptrons. <em>Automation and Remote Control</em>, <strong>25</strong>.</li><li>VAPNIK, V., 1979. <em>Estimation of Dependences Based on Empirical Data</em> [in Russian]. Moscow: Nauka.</li><li>Platt, J.,1998. <em>Sequential Minimal Optimization: A Fast Algorithm for Training Support Vector Machines.</em> Microsoft Research Technical Report.</li><li>Shalev-Shwartz S, Singer Y, Srebro N, Cotter A (2011) Pegasos: Primal estimated sub-gradient solver for SVM. Math Program. <a href="https://doi.org/10.1007/s10107-010-0420-4">https://doi.org/10.1007/s10107-010-0420-4</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1e2d5b9c5be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>