<?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 Le Nguyen on Medium]]></title>
        <description><![CDATA[Stories by Le Nguyen on Medium]]></description>
        <link>https://medium.com/@ln8378?source=rss-b34fcbf59198------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AkTqC7VeULn17ACsw9nTnQ.jpeg</url>
            <title>Stories by Le Nguyen on Medium</title>
            <link>https://medium.com/@ln8378?source=rss-b34fcbf59198------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:46:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ln8378/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[Simulation 106: Modeling Information Diffusion and Social Contagion with Networks]]></title>
            <link>https://medium.com/data-science/simulation-106-modeling-information-diffusion-and-social-contagion-with-networks-7c1184004889?source=rss-b34fcbf59198------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c1184004889</guid>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[social-network]]></category>
            <dc:creator><![CDATA[Le Nguyen]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 19:07:41 GMT</pubDate>
            <atom:updated>2023-09-07T19:50:36.758Z</atom:updated>
            <content:encoded><![CDATA[<h4>A graph-based approach to modeling the spread of information through social networks</h4><p>Social media has completely revolutionized the information landscape. We are more connected to each other than we have every been in human history. News stories can reach us in an instant and ideas spread across the globe in days, but how does this work? How does information spread and can we model it? In this article, we will cover the theory behind information spread and use networks to model it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGlLfMO6QyFXYVQXdl5Chg.png" /><figcaption>Figure 1: <a href="https://commons.wikimedia.org/wiki/File:Social_Network_Visualization.png">Artistic representation of our world connected by networks</a>. Licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons</a>.</figcaption></figure><p>In this article we will:</p><ul><li>Learn the basics of graph and network theory</li><li>Overview information diffusion and social contagion</li><li>Build a computational framework to simulate the spread of ideas</li></ul><h3>Graphs and Networks</h3><h4>What are Graphs and Networks?</h4><p>A <a href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)">graph</a> is a mathematical structure that shows the relation between objects. It does this by representing each object as a <em>vertex</em> that is connected to other vertices with <em>edges </em>that show the relationship between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*-tZKNdCJADf8Km5PAJzVTA.png" /><figcaption>Figure 2:<a href="https://commons.wikimedia.org/wiki/File:6n-graf.svg"> Example of a graph with 7 edges and 6 vertices</a></figcaption></figure><p>There are many <a href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)#Types_of_graphs">types of graphs</a> including <a href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)#Weighted_graph">weighted graphs</a> where all of the edges are given values to not just show relation but strength of relation and <a href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)#Directed_graph">directed graphs</a> where the edges have a direction to them to show directed relationships. The varying types of graphs make them a powerful tool to show the relationship between entities which we will discuss.</p><p>Conceptually, graphs and <a href="https://en.wikipedia.org/wiki/Network_theory">networks</a> are identical and in most cases the terms can be used interchangeably. Though, by convention, <em>graph </em>is used to refer to the abstract mathematical concept and <em>network</em> is used for applied contexts. For instance, we used the terms “computer network” and “social network” even though computer or social graph would convey the same thing. For our purposes we will say that a network is an applied graph and the only difference in terminology we need is referring to <em>vertices</em> as <em>nodes</em> instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ovqsz38BB3o6f-7YiPmCcA.png" /><figcaption>Figure 3:<a href="https://commons.wikimedia.org/wiki/File:NetworkGraph.png"> Example of a network with specified features</a></figcaption></figure><h4>Graph Theory</h4><p><a href="https://en.wikipedia.org/wiki/Graph_theory#:~:text=In%20mathematics%2C%20graph%20theory%20is,also%20called%20links%20or%20lines).">Graph theory</a> is the branch of mathematics that studies graphs (and networks) and describes the properties of graphs as well as their applications. We will not be covering the entire field of graph theory in this article, but we will look at the highlights relevant to the spread of information.</p><p>The spread of information can be modeled with a <a href="https://en.wikipedia.org/wiki/Flow_graph_(mathematics)">flow graph</a>, or in our case a <a href="https://en.wikipedia.org/wiki/Flow_network">flow network</a>. A flow network is a type of weighted <a href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)#Directed_graph">directed graph</a> that shows the transfer or transport of something within a structure. This could be water through pipes, data through a computer network, or, in our case, information in a social network.</p><p>A flow network has all the components of any network (nodes, edges, weights), but now they are specific representations of the flow of something in a given structure. In our case, <em>nodes </em>are<em> </em>individuals<em> </em>in a social network who are connected to other individuals with <em>edges</em> that are <em>weight</em>ed by the degree of contact they have. Flow networks can also be built with a <em>source, </em>or the origin of the information, along with a <em>sink,</em> where the flow of information terminates and a <em>capacity </em>or maximum amount of information that can go through the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*e1gBlZqsSxK5dRzRfGm5Ew.png" /><figcaption>Figure 4: <a href="https://commons.wikimedia.org/wiki/File:Moreno_Sociogram_2nd_Grade.png">Example of a social flow network</a></figcaption></figure><p>Figure 4 is a social flow network that represents a classroom. Each student (and the teacher) is a node in this network that is connected to others in the classroom with directed edges showing who they have contact with. In this case, the edges are not weighted but the nodes are sized by their <a href="https://en.wikipedia.org/wiki/Centrality">centrality</a>.</p><p>There are many measures of graph/network centrality but overall centrality gives the importance of a node inside of a network. A few examples are <a href="https://en.wikipedia.org/wiki/Centrality#Degree_centrality">degree centrality</a> which is defined as the number of edges connected to a node and <a href="https://en.wikipedia.org/wiki/Centrality#Closeness_centrality">closeness centrality</a> which is the number of short paths a node has to all other nodes. In the case of figure 4, we see nodes sized be degree centrality, with the teacher (SL) being the most central node in the network with the highest degree centrality.</p><p>With a basic understanding of graphs and networks, we can go over the next piece we need; information diffusion and social contagion.</p><h3>Information Diffusion and Social Contagion</h3><p><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7123536/">Information diffusion</a> refers to the spreading of information through a population or system. For a population, information spreads by members interacting in various ways such as in person, online, in writing, through speech or recording. Information diffusion is use to describe the spread of rumors, effectiveness of an advertising campaign, and any other of information through a population.</p><p>We can’t talk about information diffusion without also talking about <a href="https://en.wikipedia.org/wiki/Social_contagion">social contagion</a>. It looks at <em>how</em> information is spread through a population in the information diffusion process and the factors that influence it. Social contagion factors in social connections, media coverage and cultural norms among other things to study how fast or how contagious information is, how much of a population information spreads to, and the resistance members of a population have to new information. Social contagion can be used to study phenomenon like the rapid spread of a viral video, propagation of conspiracy theories, and adoption of new trends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*_J8lYfJQT-f6RKm02lwdSw.jpeg" /><figcaption>Figure 5: <a href="https://commons.wikimedia.org/wiki/File:%D7%94%D7%93%D7%91%D7%A7%D7%94.jpg">Illustration of information diffusion and social contagion</a>. We can see information spreading from a single person and propagating or diffusing through a larger population. The arrows in this diagram indicate a contagion process of this information.</figcaption></figure><h4>Diffusion and Contagion Models</h4><p>Information diffusion and social contagion are both well researched topics that have theoretical models developed for them. We will first look at a simple information diffusion model known as the <a href="https://en.wikipedia.org/wiki/Two-step_flow_of_communication">two-step flow model</a>.</p><p>The two-step flow model starts with mass media of some kind such as a news network or a large company putting out an idea that is then picked up by opinion leaders/highly influential members of a community. Then, members of the community will adopted the idea from opinion leaders they are closest to. This two step process of media to opinion leader then leader to their community assumes most people don’t adopt ideas straight from mass media; they need a source that is closer to them to share the idea for them to adopt it.</p><p>For example, say there’s a new phone releases and there are advertisements for it everywhere. The general population will likely be jaded to the advertising or overwhelmed with advertisements from competing phone companies and it will not convince them to purchase the new phone. Now, if they hear about the new phone from a closer source, say a favorite celebrity, influencer, coworker, or family member, that will be much more persuasive. We can see a visualization of this two-step flow process in figure 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*TaDWJ577_S8z85jUaYQ-uQ.png" /><figcaption>figure 6:<a href="https://scholarworks.rit.edu/cgi/viewcontent.cgi?article=12588&amp;context=theses"> The two-step flow model of information diffusion</a></figcaption></figure><p>Before diving into simulation, we will look at a model for social contagion. Social contagion treats the spread of information like a disease (hence “contagion”) that spreads through contact with the information. Thus, the basic social contagion model draws from disease modeling and resembles a SIR curve like we saw <a href="https://medium.com/@ln8378/simulation-102-agent-based-disease-modeling-17307f2de2f3">previously when we modeled disease spread</a>.</p><p>This curve can be seen in figure 7 which is a line modeling of what we saw in figure 5. First, an idea is held by a individual or small group who spread it to the people closest to them. Then those people spread it to the people closest to them spreading the information outward into the population. This iterative process will spread the idea exponentially at first until it hits a critical mass after going mainstream which will then spread the idea linearly. This growth will start to taper off once it reaches everyone and runs out of people to spread through. This is the same behavior we see with diseases that spread through contact, so it makes sense that information spreads in a similar manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x32tb14WubmzUE0zlH6P7w.png" /><figcaption>Figure 7: <a href="https://scholarworks.rit.edu/cgi/viewcontent.cgi?article=12588&amp;context=theses">Contagion curve of information</a></figcaption></figure><p>We can now combine our understanding of networks and how ideas spread to create a computational framework to simulate the spread of information and ideas.</p><h3>Simulation</h3><p>For this simulation we will be using a python class based approach similar to the one we created in our <a href="https://medium.com/@ln8378/simulation-102-agent-based-disease-modeling-17307f2de2f3">agent-based disease model</a>. We will also be using the <a href="https://networkx.org/">NetworkX </a>library to build networks for us. We first start by creating a network class and adding some initial methods. We need a method to create an initial source of information in our network as well as add new nodes (people) and directed edges (connections). The code to do this is given below and is visualized in figure 8.</p><pre>class Network:<br>    <br>    def create_source(self):<br>        G = nx.DiGraph()<br>        self.G = G<br>        self.G.add_node(0)<br>       <br>    def add_node(self):<br>        index = len(self.G.nodes)<br>        self.G.add_node(index)<br>       <br>    def add_connection(self,node1,node2):<br>        self.G.add_edge(node1,node2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jz4xrs3KAdCxJQoBQglg7Q.png" /><figcaption>Figure 8: Initial methods of network class.</figcaption></figure><p>We can now initialize a source on information, add more people to our network and add connections between the source and the people in the network as well as connect people to other people. We need to add more functionality to our network class before we can run our full simulation though. We need a way to keep track of what people in the network the initial idea has reached and have a mechanism that propagates said idea.</p><p>This is done by adding features to our nodes, which is easily handled by the functionality of NetworkX. We give each person or node in our graph the feature “informed” that is a boolean value that tells us if the idea has reached them or not. Spreading an idea through our network will set more and more nodes to having the value 1 (true) for their <em>informed </em>feature.</p><p>With the <em>informed</em> feature added to our nodes we can also create a method to propagate and idea through our network. We do this by going through the list of edges in our network (provided by the NetworkX object) and seeing which nodes are connected to each other. If an informed node is connected to an uninformed node (<em>informed</em> feature value is 0 or false) then it will propagate its idea to the uninformed node; setting its <em>informed</em> feature value to 1.</p><p>To make this simulation more realistic, we will make the propagation mechanism probabilistic because not all interactions between people share ideas or the specific idea propagating through the graph. We will do this by weighting the edge values (giving the connections between nodes a strength value) and then rolling a random number against this edge value to see if we propagate the idea between the two nodes or not. For this simulation we will weight the edges by the degree centrality of the node they are coming out of, so more central, well connected nodes in the network will have a higher probability of propagating the idea.</p><p>Additionally this random roll against the edge value will be governed by a <em>resistance</em> value. The <em>resistance</em> value is something we see in social contagion theory that determines how resistant a person is to accepting or spreading a new idea. The lower the <em>resistance</em> value of an individual in our network, the more likely they are to roll favorably against the edge value and become informed.</p><p>Adding the <em>informed </em>feature and the propagation method is shown in the code below as well as visualized in figure 8.</p><pre>class Network:<br>    <br>    def create_source(self):<br>        G = nx.DiGraph()<br>        self.G = G<br>        self.G.add_node(0)<br>        self.G.nodes[0][&quot;Informed&quot;] = 1<br>    <br>    def add_node(self):<br>        index = len(self.G.nodes)<br>        self.G.add_node(index)<br>        self.G.nodes[index][&quot;Informed&quot;] = 0<br>        <br>    def add_connection(self,node1,node2):<br>        self.G.add_edge(node1,node2)<br>        self.G[node1][node2][&quot;Connection&quot;] = nx.degree_centrality(self.G)[node1]<br>    <br>    def propogate_information(self, resistance):<br>        for edge in list(self.G.edges):<br>            rand = np.random.uniform(0,resistance)<br>            if self.G.nodes[edge[0]][&quot;Informed&quot;] == 1 and rand &lt; self.G[edge[0]][edge[1]][&quot;Connection&quot;]:<br>                self.G.nodes[edge[1]][&quot;Informed&quot;] = 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6EX_d3TZcCkam9VyOJhcQ.png" /><figcaption>Figure 8: Nodes are now binary colored in green (true) and red (false) to show their informed feature value. Edges are also weighted by degree centrality.</figcaption></figure><p>With the methods we have constructed we can create a social network. Our network starts with a source of information and then we add 100 nodes (people to the network). Next we add in connections between people by randomly selecting 2 nodes out of the network and creating a directed edge between them. This is done 300 times, meaning on average every person is connected to 3 other people. Figure 9 shows the result of doing this with our initial social network where the idea is contained at the source.</p><pre>def get_color(network):<br>    color_dict = dict({0:&quot;red&quot;,1:&quot;green&quot;})<br>    color = list(dict(network.G.nodes(data=&quot;Informed&quot;)).values())<br>    color = [color_dict[i] for i in color]<br>    return color<br><br>network = Network()<br>network.create_source()<br><br>for i in range(0,100):<br>    network.add_node()<br>    <br>nodes = list(network.G.nodes)<br>for i in range(0,300):<br>    if i == 0: <br>        node1 = nodes[0]<br>    else:<br>        node1 = np.random.choice(nodes)<br>    node2 = np.random.choice(nodes)<br>    <br>    if node1 != node2:<br>        network.add_connection(node1,node2)<br><br>        <br>pos = nx.kamada_kawai_layout(network.G)<br>color = get_color(network)<br><br>plt.figure(figsize =(10,10))<br>nx.draw(network.G,  node_color = color, arrowsize=20, pos = pos)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GUEEszJJGu04BPqLDdi6bw.png" /><figcaption>Figure 9: Initial social network</figcaption></figure><p>Now it is time to propagate the idea from our source through the rest of the network. We will simply add our propagation method into a loop and let it spread and idea through our network for a given number of time steps. Here we will propagate the idea for 50 time steps and give everyone a uniform resistance value of 0.3.</p><p>An animation of this spread is shown in figure 10 and the final network in figure 11.</p><pre>informed = []<br>networks = [network.G.copy()]<br>for i in range(0,50):<br>    network.propogate_information(.3)<br>    informed.append(sum(list(dict(network.G.nodes(data=&quot;Informed&quot;)).values())))<br>    networks.append(network.G.copy())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*TIl4WcEgR3Yhh1qO6jfu4A.gif" /><figcaption>Figure 10: Animation of idea propagation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Acs6UBFpWE_sxvNpvVpEFA.png" /><figcaption>Figure 11: Final network</figcaption></figure><p>Through our simulation, we can keep track of how the idea spread through out network by saving the number of informed people per time step. This can be seen in figure 12, which very closes resembles the theoretical curve we would expect from social contagion theory in figure 7. We see the classic S-shaped curve where the idea picks up exponentially, has a linear phase, and then flattens out at the end as our network becomes saturated with the idea. Looking closely at our network, there are a few nodes that have no edges pointing to them, only pointing out of them which means they flow information into the network but the reverse is not true. These nodes will never become informed so our total population will never fully be exposed to the source idea.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*8XGZXIha0fSCy7D5EHb8bw.png" /><figcaption>Figure 12: Contagion curve</figcaption></figure><h3>Conclusion</h3><p>In this article we learned about graphs and networks as mathematical structures that represent relations between objects. We also learned about the spread of ideas by going over information diffusion and social contagion theory. We then combined our understanding of networks and the spread of ideas to simulate the spread of an idea through a social network.</p><h3>Full Code</h3><pre>#Import Libraries<br>import networkx as nx<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import imageio<br><br>#Make helper functions<br>def makeGif(networks, name):<br>    !mkdir frames<br>    <br>    counter=0<br>    images = []<br>    for i in range(0,len(networks)):<br>        plt.figure(figsize = (8,8))<br><br>        color = get_color(networks[i])<br>        nx.draw(networks[i],  node_color = color, arrowsize=20, pos = pos)<br>        plt.savefig(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;)<br>        images.append(imageio.imread(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;))<br>        counter += 1<br>        plt.close()<br><br>    imageio.mimsave(name, images)<br><br>    !rm -r frames<br><br>def get_color(graph):<br>    color_dict = dict({0:&quot;red&quot;,1:&quot;green&quot;})<br>    color = list(dict(graph.nodes(data=&quot;Informed&quot;)).values())<br>    color = [color_dict[i] for i in color]<br>    return color<br><br>#Create Network Class<br>class Network:<br>    <br>    def create_source(self):<br>        G = nx.DiGraph()<br>        self.G = G<br>        self.G.add_node(0)<br>        self.G.nodes[0][&quot;Informed&quot;] = 1<br>    <br>    def add_node(self):<br>        index = len(self.G.nodes)<br>        self.G.add_node(index)<br>        self.G.nodes[index][&quot;Informed&quot;] = 0<br>        <br>    def add_connection(self,node1,node2):<br>        self.G.add_edge(node1,node2)<br>        self.G[node1][node2][&quot;Connection&quot;] = nx.degree_centrality(self.G)[node1]<br>    <br>    def propogate_information(self, resistance):<br>        for edge in list(self.G.edges):<br>            rand = np.random.uniform(0,resistance)<br>            if self.G.nodes[edge[0]][&quot;Informed&quot;] == 1 and rand &lt; self.G[edge[0]][edge[1]][&quot;Connection&quot;]:<br>                self.G.nodes[edge[1]][&quot;Informed&quot;] = 1<br>#Run simulation<br>network = Network()<br>network.create_source()<br><br>for i in range(0,100):<br>    network.add_node()<br>    <br>nodes = list(network.G.nodes)<br>for i in range(0,300):<br>    if i == 0: <br>        node1 = nodes[0]<br>    else:<br>        node1 = np.random.choice(nodes)<br>    node2 = np.random.choice(nodes)<br>    <br>    if node1 != node2:<br>        network.add_connection(node1,node2)<br>        <br>pos = nx.kamada_kawai_layout(network.G)<br>color = get_color(network.G)<br><br>#Plot initial netowork<br>plt.figure(figsize =(10,10))<br>nx.draw(network.G,  node_color = color, arrowsize=20, pos = pos)<br><br>#Propogate idea<br>informed = []<br>networks = [network.G.copy()]<br>for i in range(0,50):<br>    network.propogate_information(.3)<br>    informed.append(sum(list(dict(network.G.nodes(data=&quot;Informed&quot;)).values())))<br>    networks.append(network.G.copy())<br><br>#Plot final network<br>plt.figure(figsize =(10,10))<br>color = get_color(network.G)<br>nx.draw(network.G,  node_color = color, arrowsize=20, pos = pos)<br><br>#Plot contagion curve<br>plt.figure()<br>t = np.arange(0,len(informed),1)<br>plt.plot(t,informed)<br>plt.xlabel(&quot;Time&quot;)<br>plt.ylabel(&quot;Informed Members&quot;)<br>plt.title(&quot;Information Contagion Curve&quot;)<br>plt.savefig(&quot;contagionCurve.png&quot;)<br><br>#Save gif<br>makeGif(networks, &quot;contagion.gif&quot;)<br></pre><h3>References</h3><p>All images used in this article were created by the author, taken from the author’s own work, or fall under <a href="https://creativecommons.org/licenses/">the creative commons license</a>.</p><p>Nguyen, Le, “A Graph-Based Approach to Studying the Spread of Radical Online Sentiment” (2023). Thesis. Rochester Institute of Technology. Accessed from<br>https://scholarworks.rit.edu/theses/11453</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c1184004889" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/simulation-106-modeling-information-diffusion-and-social-contagion-with-networks-7c1184004889">Simulation 106: Modeling Information Diffusion and Social Contagion with Networks</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[Why AI can Program — Linguistic Patterns in Code]]></title>
            <link>https://medium.com/technology-hits/why-ai-can-program-linguistic-patterns-in-code-cba153d832a9?source=rss-b34fcbf59198------2</link>
            <guid isPermaLink="false">https://medium.com/p/cba153d832a9</guid>
            <category><![CDATA[linguistics]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Le Nguyen]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 11:18:20 GMT</pubDate>
            <atom:updated>2023-08-16T11:18:20.915Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why AI can Program — Linguistic Patterns in Code</h3><h4>Zipf’s Law in Code and Software Engineering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RroisKL-8TgZb_puRgw7TQ.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/DuHKoV44prg">https://unsplash.com/photos/DuHKoV44prg</a></figcaption></figure><p>Humans are as much creatures of pattern as habit. There are patterns in everything we make from art, to language, and, as it turns out, code. Before we dig into code, we are going to go into patterns in language and how AI learns from them to see that AI can learn how to code in the same way.</p><h4>Zipf’s Law</h4><p>We can quantify the patterned nature of language using <a href="https://en.wikipedia.org/wiki/Zipf%27s_law">Zipf’s law</a>. Zipf’s law is an empirical law that statistically describes the frequency words (and other language patterns) are used. Zipf’s law states that in any language, the frequency of any word is inversely proportional to its rank when ranked by frequency. That is, if you rank words by the number of uses with a rank <em>n</em>, the frequency of that word is 1/<em>n.</em></p><p>To state it simply, the most frequently used word will appear approximately twice as much as the second most frequently used word and 3 times as much as the third most frequently used word and so on. The frequency of vocabulary used follows a <a href="https://en.wikipedia.org/wiki/Power_law">power law</a> with each word being used only a fraction as much as the word before it (when ordered by frequency). This relation can be seen in the <a href="https://en.wikipedia.org/wiki/Log%E2%80%93log_plot">log-log plot</a> below with texts in various languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYWYb-qV3srGbRfa13DFlg.png" /><figcaption>Log-log plot of ordered word frequency in texts written in various languages. Source: <a href="https://commons.wikimedia.org/wiki/File:Zipf-euro-4_German,_Russian,_French,_Italian,_Medieval_English.svg">https://commons.wikimedia.org/wiki/File:Zipf-euro-4_German,_Russian,_French,_Italian,_Medieval_English.svg</a></figcaption></figure><p>As a result of Zipf’s law, 50% of any given language is expressed with the top 100 most frequently used words. With the top 300 most frequently used words, 65% of language usage is express and 80% with the top 1000 (A fraction of the overall vocabulary). Other language patterns follow Zipf’s law as well such as N-grams (words used in a sequence), collocations (words used together), and grammar rules.</p><h4>AI Language Learning</h4><p>With how regular language is, it’s no wonder that <a href="https://en.wikipedia.org/wiki/Language_model">language models</a> have taken off. As we have seen with Zipf’s law, they only have to master a small percentage of word usage and grammar to have a good understanding of a language. We now have enough data and advanced algorithms that AI can pick up on all the patterns in language and very easily generate new content.</p><p>This can be done with any prediction algorithm that picks up on high-level patterns such as <a href="https://en.wikipedia.org/wiki/Transformer_(machine_learning_model)">transformers</a> or <a href="https://en.wikipedia.org/wiki/Neural_network">neural networks</a>. We most commonly see this on a daily basis with predictive text and auto complete when we type. These models will even pick up on our own pattern of typing as we use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IdKXGC_yNTeW1rpiWOqrCg.png" /><figcaption>Example of predictive text. Source: author generated</figcaption></figure><h4>Zipf’s Law in Code</h4><p>It turns out that we find Zipf’s law in code and in software engineering practice as well. The majority of code is written with only a fraction of all variable names, functions, dependencies and even bugs. We see the same pattern behavior in code as we see in language, so AI can learn code the same way it learns language. We are already seeing this in <a href="https://github.com/features/copilot">GitHub Copilot</a>, and <a href="https://openai.com/blog/openai-codex">OpenAI Codex</a> and all the AIs to come.</p><p>So, why can AI code and how does it do it? Well, it just picks up on all of the patterns we have created and follows them. Does this say more about the complexity of AI or simplicity of humans? Who’s to say.</p><h3>References</h3><p>All images used in this article are openly licensed</p><ol><li>Zipf’s Law in 50 languages: <a href="https://arxiv.org/pdf/1807.01855.pdf">https://arxiv.org/pdf/1807.01855.pdf</a></li><li>Language Learning — 80/20 rule: <a href="https://www.youtube.com/watch?v=lwh-m_XcIP0&amp;ab_channel=SteveKaufmann-lingosteve">https://www.youtube.com/watch?v=lwh-m_XcIP0&amp;ab_channel=SteveKaufmann-lingosteve</a></li><li>Zipf’s Law of Abbreviation In Many Systems: <a href="https://www.sciencedirect.com/science/article/pii/S0010027723001610#:~:text=Abstract,of%20words%20in%20many%20languages">https://www.sciencedirect.com/science/article/pii/S0010027723001610#:~:text=Abstract,of%20words%20in%20many%20languages</a>.</li><li>Top 300 Words in English that Make Up 65% of Written Language: <a href="https://www.latinhire.com/top-300-words-in-english-that-make-up-65-of-written-language/#:~:text=The%20top%20100%20words%20in,of%20text%20or%20spoken%20conversation">https://www.latinhire.com/top-300-words-in-english-that-make-up-65-of-written-language/#:~:text=The%20top%20100%20words%20in,of%20text%20or%20spoken%20conversation</a>.</li><li>Exploring Regularity in Source Code: Software Science and Zipf’s Law: <a href="https://ieeexplore.ieee.org/abstract/document/4656399?casa_token=psyhZ9O-7IYAAAAA:AWfRP30pXFvjtNrL87Y7VCwaoAJ3dfkFo2zyQLyxqDAZmcQezTyWHEVD-1WHQuWDALuGsdZ5tA">https://ieeexplore.ieee.org/abstract/document/4656399?casa_token=psyhZ9O-7IYAAAAA:AWfRP30pXFvjtNrL87Y7VCwaoAJ3dfkFo2zyQLyxqDAZmcQezTyWHEVD-1WHQuWDALuGsdZ5tA</a></li><li>Software Libraries and Their Reuse: Entropy, Kolmogorov Complexity, and Zipf’s Law: <a href="https://arxiv.org/abs/cs/0508023">https://arxiv.org/abs/cs/0508023</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cba153d832a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/technology-hits/why-ai-can-program-linguistic-patterns-in-code-cba153d832a9">Why AI can Program — Linguistic Patterns in Code</a> was originally published in <a href="https://medium.com/technology-hits">Technology Hits</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulation 105: Double Pendulum Modeling with Numerical Integration]]></title>
            <link>https://medium.com/data-science/simulation-105-double-pendulum-modeling-with-numerical-integration-53189ae63959?source=rss-b34fcbf59198------2</link>
            <guid isPermaLink="false">https://medium.com/p/53189ae63959</guid>
            <category><![CDATA[classical-mechanics]]></category>
            <category><![CDATA[numerical-methods]]></category>
            <category><![CDATA[computation]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Le Nguyen]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 19:17:12 GMT</pubDate>
            <atom:updated>2023-08-14T19:17:12.850Z</atom:updated>
            <content:encoded><![CDATA[<h4>Modeling a chaotic system</h4><p>The pendulum is a classical physics system that we are all familiar with. Be it a grandfather clock or a child on a swing, we have seen the regular, periodic motion of the pendulum. A single pendulum is well defined in classical physics, but the double pendulum (a pendulum attached to the end of another pendulum) is <a href="https://en.wikipedia.org/wiki/Chaos_theory">literal chaos</a>. In this article, we are going to build on our intuitive understanding of pendulums and model the chaos of the double pendulum. The physics is interesting and the numerical methods needed are an essential tool in anyone’s arsenal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*CejHLnbeR6qmkhrl1_cTHA.gif" /><figcaption>Figure 1: <a href="https://commons.wikimedia.org/wiki/File:Double_pendulum_predicting_dynamics.gif">Example of a chaotic double pendulum</a></figcaption></figure><p>In this article we will:</p><ul><li>Learn about harmonic motion and model the behavior of a single pendulum</li><li>Learn the fundamentals of chaos theory</li><li>Model the chaotic behavior of a double pendulum numerically</li></ul><h3>Harmonic Motion and the Single Pendulum</h3><h4>Simple Harmonic Motion</h4><p>We describe the periodic oscillating movement of a pendulum as <a href="https://en.wikipedia.org/wiki/Simple_harmonic_motion">harmonic motion</a>. Harmonic motion occurs when there is movement in a system that is balanced out by a proportional restoring force in the opposite direction of said movement. We see an example of this in figure 2 where a mass on a spring is being pulled down due to gravity, but this puts energy into the spring which then recoils and pulls the mass back up. Next to the spring system, we see the height of the mass going around in a circle called a <a href="https://en.wikipedia.org/wiki/Phasor">phasor diagram</a> which further illustrates the regular motion of the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*xZoUzoIdLkLnm3YVtzjBLw.gif" /><figcaption>Figure 2: Example of <a href="https://mathimages.swarthmore.edu/index.php/File:SpringCircle2.gif">simple harmonic motion of a mass on a spring</a></figcaption></figure><p>Harmonic motion can be damped (decreasing in amplitude due to drag forces) or driven (increasing in amplitude due to outside force being added), but we will start with the simplest case of indefinite harmonic motion with no outside forces acting on it (undamped motion). This is kind of motion is a good approximation for modeling a single pendulum that swings at a small angle/low amplitude. In this case we can model the motion with equation 1 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*q6pLgjS-HRy-lTg3nIY4GQ.png" /><figcaption>Equation 1: Simple harmonic motion for a small angle pendulum</figcaption></figure><p>We can easily put this function into code and simulate a simple pendulum over time.</p><pre>def simple_pendulum(theta_0, omega, t, phi):<br>    theta = theta_0*np.cos(omega*t + phi)<br>    return theta<br><br>#parameters of our system<br>theta_0 = np.radians(15) #degrees to radians<br><br>g = 9.8 #m/s^2<br>l = 1.0 #m<br>omega = np.sqrt(g/l)<br><br>phi = 0 #for small angle<br><br>time_span = np.linspace(0,20,300) #simulate for 20s split into 300 time intervals<br>theta = []<br>for t in time_span:<br>    theta.append(simple_pendulum(theta_0, omega, t, phi))<br><br>#Convert back to cartesian coordinates<br>x = l*np.sin(theta)<br>y = -l*np.cos(theta) #negative to make sure the pendulum is facing down</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*rqDXiZ6tbyiKUa-QCToFUQ.gif" /><figcaption>Figure 3: Simple pendulum simulation</figcaption></figure><h4>Full Pendulum Motion with Lagrangian Mechanics</h4><p>A simple small angle pendulum is a good start, but we want to go beyond this and model the motion of a full pendulum. Since we can no longer use <a href="https://en.wikipedia.org/wiki/Small-angle_approximation">small angle approximations</a> it is best to model the pendulum using <a href="https://en.wikipedia.org/wiki/Lagrangian_mechanics">Lagrangian mechanics</a>. This is an essential tool in physics that switches us from looking at the forces in a system to looking at the energy in a system. We are switching our frame of reference from driving force vs restoring force to <a href="https://en.wikipedia.org/wiki/Kinetic_energy">kinetic</a> vs <a href="https://en.wikipedia.org/wiki/Potential_energy">potential</a> energy.</p><p>The Lagrangain is the difference between kinetic and potential energy given in equation 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*HJffhw1mu2TjEiOOmrgoDA.png" /><figcaption>Equation 2: The Lagrangian</figcaption></figure><p>Substituting in the Kinetic and Potential of a pendulum given in equation 3 yields the Lagrangain for a pendulum seen is equation 4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*dAY0kHvuj_OfEE3H0Fo87w.png" /><figcaption>Equation 3: Kinetic and potential energy for a pendulum</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*i9fKRYt7e7qu5Jro47zenw.png" /><figcaption>Equation 4: Lagrangian for a pendulum</figcaption></figure><p>With the Lagrangian for a pendulum we now describe the energy of our system. There is one last math step to go through to transform this into something that we can build a simulation on. We need to bridge back to the dynamic/force oriented reference from the energy reference using the <a href="https://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation">Euler-Lagrange equation</a>. Using this equation we can use the Lagrangian to get the angular acceleration of our pendulum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*xhm---Z0q3wFJrWOmXiRgw.png" /><figcaption>Equation 5: Angular acceleration from the Euler-Lagrange equation</figcaption></figure><p>After going through the math, we have angular acceleration which we can use to get angular velocity and angle itself. This will require some <a href="https://en.wikipedia.org/wiki/Numerical_integration">numerical integration</a> that will be laid out in our full pendulum simulation. Even for a single pendulum, the <a href="https://en.wikipedia.org/wiki/Nonlinear_system">non-linear dynamics</a> means there is no analytical solution for solving for <em>theta, </em>thus the need for a numerical solution. The integration is quite simple (but powerful), we use angular acceleration to update angular velocity and angular velocity to update <em>theta </em>by adding the former quantity to the latter and multiplying this by some time step. This gets us an approximation for the area under the acceleration/velocity curve. The smaller the time step, the more accurate the approximation.</p><pre>def full_pendulum(g,l,theta,theta_velocity, time_step):<br>    #Numerical Integration<br>    theta_acceleration = -(g/l)*np.sin(theta) #Get acceleration<br>    theta_velocity += time_step*theta_acceleration #Update velocity with acceleration<br>    theta += time_step*theta_velocity #Update angle with angular velocity<br>    return theta, theta_velocity<br><br>g = 9.8 #m/s^2<br>l = 1.0 #m<br><br>theta = [np.radians(90)] #theta_0<br>theta_velocity = 0 #Start with 0 velocity<br>time_step = 20/300 #Define a time step<br><br>time_span = np.linspace(0,20,300) #simulate for 20s split into 300 time intervals<br>for t in time_span:<br>    theta_new, theta_velocity = full_pendulum(g,l,theta[-1], theta_velocity, time_step)<br>    theta.append(theta_new)<br><br>#Convert back to cartesian coordinates <br>x = l*np.sin(theta)<br>y = -l*np.cos(theta)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rrhqw2Qrslht69sAYl4_Qg.gif" /><figcaption>Figure 4: Simulation of a full pendulum</figcaption></figure><p>We have simulated a full pendulum, but this is still a well defined system. It is now time to step into the chaos of the double pendulum.</p><h3>Chaos and the Double Pendulum</h3><p><a href="https://en.wikipedia.org/wiki/Chaos_theory">Chaos</a>, in the mathematical sense, refers to systems that are highly sensitive to their initial conditions. Even slight changes in the system’s start will lead to vastly different behaviors as the system evolves. This perfectly describes the motion of the double pendulum. Unlike the single pendulum, it is not a well behaved system and will evolve in a vastly different way with even slight changes in starting angle.</p><p>To model the motion of the double pendulum, we will use the same Lagrangian approach as before (<a href="https://mse.redwoods.edu/darnold/math55/DEproj/sp08/jaltic/presentation.pdf">see full derivation</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0zaQOe2Y5g4HRwVohwEzCw.png" /></figure><p>We will also be using the same numerical integration scheme as before when implementing this equation into code and finding theta.</p><pre>#Get theta1 acceleration <br>def theta1_acceleration(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g):<br>    mass1 = -g*(2*m1 + m2)*np.sin(theta1)<br>    mass2 = -m2*g*np.sin(theta1 - 2*theta2)<br>    interaction = -2*np.sin(theta1 - theta2)*m2*np.cos(theta2_velocity**2*l2 + theta1_velocity**2*l1*np.cos(theta1 - theta2))<br>    normalization = l1*(2*m1 + m2 - m2*np.cos(2*theta1 - 2*theta2))<br>    <br>    theta1_ddot = (mass1 + mass2 + interaction)/normalization<br>    <br>    return theta1_ddot<br><br>#Get theta2 acceleration<br>def theta2_acceleration(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g):<br>    system = 2*np.sin(theta1 - theta2)*(theta1_velocity**2*l1*(m1 + m2) + g*(m1 + m2)*np.cos(theta1) + theta2_velocity**2*l2*m2*np.cos(theta1 - theta2))<br>    normalization = l1*(2*m1 + m2 - m2*np.cos(2*theta1 - 2*theta2))<br>    <br>    theta2_ddot = system/normalization<br>    return theta2_ddot<br><br>#Update theta1<br>def theta1_update(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step):<br>    #Numerical Integration<br>    theta1_velocity += time_step*theta1_acceleration(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g)<br>    theta1 += time_step*theta1_velocity<br>    return theta1, theta1_velocity<br><br>#Update theta2<br>def theta2_update(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step):<br>    #Numerical Integration<br>    theta2_velocity += time_step*theta2_acceleration(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g)<br>    theta2 += time_step*theta2_velocity<br>    return theta2, theta2_velocity<br><br>#Run full double pendulum<br>def double_pendulum(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step,time_span):<br>    theta1_list = [theta1]<br>    theta2_list = [theta2]<br>    <br>    for t in time_span:<br>        theta1, theta1_velocity = theta1_update(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step)<br>        theta2, theta2_velocity = theta2_update(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step)<br><br>        theta1_list.append(theta1)<br>        theta2_list.append(theta2)<br>    <br>    x1 = l1*np.sin(theta1_list) #Pendulum 1 x<br>    y1 = -l1*np.cos(theta1_list) #Pendulum 1 y<br><br>    x2 = l1*np.sin(theta1_list) + l2*np.sin(theta2_list) #Pendulum 2 x<br>    y2 = -l1*np.cos(theta1_list) - l2*np.cos(theta2_list) #Pendulum 2 y<br>    <br>    return x1,y1,x2,y2</pre><pre>#Define system parameters<br>g = 9.8 #m/s^2<br><br>m1 = 1 #kg<br>m2 = 1 #kg<br><br>l1 = 1 #m<br>l2 = 1 #m<br><br>theta1 = np.radians(90)<br>theta2 = np.radians(45)<br><br>theta1_velocity = 0 #m/s<br>theta2_velocity = 0 #m/s<br><br>theta1_list = [theta1]<br>theta2_list = [theta2]<br><br>time_step = 20/300<br><br>time_span = np.linspace(0,20,300)<br>x1,y1,x2,y2 = double_pendulum(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step,time_span)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*qCD4_U64YqrdNsrTKvZczA.gif" /><figcaption>Figure 5: Double pendulum simulation</figcaption></figure><p>We’ve finally done it! We have successfully modeled a double pendulum, but now it’s time to observe some chaos. Our final simulation will be of two double pendulums with slightly different starting condition. We will set one pendulum to have a <em>theta 1 </em>of 90 degrees and the other to have a <em>theta 1</em> of 91 degrees. Let’s see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqE9SnSR6rE9pZlvWQOgDg.gif" /><figcaption>Figure 6: 2 Double pendulums with slightly different starting conditions</figcaption></figure><p>We can see that both pendulums start off with similar trajectories but quickly diverge. This is what we mean when we say chaos, even a 1 degree difference in angle cascades into vastly different end behavior.</p><h3>Conclusion</h3><p>In this article we learned about pendulum motion and how to model it. We started from the simplest harmonic motion model and built up to the complex and chaotic double pendulum. Along the way we learned about the Lagrangian, chaos, and numerical integration.</p><p>The double pendulum is the simplest example of a chaotic system. These systems exist everywhere in our world from <a href="https://support.goldsim.com/hc/en-us/articles/115011378368-Chaotic-Behavior-in-Population-Dynamics">population dynamics</a>, <a href="https://earth.stanford.edu/news/climate-chaos-why-warming-makes-weather-less-predictable">climate</a>, and even <a href="https://plus.maths.org/content/chaos-billiard-table#:~:text=It%20turns%20out%20that%20the,explore%20all%20of%20the%20table.">billiards</a>. We can take the lessons we have learned from the double pendulum and apply them whenever we encounter a chaotic systems.</p><h4>Key Take Aways</h4><ul><li>Chaotic systems are very sensitive to initial conditions and will evolve in vastly different ways with even slight changes to their start.</li><li>When dealing with a system, especially a chaotic system, is there another frame of reference to look at it that makes it easier to work with? (Like the force reference frame to the energy reference frame)</li><li>When systems get too complicated we need to implement numerical solutions to solve them. These solutions are simple but powerful and offer good approximations to the actual behavior.</li></ul><h3>References</h3><p>All figures used in this article were either created by the author or are from <a href="https://mathimages.swarthmore.edu/index.php/Main_Page">Math Images</a> and full under the <a href="http://www.gnu.org/copyleft/fdl.html">GNU Free Documentation License 1.2</a></p><p><a href="https://www.wired.com/2016/07/everything-harmonic-oscillator/">Everything-Yes, Everything-Is a Harmonic Oscillator</a></p><p>Classical Mechanics, John Taylor <a href="https://neuroself.files.wordpress.com/2020/09/taylor-2005-classical-mechanics.pdf">https://neuroself.files.wordpress.com/2020/09/taylor-2005-classical-mechanics.pdf</a></p><h3>Full Code</h3><h4>Simple Pendulum</h4><pre>def makeGif(x,y,name):<br>    !mkdir frames<br>    <br>    counter=0<br>    images = []<br>    for i in range(0,len(x)):<br>        plt.figure(figsize = (6,6))<br><br>        plt.plot([0,x[i]],[0,y[i]], &quot;o-&quot;, color = &quot;b&quot;, markersize = 7, linewidth=.7 )<br>        plt.title(&quot;Pendulum&quot;)<br>        plt.xlim(-1.1,1.1)<br>        plt.ylim(-1.1,1.1)<br>        plt.savefig(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;)<br>        images.append(imageio.imread(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;))<br>        counter += 1<br>        plt.close()<br><br>    imageio.mimsave(name, images)<br><br>    !rm -r frames<br><br>def simple_pendulum(theta_0, omega, t, phi):<br>    theta = theta_0*np.cos(omega*t + phi)<br>    return theta<br><br>#parameters of our system<br>theta_0 = np.radians(15) #degrees to radians<br><br>g = 9.8 #m/s^2<br>l = 1.0 #m<br>omega = np.sqrt(g/l)<br><br>phi = 0 #for small angle<br><br>time_span = np.linspace(0,20,300) #simulate for 20s split into 300 time intervals<br>theta = []<br>for t in time_span:<br>    theta.append(simple_pendulum(theta_0, omega, t, phi))<br><br>x = l*np.sin(theta)<br>y = -l*np.cos(theta) #negative to make sure the pendulum is facing down</pre><h4>Pendulum</h4><pre>def full_pendulum(g,l,theta,theta_velocity, time_step):<br>    theta_acceleration = -(g/l)*np.sin(theta)<br>    theta_velocity += time_step*theta_acceleration<br>    theta += time_step*theta_velocity<br>    return theta, theta_velocity<br><br>g = 9.8 #m/s^2<br>l = 1.0 #m<br><br>theta = [np.radians(90)] #theta_0<br>theta_velocity = 0<br>time_step = 20/300<br><br>time_span = np.linspace(0,20,300) #simulate for 20s split into 300 time intervals<br>for t in time_span:<br>    theta_new, theta_velocity = full_pendulum(g,l,theta[-1], theta_velocity, time_step)<br>    theta.append(theta_new)<br><br>#Convert back to cartesian coordinates <br>x = l*np.sin(theta)<br>y = -l*np.cos(theta)<br><br>#Use same function from simple pendulum<br>makeGif(x,y,&quot;pendulum.gif&quot;)</pre><h4>Double Pendulum</h4><pre>def theta1_acceleration(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g):<br>    mass1 = -g*(2*m1 + m2)*np.sin(theta1)<br>    mass2 = -m2*g*np.sin(theta1 - 2*theta2)<br>    interaction = -2*np.sin(theta1 - theta2)*m2*np.cos(theta2_velocity**2*l2 + theta1_velocity**2*l1*np.cos(theta1 - theta2))<br>    normalization = l1*(2*m1 + m2 - m2*np.cos(2*theta1 - 2*theta2))<br>    <br>    theta1_ddot = (mass1 + mass2 + interaction)/normalization<br>    <br>    return theta1_ddot<br><br>def theta2_acceleration(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g):<br>    system = 2*np.sin(theta1 - theta2)*(theta1_velocity**2*l1*(m1 + m2) + g*(m1 + m2)*np.cos(theta1) + theta2_velocity**2*l2*m2*np.cos(theta1 - theta2))<br>    normalization = l1*(2*m1 + m2 - m2*np.cos(2*theta1 - 2*theta2))<br>    <br>    theta2_ddot = system/normalization<br>    return theta2_ddot<br><br>def theta1_update(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step):<br>    <br>    theta1_velocity += time_step*theta1_acceleration(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g)<br>    theta1 += time_step*theta1_velocity<br>    return theta1, theta1_velocity<br><br>def theta2_update(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step):<br>    <br>    theta2_velocity += time_step*theta2_acceleration(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g)<br>    theta2 += time_step*theta2_velocity<br>    return theta2, theta2_velocity<br><br>def double_pendulum(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step,time_span):<br>    theta1_list = [theta1]<br>    theta2_list = [theta2]<br>    <br>    for t in time_span:<br>        theta1, theta1_velocity = theta1_update(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step)<br>        theta2, theta2_velocity = theta2_update(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step)<br><br>        theta1_list.append(theta1)<br>        theta2_list.append(theta2)<br>    <br>    x1 = l1*np.sin(theta1_list)<br>    y1 = -l1*np.cos(theta1_list)<br><br>    x2 = l1*np.sin(theta1_list) + l2*np.sin(theta2_list)<br>    y2 = -l1*np.cos(theta1_list) - l2*np.cos(theta2_list)<br>    <br>    return x1,y1,x2,y2</pre><pre>#Define system parameters, run double pendulum<br>g = 9.8 #m/s^2<br><br>m1 = 1 #kg<br>m2 = 1 #kg<br><br>l1 = 1 #m<br>l2 = 1 #m<br><br>theta1 = np.radians(90)<br>theta2 = np.radians(45)<br><br>theta1_velocity = 0 #m/s<br>theta2_velocity = 0 #m/s<br><br>theta1_list = [theta1]<br>theta2_list = [theta2]<br><br>time_step = 20/300<br><br>time_span = np.linspace(0,20,300)<br>for t in time_span:<br>    theta1, theta1_velocity = theta1_update(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step)<br>    theta2, theta2_velocity = theta2_update(m1,m2,l1,l2,theta1,theta2,theta1_velocity,theta2_velocity,g,time_step)<br>    <br>    theta1_list.append(theta1)<br>    theta2_list.append(theta2)<br>    <br>x1 = l1*np.sin(theta1_list)<br>y1 = -l1*np.cos(theta1_list)<br><br>x2 = l1*np.sin(theta1_list) + l2*np.sin(theta2_list)<br>y2 = -l1*np.cos(theta1_list) - l2*np.cos(theta2_list)</pre><pre>#Make Gif<br>!mkdir frames<br>    <br>counter=0<br>images = []<br>for i in range(0,len(x1)):<br>    plt.figure(figsize = (6,6))<br><br>    plt.figure(figsize = (6,6))<br>    plt.plot([0,x1[i]],[0,y1[i]], &quot;o-&quot;, color = &quot;b&quot;, markersize = 7, linewidth=.7 )<br>    plt.plot([x1[i],x2[i]],[y1[i],y2[i]], &quot;o-&quot;, color = &quot;b&quot;, markersize = 7, linewidth=.7 )<br>    plt.title(&quot;Double Pendulum&quot;)<br>    plt.xlim(-2.1,2.1)<br>    plt.ylim(-2.1,2.1)<br>    plt.savefig(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;)<br>    images.append(imageio.imread(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;))<br>    counter += 1<br>    plt.close()<br><br>imageio.mimsave(&quot;double_pendulum.gif&quot;, images)<br><br>!rm -r frames</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53189ae63959" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/simulation-105-double-pendulum-modeling-with-numerical-integration-53189ae63959">Simulation 105: Double Pendulum Modeling with Numerical Integration</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[Simulation 104: Electromagnetic Mapping with Vector Fields]]></title>
            <link>https://medium.com/data-science/simulation-104-electromagnetic-mapping-with-vector-fields-96ab3d5e7637?source=rss-b34fcbf59198------2</link>
            <guid isPermaLink="false">https://medium.com/p/96ab3d5e7637</guid>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[magnetism]]></category>
            <category><![CDATA[electricity]]></category>
            <dc:creator><![CDATA[Le Nguyen]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 14:18:41 GMT</pubDate>
            <atom:updated>2023-08-07T15:12:39.871Z</atom:updated>
            <content:encoded><![CDATA[<h4>Modeling electric and magnetic fields</h4><p>Water, fire, air, and dirt, magnets how do they work? It’s not miracles, it’s science! We’ve all played with magnets before be it on the fridge or in science class, but we might not understand what magnets really are or what they do. In this article we will learn the basic theory behind electric and magnetic fields and learn how to make a computational framework to model them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ku3zEu5-TqmJZg9_8CLzQw.png" /><figcaption>Figure 1: <a href="https://en.wikipedia.org/wiki/Magnetic_field">Example of electric field</a></figcaption></figure><p>In this article we will:</p><ul><li>Learn basic electromagnetic (EM) theory</li><li>Create vector fields</li><li>Map out EM fields using vector fields</li></ul><h3>Electric and Magnetic Fields</h3><p>Electromagnetism is one of the <a href="https://www.space.com/four-fundamental-forces.html">4 fundamental forces of the universe</a>. It is the force that governs the behavior of charged particles and electric and magnetic fields are how this force manifests itself. In this section, we will break down the theory behind each of these fields</p><h4>Electric Fields</h4><p><a href="https://en.wikipedia.org/wiki/Electric_field">Electric fields </a>are inherent to charged particles. It is the reason why charged particles can repel and attract each other. By convention, we say that positively charged particles have an electric field that points outward and negatively charged particles have an electric field that points inward seen in figure 2. In the attractive case when a negatively and a positively charged particle are near each other, the field lines start at the positive charge and terminate at the negative charge as seen in figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*xVWcJkxIwv6UTVC94ljX1Q.png" /><figcaption>Figure 2: <a href="https://en.wikipedia.org/wiki/Field_line">Electric field lines</a> for a positive, negative, and neutrally charged particle.</figcaption></figure><p>The force charged particles exert on each other is described by <a href="https://en.wikipedia.org/wiki/Coulomb%27s_law"><strong>Coulomb’s law</strong></a>. Coulomb’s law states that the force between charges is proportional to the charge of each particle divided by the distance between then. The exact equation is stated in equation 1 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*teVI7VgzLAbHUAyQ55GiFg.png" /><figcaption>Equation 1: Coulomb’s law</figcaption></figure><p>We now know the basics of electric fields and can move on to magnetic.</p><h4>Magnetic Fields</h4><p><a href="https://en.wikipedia.org/wiki/Magnetic_field#:~:text=A%20magnetic%20field%20is%20a,electric%20currents%2C%20and%20magnetic%20materials.">Magnetic fields</a> are a bit more complicated than electric fields because they are generated from moving charges. This can be due to electric currents in the case of <a href="https://en.wikipedia.org/wiki/Electromagnet">electromagnets</a> or inherent magnetic dipoles due to electron spin in <a href="https://en.wikipedia.org/wiki/Ferromagnetism">ferromagnets</a>. In either case, the magnetic field is what exerts force between magnets (and moving charges). Magnetic field is more complicated because, unlike charged particles, there are no magnetic monopoles. That is, there are no positive and negative magnets, each one has a north and a south end that are attracted to the opposite end of other magnets. This means that orientation and geometry of the magnets need to be taken into account when determining magnet field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Urs1_tgaDiZpmDGvac9vjg.png" /><figcaption>Figure 3:<a href="https://commons.wikimedia.org/wiki/File:VFPt_cylindrical_magnet_thumb.svg"> Magnetic field lines </a>of a cylindrical magnet</figcaption></figure><p>Because of the complexity of magnetic fields, we are going to be looking at the simplest case of magnets that are so small or so far apart their geometry does not matter. In this case, magnets can be treated like charged particles or rather a positive and negative particle next to each other like in figure 1. This simplified set up is know as<a href="https://en.wikipedia.org/wiki/Magnetic_dipole%E2%80%93dipole_interaction#:~:text=Magnetic%20dipole%E2%80%93dipole%20interaction%2C%20also,in%20calculating%20their%20interaction%20energy."> magnet dipole-dipole interaction</a> and it further simplifies if we assume the magnets are aligned in the same direction.</p><p>With all these simplifying assumptions we get the magnetic field described in equation 2 with the force applied by the magnetic field described in equation 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*am_ySDwqbfSybzVIply7dw.png" /><figcaption>Equation 2: Magnet dipole-dipole field</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*IlcOteKebk9-3eJbtqjRJQ.png" /><figcaption>Equation 3: Magnet dipole-dipole force</figcaption></figure><p>With an understanding of electric and magnetic fields, we will move on to vector fields; a computational scheme which will help us model our fields.</p><p><em>Note: many simplifications were taken in covering the theory behind EM fields for the sake of brevity and simplicity for this introductory article. More advanced explanations will be given in future articles.</em></p><h3>Vector Fields</h3><p><a href="https://en.wikipedia.org/wiki/Vector_(mathematics_and_physics)">Vectors </a>are mathematical representations of quantities that also have an associated direction. For instance, I could tell you the windspeed outside is 25 mph which is the quantity, or scalar, associated with windspeed, but if I told you that the windspeed is 25 mph northeast you now have the windspeed vector since you know the strength or magnitude of the wind as well as what direction it is blowing.</p><p>Keeping with this windspeed analogy, a vector could only represent the wind at one point in space, but let’s say we want to know how the wind is behaving over an entire area. For this, we need a <a href="https://en.wikipedia.org/wiki/Vector_field">vector field</a> which is similar to a mesh grid as discussed in our <a href="https://medium.com/towards-data-science/simulation-101-conductive-heat-transfer-a4f09b3e16b4">pervious article</a>, except instead of looking at points in a grid we are now looking at vectors in a grid. An example of a vector field is shown below in figure 4. As we can see, there are many uniformly spaced vectors with their own direction and size. Visually, the magnitude or strength of the vector is represented by size so bigger vectors represent a higher windspeed in their given direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLTjsRWONbTqDByOUmU-OQ.png" /><figcaption>Figure 4: <a href="https://commons.wikimedia.org/wiki/File:VectorField.svg?uselang=en#Licensing">Example of a vector field</a></figcaption></figure><p>Vector fields are perfect computational tools to model electromagnetic fields because, as we saw in the previous section, they have a strength and direction. We will now go into how to model electric and magnetic fields using vector fields.</p><h3>EM Field Mapping</h3><p>To create our vector fields we are going to be using <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.arrow.html">matplotlib’s arrow function</a>. This function will plot a vector at a given x,y positions along with an x,y magnitude. Combine this with with <a href="https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html">numpy’s mesh grid function </a>and we can create a vector field by making a mesh grid of vectors. Now, let’s get started.</p><h4>Electric Field</h4><p>Let’s first create a <a href="https://docs.python.org/3/tutorial/classes.html">class</a> for charged particle we can call to make however many particles we want. The class will take in a position and a given charge amount to initialize a particle.</p><pre>class charge():<br><br>    def init(self, position, charge):<br>        self.position = np.array(position)<br>        self.charge = charge</pre><p>Now let’s write a function for Coulomb’s law that will take in coulomb’s constant, the charge of a particle, and the distance to some observation point. Note that at this point we are using Coulomb’s law to look at the field strength at some observation point due to one particle so the charge of a second particle is not needed (yet). Also note we are representing our direction unit vector with <em>r</em> divided by the magnitude of <em>r</em>.</p><pre>def coulombs_law(k,q,r):<br>    F = k*q*r/(np.linalg.norm(r))**3<br>    return F</pre><p>Let’s map the electric field around a single charged particle. We will make a ring of observation points around our particle and see what the field strength (magnitude) and direction is. Our results will be seen in figure 5.</p><pre>#Define coulomb&#39;s constant and charge of our particle<br>k = 8.9e9                           <br>q = 0.1e-6    <br><br>#Make our charged particle<br>particle = charge()<br>particle.init([0,0],q)<br><br>#Define our source and observation points<br>source = np.array(particle.position)<br>observations = []<br>r = []<br>field = []<br>#Need to scale our vectors to always have a visible magnitude<br>visual_scale = []<br><br>#Loop over points in a circle around our charge<br>for i in np.linspace(0,2*np.pi,20):<br>    observations.append(np.array([0.1*np.cos(i),0.1*np.sin(i)]))          <br>    r.append(observations[-1] - source)                <br>    field.append(coulombs_law(k,q,r[-1]))  <br>    visual_scale.append(np.linalg.norm(r[-1])/np.linalg.norm(field[-1])/2)  <br><br>#Plot our particle and the vector field around it<br>fig = plt.figure(figsize=(5,5))<br>plt.plot(particle.position[0],particle.position[1],&#39;ro&#39;)<br><br>for j in range(0, len(observations)):<br>    plt.arrow(observations[j][0],observations[j][1],visual_scale[j]*field[j][0],visual_scale[j]*field[j][1])  <br><br>plt.title(&quot;Positively Charged Particle&quot;);<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*txxGo5vhttTo2AjoztnwLA.png" /><figcaption>Figure 5: Simulated positively charged particle with electric field</figcaption></figure><p>We have successfully simulated the electric field around a single charged particle which is cool, but let’s simulate something more interesting. How about a negative charge next to a positive one like in figure 1? Now we will have 2 charged particles with equal and opposite charges so we have to keep track of the electric field from both particles and see how they add up to the overall field. This will require us to find 2 distance <em>r</em>s from each particle to a given observation point and then find the vector contribution of field from each particle to <a href="https://www.physicsclassroom.com/class/vectors/Lesson-1/Vector-Addition">sum them up</a> and get the overall field at that observation point.</p><p>Here we will be using a mesh grid of observation points to create a vector field. See results for our electric charge dipole in figure 6.</p><pre>#Define coulomb&#39;s constant and charge of our particle<br>k = 8.9e9                           <br>q = 0.1e-6  <br><br>#Make our charges<br>q1 = charge()<br>q2 = charge()<br>q1.init([0.4,0],q)<br>q2.init([-0.4,0],-q)<br><br>#Make a meshgrid of observation points<br>x = np.linspace(-.8,.8,20)<br>X,Y = np.meshgrid(x,x)<br>grid =[]<br>for i in range(0, len(X)):<br>    for j in range(0, len(Y)):<br>        grid.append([X[i][j],Y[i][j]])<br><br>#Define our needed quantities<br>observations = np.array(grid)  <br>r1 = []<br>r2 = []<br>field1 = []<br>field2 = []<br>field_total = []<br><br>#Loop through observation points<br>for n in range(0,len(observations)):<br>           <br>    r1.append(observations[n] - q1.position)               <br>    r2.append(observations[n] - q2.position)<br>    <br>    field1.append(coulombs_law(k,q1.charge,r1[-1]))  <br>    field2.append(coulombs_law(k,q2.charge,r2[-1]))<br>    field_total.append(field1[-1]+field2[-1])<br><br>#Scale x and y<br>field_total = np.array(field_total)<br>scale_x = .3/max(field_total[:,0])<br>scale_y = .3/max(field_total[:,1])<br>    <br>#Plot vector field<br>fig = plt.figure(figsize=(5,5))<br><br>plt.plot(q1.position[0],q1.position[1],&#39;ro&#39;, label = &quot;Positive&quot;)<br>plt.plot(q2.position[0],q2.position[1],&#39;bo&#39;, label = &quot;Negitive&quot;)<br><br>for j in range(0, len(observations)):<br>    plt.arrow(observations[j][0],observations[j][1],scale_x*field_total[j][0],scale_y*field_total[j][1], head_width = .025)  <br><br>plt.title(&quot;Electric Field of Positive and Negative Charge&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*nfkCrZk5giBbJBQHdf0yiQ.png" /><figcaption>Figure 6: Simulated electric field for charge dipole</figcaption></figure><p>We’ve have now simulated the electric field for a positive and negative charge like in figure 1. As we can see all of the vector heads are pointing in the correct direction; from the positive charge (red) to the negative charge (blue). There is some visual noise added by looking at observation points near our charged particles. Due to how Coulomb’s law is formulated, as the distance from the particle goes to 0, the field strength will go to infinity; thus we will get large vectors looking at points near the charges. We can choose to normalize them or remove them or just keep them in as a sanity check.</p><p>Now that we have simulated electric field, it’s time to move onto magnetic.</p><h4>Magnetic Field</h4><p>As we simplified our magnetic field scenario to look like electric field, the code will look very similar. We will define a magnet class and a dipole-dipole interaction function. Note that different from equation 2, I use x and y coordinates instead of a distance <em>r</em>. This just makes the computation cleaner since unlike particle charge, dipole (<em>m</em>) is a vector in itself with x,y components. Also note that here we will be mapping <em>magnetic field </em>not<em> magnetic force. </em>The magnetic force applied by a magnetic field is dependent on how a charged particle/other magnetic moves through it which is outside the scope of this article.</p><pre>class magnet():<br><br>    def init(self, position, dipole):<br>        self.position = np.array(position)<br>        self.dipole = dipole<br><br>def dipole_dipole(u_0,m,x,y):<br>    <br>    r = np.sqrt(x**2 + y**2)<br>    r_hat_x = x / r<br>    r_hat_y = y / r<br><br>    factor = (u_0 / (4 * np.pi)) * (3 * (m[0] * r_hat_x + m[1] * r_hat_y))<br>    <br>    Bx = factor * r_hat_x - m[0]<br>    By = factor * r_hat_y - m[1]<br><br>    Bx /= r**3<br>    By /= r**3<br><br>    return Bx, By</pre><p>Now let us simulate a magnetic field. Here we will simulate the magnetic field of an electron and use its dipole.</p><pre>#Define magnetic constant and dipole of our magnet<br>u_0 = 4*np.pi*10**-7<br>#dipole on an electron<br>m = (-9.28*10**-24,0)   <br><br>#Make our magnets<br>m1 = magnet()<br>m1.init([.1,0],m)<br><br>#Make a meshgrid of observation points<br>x = np.linspace(-.5,.5,20)<br>X,Y = np.meshgrid(x,x)<br>grid =[]<br>for i in range(0, len(X)):<br>    for j in range(0, len(Y)):<br>        grid.append([X[i][j],Y[i][j]])<br><br>#Define our needed quantities<br>observations = np.array(grid)  <br>field1 = []<br><br>#Loop through observation points<br>for n in range(0,len(observations)):<br>           <br>    x = observations[n][0] - m1.position[0]               <br>    y = observations[n][0] - m1.position[1]<br>    <br>    field1.append(dipole_dipole(u_0,m1.dipole,x,y))  <br>    <br>#Scale x and y<br>field_total = np.array(field1)<br>scale_x = .1/max(field_total[:,0])<br>scale_y = .1/max(field_total[:,1])<br>    <br>#Plot vector field<br>fig = plt.figure(figsize=(5,5))<br><br>plt.plot(m1.position[0],m1.position[1],&#39;rs&#39;)<br><br>for j in range(0, len(observations)):<br>    plt.arrow(observations[j][0],observations[j][1],scale_x*field1[j][0],scale_y*field1[j][1], head_width = .02)  <br><br>plt.title(&quot;Magnetic Field of an Electron&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*m5fRyMjef4y4_1e8lYX7bQ.png" /><figcaption>Figure 7: Simulated magnetic field of an electron</figcaption></figure><p>Here we see our simulated magnetic field of an electron. It looks a bit odd because we are only working in 2 dimensions so really we are only seeing a vertical slice of the magnetic field. In 3 dimensions <a href="http://www.faithfulscience.com/classical-physics/electric-and-magnetic-fields.html">we would see the vectors curl towards us and coil around the electron</a>.</p><p>We will see the same effect with 2 electrons as well.</p><pre>#Define coulomb&#39;s constant and charge of our particle<br>u_0 = 4*np.pi*10**-7                          <br>m = (-9.28*10**-24,0)   <br><br>#Make our charges<br>m1 = magnet()<br>m2 = magnet()<br>m1.init([0,.2],m)<br>m2.init([0,0],m)<br><br>#Make a meshgrid of observation points<br>x = np.linspace(-1,1,30)<br>X,Y = np.meshgrid(x,x)<br>grid =[]<br>for i in range(0, len(X)):<br>    for j in range(0, len(Y)):<br>        grid.append([X[i][j],Y[i][j]])<br><br>#Define our needed quantities<br>observations = np.array(grid)  <br>field1 = []<br>field2 = []<br>field_total = []<br><br>#Loop through observation points<br>for n in range(0,len(observations)):<br>           <br>    x1 = observations[n][0] - m1.position[0]               <br>    y1 = observations[n][0] - m1.position[1]<br>    <br>    x2 = observations[n][0] - m2.position[0]               <br>    y2 = observations[n][0] - m2.position[1]<br>    <br>    field1.append(dipole_dipole(u_0,m1.dipole,x1,y1))  <br>    field2.append(dipole_dipole(u_0,m2.dipole,x2,y2))<br>    field_total.append(field1[-1]+field2[-1])<br><br>#Scale x and y<br>field_total = np.array(field_total)<br>scale_x = .1/max(field_total[:,0])<br>scale_y = .1/max(field_total[:,1])<br>    <br>#Plot vector field<br>fig = plt.figure(figsize=(5,5))<br><br>plt.plot(m1.position[0],m1.position[1],&#39;ro&#39;, label = &quot;Positive&quot;)<br>plt.plot(m2.position[0],m2.position[1],&#39;bo&#39;, label = &quot;Negitive&quot;)<br><br>for j in range(0, len(observations)):<br>    plt.arrow(observations[j][0],observations[j][1],scale_x*field_total[j][0],scale_y*field_total[j][1], head_width = .025)  <br><br>plt.title(&quot;Magnetic Field of 2 Electrons&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*RlsyUb8mTBiKkUo1qm7PqQ.png" /><figcaption>Figure 8: Magnetic field of 2 electrons (they are represented by different color but have the same dipole)</figcaption></figure><p>This may not be the most intuitive result, but in a future article we will do EM field mapping in 3 dimensions and include geometry to see better defined fields.</p><h3>Full Code</h3><h4>Electric Field</h4><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br>class charge():<br><br>    def init(self, position, charge):<br>        self.position = np.array(position)<br>        self.charge = charge<br><br>def coulombs_law(k,q,r):<br>    F = k*q*r/(np.linalg.norm(r))**3<br>    return F<br><br>#Define coulomb&#39;s constant and charge of our particle<br>k = 8.9e9                           <br>q = 0.1e-6  <br><br>#Make our charged particle<br>particle = charge()<br>particle.init([0,0],q)<br><br>#Define our source and observation points<br>source = np.array(particle.position)<br>observations = []<br>r = []<br>field = []<br>#Need to scale our vectors to always have a visible magnitude<br>visual_scale = []<br><br>#Loop over points in a circle around our charge<br>for i in np.linspace(0,2*np.pi,20):<br>    observations.append(np.array([0.1*np.cos(i),0.1*np.sin(i)]))          <br>    r.append(observations[-1] - source)                <br>    field.append(coulombs_law(k,q,r[-1]))  <br>    visual_scale.append(np.linalg.norm(r[-1])/np.linalg.norm(field[-1])/2)  <br><br>#Plot our particle and the vector field around it<br>fig = plt.figure(figsize=(5,5))<br>plt.plot(particle.position[0],particle.position[1],&#39;ro&#39;)<br><br>for j in range(0, len(observations)):<br>    plt.arrow(observations[j][0],observations[j][1],visual_scale[j]*field[j][0],visual_scale[j]*field[j][1])  <br><br>plt.title(&quot;Positively Charged Particle&quot;);</pre><pre>#Make our charges<br>q1 = charge()<br>q2 = charge()<br>q1.init([0.4,0],q)<br>q2.init([-0.4,0],-q)<br><br>#Make a meshgrid of observation points<br>x = np.linspace(-.8,.8,20)<br>X,Y = np.meshgrid(x,x)<br>grid =[]<br>for i in range(0, len(X)):<br>    for j in range(0, len(Y)):<br>        grid.append([X[i][j],Y[i][j]])<br><br>#Define our needed quantities<br>observations = np.array(grid)  <br>r1 = []<br>r2 = []<br>field1 = []<br>field2 = []<br>field_total = []<br><br>#Loop through observation points<br>for n in range(0,len(observations)):<br>           <br>    r1.append(observations[n] - q1.position)               <br>    r2.append(observations[n] - q2.position)<br>    <br>    field1.append(coulombs_law(k,q1.charge,r1[-1]))  <br>    field2.append(coulombs_law(k,q2.charge,r2[-1]))<br>    field_total.append(field1[-1]+field2[-1])<br><br>#Scale x and y<br>field_total = np.array(field_total)<br>scale_x = .3/max(field_total[:,0])<br>scale_y = .3/max(field_total[:,1])<br>    <br>#Plot vector field<br>fig = plt.figure(figsize=(5,5))<br><br>plt.plot(q1.position[0],q1.position[1],&#39;ro&#39;, label = &quot;Positive&quot;)<br>plt.plot(q2.position[0],q2.position[1],&#39;bo&#39;, label = &quot;Negitive&quot;)<br><br>for j in range(0, len(observations)):<br>    plt.arrow(observations[j][0],observations[j][1],scale_x*field_total[j][0],scale_y*field_total[j][1], head_width = .025)  <br><br>plt.title(&quot;Electric Field of Positive and Negative Charge&quot;)<br></pre><h4>Magnetic Field</h4><pre>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre>class magnet():<br><br>    def init(self, position, dipole):<br>        self.position = np.array(position)<br>        self.dipole = dipole<br><br>def dipole_dipole(u_0,m,x,y):<br>    <br>    r = np.sqrt(x**2 + y**2)<br>    r_hat_x = x / r<br>    r_hat_y = y / r<br><br>    factor = (u_0 / (4 * np.pi)) * (3 * (m[0] * r_hat_x + m[1] * r_hat_y))<br>    <br>    Bx = factor * r_hat_x - m[0]<br>    By = factor * r_hat_y - m[1]<br><br>    Bx /= r**3<br>    By /= r**3<br><br>    return Bx, By<br><br>#Define magnetic constant and dipole of our magnet<br>u_0 = 4*np.pi*10**-7<br>#dipole on an electron<br>m = (-9.28*10**-24,0)   <br><br>#Make our magnets<br>m1 = magnet()<br>m1.init([.1,0],m)<br><br>#Make a meshgrid of observation points<br>x = np.linspace(-.5,.5,20)<br>X,Y = np.meshgrid(x,x)<br>grid =[]<br>for i in range(0, len(X)):<br>    for j in range(0, len(Y)):<br>        grid.append([X[i][j],Y[i][j]])<br><br>#Define our needed quantities<br>observations = np.array(grid)  <br>field1 = []<br><br>#Loop through observation points<br>for n in range(0,len(observations)):<br>           <br>    x = observations[n][0] - m1.position[0]               <br>    y = observations[n][0] - m1.position[1]<br>    <br>    field1.append(dipole_dipole(u_0,m1.dipole,x,y))  <br>    <br>#Scale x and y<br>field_total = np.array(field1)<br>scale_x = .1/max(field_total[:,0])<br>scale_y = .1/max(field_total[:,1])<br>    <br>#Plot vector field<br>fig = plt.figure(figsize=(5,5))<br><br>plt.plot(m1.position[0],m1.position[1],&#39;rs&#39;)<br><br>for j in range(0, len(observations)):<br>    plt.arrow(observations[j][0],observations[j][1],scale_x*field1[j][0],scale_y*field1[j][1], head_width = .02)  <br><br>plt.title(&quot;Magnetic Field of an Electron&quot;)</pre><pre>#Make our charges<br>m1 = magnet()<br>m2 = magnet()<br>m1.init([0,.2],m)<br>m2.init([0,0],m)<br><br>#Make a meshgrid of observation points<br>x = np.linspace(-1,1,30)<br>X,Y = np.meshgrid(x,x)<br>grid =[]<br>for i in range(0, len(X)):<br>    for j in range(0, len(Y)):<br>        grid.append([X[i][j],Y[i][j]])<br><br>#Define our needed quantities<br>observations = np.array(grid)  <br>field1 = []<br>field2 = []<br>field_total = []<br><br>#Loop through observation points<br>for n in range(0,len(observations)):<br>           <br>    x1 = observations[n][0] - m1.position[0]               <br>    y1 = observations[n][0] - m1.position[1]<br>    <br>    x2 = observations[n][0] - m2.position[0]               <br>    y2 = observations[n][0] - m2.position[1]<br>    <br>    field1.append(dipole_dipole(u_0,m1.dipole,x1,y1))  <br>    field2.append(dipole_dipole(u_0,m2.dipole,x2,y2))<br>    field_total.append(field1[-1]+field2[-1])<br><br>#Scale x and y<br>field_total = np.array(field_total)<br>scale_x = .1/max(field_total[:,0])<br>scale_y = .1/max(field_total[:,1])<br>    <br>#Plot vector field<br>fig = plt.figure(figsize=(5,5))<br><br>plt.plot(m1.position[0],m1.position[1],&#39;ro&#39;, label = &quot;Positive&quot;)<br>plt.plot(m2.position[0],m2.position[1],&#39;bo&#39;, label = &quot;Negitive&quot;)<br><br>for j in range(0, len(observations)):<br>    plt.arrow(observations[j][0],observations[j][1],scale_x*field_total[j][0],scale_y*field_total[j][1], head_width = .025)  <br><br>plt.title(&quot;Magnetic Field of 2 Electrons&quot;)</pre><h3>References</h3><ol><li>All figures used in this article were either generated by the author or fall under the <a href="https://creativecommons.org/licenses/by-sa/3.0/">creative common license CC BY-SA</a> as stated by the original image creators</li><li>Introduction to Electrodynamics, 4th edition <a href="https://hansandcassady.org/David%20J.%20Griffiths-Introduction%20to%20Electrodynamics-Addison-Wesley%20(2012).pdf">https://hansandcassady.org/David%20J.%20Griffiths-Introduction%20to%20Electrodynamics-Addison-Wesley%20(2012).pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96ab3d5e7637" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/simulation-104-electromagnetic-mapping-with-vector-fields-96ab3d5e7637">Simulation 104: Electromagnetic Mapping with Vector Fields</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[Simulation 103: Monte Carlo Modeling Quantum Mechanics]]></title>
            <link>https://medium.com/@ln8378/simulation-103-monte-carlo-modeling-quantum-mechanics-22b79a0110e9?source=rss-b34fcbf59198------2</link>
            <guid isPermaLink="false">https://medium.com/p/22b79a0110e9</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[computation]]></category>
            <category><![CDATA[quantum-physics]]></category>
            <category><![CDATA[monte-carlo]]></category>
            <category><![CDATA[simulation]]></category>
            <dc:creator><![CDATA[Le Nguyen]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 12:16:44 GMT</pubDate>
            <atom:updated>2023-08-05T14:00:44.889Z</atom:updated>
            <content:encoded><![CDATA[<h4>Handling the probabilistic nature of Quantum Mechanics computationally</h4><p>Quantum Mechanics is seen as an especially ominous field of physics as it describes reality at a level we don’t perceive on a day to day basis. Not only that, the conclusions Quantum Mechanics gives us are unintuitive and seemingly bizarre. In this article, we will not only demystify some of the underlying facts of Quantum Mechanics but also develop a computational framework to simulate a keystone quantum experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8WRxY1tPMKrZRFRA-S9Xg.jpeg" /><figcaption>Figure 1: <a href="https://www.livescience.com/33816-quantum-mechanics-explanation.html">Artistic rendition</a> representing Quantum Mechanics</figcaption></figure><p>In this article we will:</p><ul><li>Learn a basic overview of Quantum Mechanics</li><li>Go over the theory behind the double slit experiment</li><li>Learn about Monte Carlo methods</li><li>Create a Monte Carlo simulation of the double slit experiment</li></ul><h3>Quantum Mechanics Overview</h3><p>Quantum Mechanics is a branch of physics that describes the behavior of matter and energy at the smallest scale, such as atoms and subatomic particles. It provides a framework for understanding the strange and counterintuitive phenomena that occur at such a fundamental level. These phenomena can not be described using classical physics which is what gives Quantum Mechanics its air of mysticism.</p><p>For instance, Quantum Mechanics introduces the concept of wave-particle duality, where particles can exhibit both wave-like and particle-like behavior depending on if they are observed. If a particle is not being observed, it does not exist as a discrete object; it exists as a region of probability where it could exist until it is observed. Once observed, it then becomes discrete somewhere in that region. This is an incredibly foreign way to think about existence since we only experience physics at a classical level but there is plenty of experimental evidence proving the quantum understanding of the world is true.</p><p>We will go over the most commonly know experiment in Quantum Mechanics and explore the theory behind it.</p><h4>The Double Slit Experiment</h4><p>The double slit experiment is by far the most well known experiment in Quantum Mechanics. It experimentally proved wave-particle duality by sending a stream of particles through a pair of slits in a sheet of metal. The particles could go through one slit or the other and land on a secondary sheet (viewing screen) where their final position could be observed.</p><p>On the first run of the experiment, a detector was placed to observe the particles before going into the slits. This way, we would know which slit each of the particles went through. The corresponding pattern of particle hits on the secondary sheet of metal lined up with the slits as expected. On the second run of the experiment, the detector was removed. This time, the particle hits did not line up with the slits; a banding pattern was observed. See figure 2 for a visual of the double slit experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*J1QTAT0ETe7QIaFasLmoaA.png" /><figcaption>Figure 2: <a href="https://link.springer.com/chapter/10.1007/978-1-4842-7246-6_1">Diagram of the double slit experiment.</a> Left is observed, right is unobserved.</figcaption></figure><p>So, why did this happen? Why did the particles land where we expected them to when observed but not when unobserved? Here is where wave-particle duality comes into play. When the particles were observed, they were discreate objects so it was like throwing balls through the slits; they would either go through one or the other. When the particles were unobserved they were not discreate objects; they were waves. Now, the particles are like ripples in water going through the slits, seen in figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*W2V2M-akFoRh6StvZkaVjA.png" /><figcaption>Figure 3: <a href="https://www.discovery.com/science/Double-Slit-Experiment">Diagram of interference pattern</a></figcaption></figure><p>When the particles act as waves, they create a banding pattern on the second metal sheet because of <a href="https://www.physicsclassroom.com/class/waves/Lesson-3/Interference-of-Waves#:~:text=Wave%20interference%20is%20the%20phenomenon,the%20particles%20of%20the%20medium.">wave interference</a>. The particles, now waves, get split into two waves as they pass through the slits. The two waves can then interact with each other and amplify each other when they line up (peak to peak) or cancel each other out when they are misaligned (peak to trough), seen in figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*Bt9x5y3WyDJhaW-dVTbNnQ.png" /><figcaption>Figure 4: <a href="https://www.physicsclassroom.com/class/waves/Lesson-3/Interference-of-Waves#:~:text=Wave%20interference%20is%20the%20phenomenon,the%20particles%20of%20the%20medium.">Wave addition and cancelation</a></figcaption></figure><p>The peaks of the combined wave become become the regions of highest probability for the particle to exist once it hits the second metal sheet. Conversely, the particle can not exist where the waves have canceled out. This is what creates the banding pattern on the second metal sheet. The bands line up with the peaks in the combined wave and the gaps line up with the areas of cancelation.</p><p>We will circle back to some of the theory behind the double slit experiment later on in this article, but we understand enough Quantum Mechanics to know that the behavior of quantum systems is probabilistic. In order to simulate probabilistic systems, we will need Monte Carlo methods; which will be explored in the next section.</p><h3>Monte Carlo Methods</h3><p>Monte Carlo methods, named after the Casino de Monte-Carlo in Monaco, are a set of computational methods that use randomness and selectivity to get results. Monte Carlo methods are used when a deterministic answer does not exist or is unfeasible to obtain. These methods are remarkably simple as they only require the rolling of random numbers and then checking the roll against some criteria, but they are incredibly powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gu2o1rgBuNK9DfUIR2Zv8g.jpeg" /><figcaption>Figure 5: <a href="https://www.montecarlosbm.com/en/casino-monaco/casino-monte-carlo">Casino de Monte-Carlo</a></figcaption></figure><p>We will go over a use case of Monte Carlo methods before using them to simulate a quantum system.</p><h4>Estimating Pi</h4><p>We can see the power of Monte Carlo methods with a simple estimation of pi. Here we will run a simulation where we throw darts at a board (place random points). The board will be a circle inside of a square (seen in figure 6) and we will keep track of darts that land inside of the circle as well as the total amount of darts throw.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*G2Y89I5_3w70KUgV_Vn-xg.png" /><figcaption>Figure 6: Simulation board</figcaption></figure><p>That’s it, that’s the simulation and everything we need to estimate the value of pi. We can do this by looking at the relationship between the area of our circle and our square on the board seen below in equation 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*SjpYMn29iArl6bEyoW98PA.png" /><figcaption>Equation 1: Relationship between circle and square area</figcaption></figure><p>As we can see, the value of pi is equal to four times the ratio between the area of the circle and square. This ratio between areas can be approximated by the ratio of darts that land in the circle vs the number that land in the square. In our set up, the square is the total area of our board so we can look at the number of darts that land in the circle vs the total number of darts. We run the simulation in figure 7 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IK5lHuwEm5P3GoK2od3tEw.gif" /><figcaption>Figure 7: Monte Carlo Estimation of Pi</figcaption></figure><p>In our simulation, as the number of darts increase, the accuracy of our pi estimation increases in kind. This is just a simple example of how randomness and selectivity can be used to get real results. The code snippet to run this simulation is given below.</p><pre>import random<br><br>def monteCarloPi(numSamples):<br>    dartsInCircle = 0<br>    #Throw random darts<br>    for i in range(numSamples):<br>        x = random.uniform(0, 1)<br>        y = random.uniform(0, 1)<br>        #Check if darts land in circle<br>        if (x**2 + y**2) &lt;= 1:<br>            dartsInCircle += 1<br>    estimate = 4 * dartsInCircle / (numSamples * 1.0)<br>    return estimate<br><br># Example usage:<br>print(monteCarloPi(10000))</pre><p>Now that we understand what Monte Carlo methods are and how to use them, we will build a simulation of the double slit experiment.</p><h3>Monte Carlo Quantum Simulation</h3><p>We will now use the power of Monte Carlo methods to handle the probabilistic nature of Quantum Mechanics. We will take the last two sections of this article and combine them to make a Monte Carlo simulation of the double slit experiment. We first need to define the probability function for a particle existing somewhere on the viewing screen.</p><h4>Fraunhofer Diffraction Equation</h4><p>For the sake of brevity, we will not go over the <a href="https://en.wikipedia.org/wiki/Fraunhofer_diffraction">full derivation</a> of the Fraunhofer diffraction equation in this article. We only need to accept it as our probability function in our simulation. In short, the equation takes into account the double slit layout as well as some properties of the particle to find a probability distribution of where our given particle could exist on the second metal sheet. An example of this function is given in figure 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*SnN6SjqIFv0fJ2bvDPq1BQ.png" /><figcaption>Equation 2: Fraunhofer diffraction equation. Note that<a href="https://en.wikipedia.org/wiki/Near_and_far_field"> near field approximations</a> will be made when implementing it into code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*zUQxuFjfC-iBrdWeubcv-Q.png" /><figcaption>Figure 8: <a href="https://physics.stackexchange.com/questions/254064/double-slit-intensity-distribution-for-particles">Intensity pattern (probability function) for the double-slit experiment from the Fraunhofer diffraction equation</a></figcaption></figure><h4>Simulation</h4><p>We first need to write the Fraunhofer Diffraction Equation into code so we can calculate the probability of particle being at a given location.</p><pre>#Parameters used<br>#m = Particle mass in kg<br>#v = Particle velocity in m/s                   <br><br>#lamb = h/(m*v) de broglie wavelength, scaled to be used in this modeled, h = 6.62 × 10^−34 Js. <br>#a = Slit width in meters<br>#d = Distance between slits in meters<br>#l = Distance to screen in meters<br><br>def Diffraction(a,d,lamb,l,x):<br>    <br>    #Calculating some constants<br>    c = (np.pi*d)/(lamb*l)<br>    k = (np.pi*a)/(lamb*l)<br>    <br>    #Probability function<br>    probability = ((np.cos(c))**2)*(((np.sin(k*x))/(k*x))**2)<br>    <br>    return probability</pre><p>Next we write a function to perform a Monte Carlo roll against our probability function. We first select a random location on the second metal sheet viewing screen. Then we find the probability of the particle existing at that location by evaluating our diffraction equation at that location. Finally, we roll a random number against our probability and if our probability at that location is higher than the random number we accept that location and say a particle exists there.</p><p>This Monte Carlo rolling is essentially a sampling from our probability function to estimate the behavior of the probabilistic system. Each roll represents a possible particle going through the slits and manifesting at some location on the viewing screen.</p><pre>def MonteCarlo(a,d,lamb,l):<br>    <br>    #Monte carlo throw for a particle at a given position on our viewing screen<br>    x = np.random.uniform(-.001,.001) #between -1mm and 1 mm<br>    <br>    p = Diffraction(a,d,lamb,l,x)<br>    rand = np.random.uniform(0,1)<br>    <br>    if (p &gt;= rand):<br>        return x</pre><p>With our probability function and Monte Carlo roll we can now run our simulation by continuously rolling and recording our results. We are using a feasible set of experimental parameters but they can be changed (may need to change the position roll in the above function if we do).</p><pre>#Parameters of our system<br>m= 9.1*10**-31 #Mass of electron<br>v= 5*10**5 #velocity                     <br><br>lamb = 6.62*10**-34/(m*v) #de broglie wavelength. <br>a = 150*10**-6 #Slit width<br>d = 600*10**-6 #Distance between slits<br>l = 10 #Distance to screen<br><br>#The loop that runs the monte carlo to generate the interferance pattern<br>numParticles = 10**6<br>particles = []<br>for i in range(numParticles):<br>    #Rolling a random y value as well to give our bands vertical spread<br>    y = np.random.uniform(0,1)<br>    <br>    x = MonteCarlo(a,d,lamb,l)<br>    <br>    if x != None:<br>        particles.append([x,y])</pre><p>After running our simulation, we can run the following code snippet to visualize the results seen in figure 9 and compare then to a real interference pattern in figure 10.</p><pre>#Visualize of the interferance pattern <br>particles = np.array(particles)<br>plt.figure(figsize = (20,6))<br>plt.scatter(particles[:,0],particles[:,1])<br>plt.title(&quot;Double Slit Interferance Pattern&quot;)<br>plt.xlabel(&quot;X position&quot;)<br>plt.ylabel(&quot;Y position&quot;)<br>plt.show() <br><br>plt.figure(figsize = (12,6))<br><br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*xpIXBevnQle1G-ECAEeJpg.png" /><figcaption>Figure 9: Simulated interference pattern</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*WHSjx3fEnuQUW1vK1ipJbQ.png" /><figcaption>Figure 10: <a href="https://www.youtube.com/watch?v=nuaHY5lj2AA">Real interference pattern</a></figcaption></figure><p>That looks like a realistic interference pattern! The intensity or clustering of points in our simulation matches what we would observe if we were to actually run the double slit experiment. As another check to our results, we can check the distribution of our points against the theoretical probability. We should expect our simulated distribution to follow the theory since we knew the theoretical distribution beforehand and used it.</p><p>It is important to note that in broader cases outside of this article we may not have a probability distribution to work with which is what makes Monte Carlo methods so powerful. Even with an unknown or partially know probability distribution Monte Carlo methods can be used to simulate and sample because they only need a single criterion to roll against. This criterion could come from real data or on the spot calculation when mapping out the entire probability distribution is infeasible.</p><pre>#Showing that the generated model fits the theoretical model.<br>plt.figure(figsize = (20,6))<br>weights = np.ones_like(particles[:,0])/float(len(particles[:,0]))<br>plt.hist(particles[:,0], bins = 75,  weights=weights)#density = True)<br><br>x = np.linspace(-.001,.001,500)<br>plt.plot(x,Diffraction(a,d,lamb,l,x)) #max(p) is there to normalize the function.<br>plt.title(&quot;Theoretical Model Over the Generated Distribution&quot;,fontsize = 16)<br>plt.ylabel(&quot;Probability&quot;,fontsize = 16)<br>plt.xlabel(&quot;X position&quot;,fontsize = 16)<br>plt.xticks(fontsize = 12)<br>plt.yticks(fontsize = 12)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*zJBgSWYrsBW-fEKjgP6fhw.png" /><figcaption>Figure 11: Theoretical probability against the simulated distribution</figcaption></figure><h3>Conclusion</h3><p>In this article, we went over some basic theory of quantum mechanics and the double slit experiment. Additionally, we covered Monte Carlo methods and how to use them to simulate a quantum system. Though our simulation was basic, it shows off all of the tools required to dive deeper into quantum simulation; which we will do in future articles.</p><h3>Full Code</h3><pre>import numpy as np<br>import matplotlib.pyplot as plt<br><br>#Parameters used<br>#m = Particle mass in kg<br>#v = Particle velocity in m/s                   <br><br>#lamb = h/(m*v) &quot;de broglie wavelength&quot;, scaled to be used in this modeled, h = 6.62 × 10^−34 Js. <br>#a = Slit width in meters<br>#d = Distance between slits in meters<br>#l = Distance to screen in meters<br><br>def Diffraction(a,d,lamb,l,x):<br>    <br>    #Calculating some constants<br>    c = (np.pi*d)/(lamb*l)<br>    k = (np.pi*a)/(lamb*l)<br>    <br>    #Probability function<br>    probability = ((np.cos(c))**2)*(((np.sin(k*x))/(k*x))**2)<br>    <br>    return probability<br><br>def MonteCarlo(a,d,lamb,l):<br>    <br>    #Monte carlo throw for a particle at a given position on our viewing screen<br>    x = np.random.uniform(-.001,.001)<br>    <br>    p = Diffraction(a,d,lamb,l,x)<br>    rand = np.random.uniform(0,1)<br>    <br>    if (p &gt;= rand):<br>        return x<br><br>#Parameters of our system<br>m= 9.1*10**-31 #Mass of electron<br>v= 5*10**5 #velocity                     <br><br>lamb = 6.62*10**-34/(m*v) #de broglie wavelength, scaled to be used in this modeled, h = 1. <br>a = 150*10**-6 #Slit width<br>d = 600*10**-6 #Distance between slits<br>l = 10 #Distance to screen<br><br>#The loop that runs the monte carlo to generate the interferance pattern<br>numParticles = 10**6<br>particles = []<br>for i in range(numParticles):<br>    #Rolling a random y value as well to give our bands vertical spread<br>    y = np.random.uniform(0,1)<br>    <br>    x = MonteCarlo(a,d,lamb,l)<br>    <br>    if x != None:<br>        particles.append([x,y])<br><br>#Visualize of the interferance pattern <br>particles = np.array(particles)<br>plt.figure(figsize = (20,6))<br>plt.scatter(particles[:,0],particles[:,1])<br>plt.title(&quot;Double Slit Interferance Pattern&quot;, fontsize = 16)<br>plt.xlabel(&quot;X position&quot;, fontsize = 16)<br>plt.ylabel(&quot;Y position&quot;, fontsize = 16)<br>plt.xticks(fontsize = 12)<br>plt.yticks(fontsize = 12)<br><br>#plt.show() <br><br>plt.figure(figsize = (12,6))<br><br>plt.tight_layout()<br>plt.show()<br><br>#Showing that the generated model fits the theoretical model.<br>plt.figure(figsize = (20,6))<br>weights = np.ones_like(particles[:,0])/float(len(particles[:,0]))<br>plt.hist(particles[:,0], bins = 75,  weights=weights)#density = True)<br><br>x = np.linspace(-.001,.001,500)<br>plt.plot(x,Diffraction(a,d,lamb,l,x)) #max(p) is there to normalize the function.<br>plt.title(&quot;Theoretical Model Over the Generated Distribution&quot;,fontsize = 16)<br>plt.ylabel(&quot;Probability&quot;,fontsize = 16)<br>plt.xlabel(&quot;X position&quot;,fontsize = 16)<br>plt.xticks(fontsize = 12)<br>plt.yticks(fontsize = 12)<br>plt.show()</pre><h3>References</h3><ul><li><a href="https://www.livescience.com/33816-quantum-mechanics-explanation.html">What Is Quantum Mechanics?</a></li><li><a href="https://link.springer.com/chapter/10.1007/978-1-4842-7246-6_1">What, Why, and How?</a></li><li><a href="https://www.discovery.com/science/Double-Slit-Experiment">The Double-Slit Experiment Cracked Reality Wide Open</a></li></ul><p>Young’s Double Slit Demonstration Video: <a href="https://www.youtube.com/watch?v=nuaHY5lj2AA">https://www.youtube.com/watch?v=nuaHY5lj2AA</a></p><p>Any figures not cited where created by the author</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22b79a0110e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulation 102: Agent-Based Disease Modeling]]></title>
            <link>https://medium.com/@ln8378/simulation-102-agent-based-disease-modeling-17307f2de2f3?source=rss-b34fcbf59198------2</link>
            <guid isPermaLink="false">https://medium.com/p/17307f2de2f3</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[agent-based-modeling]]></category>
            <category><![CDATA[epidemiology]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[simulation]]></category>
            <dc:creator><![CDATA[Le Nguyen]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 01:02:43 GMT</pubDate>
            <atom:updated>2023-08-04T12:13:51.736Z</atom:updated>
            <content:encoded><![CDATA[<h4>Modeling how disease spreads from person to person</h4><p>The Covid era has given all of us a lesson in how disease spreads. We know the basics: some people are infected and spread the disease to others until they recover. Our everyday experience is a good start point to understand disease spread, but here we will formalize our understanding as well as build a computational framework to simulate it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*VqeDYJ9OEfPd6Q-bPbDOuA.jpeg" /><figcaption>Figure 1: Pandemic effect map</figcaption></figure><p>In this article we will:</p><ul><li>Learn about agent-based models</li><li>Learn the basic theory of disease spread</li><li>Implement an agent-based model using classes</li><li>Simulate disease spread with agents</li></ul><h3>Agent-Based Models</h3><p><a href="https://en.wikipedia.org/wiki/Agent-based_model">Agent-Based Models</a> are models that focus on simulating individuals and their interactions. This is a fundamentally different approach to grid based simulation seen in our <a href="https://medium.com/@ln8378/simulation-101-conductive-heat-transfer-a4f09b3e16b4">last article</a>. In an agent-based model, a given number of individual agents are created and given certain properties. As the simulation evolves we see how the agents interact with each other and how that changes the properties of each agent.</p><p>In our case of simulating disease spread each agent will be a person in our simulation. We will keep track of the position of each person and whether or not they are infected. Our agents are simple, the only properties they have are location and infection status, but even with simple agents we can make powerful tools.</p><p>With our agents, we need to define their interactions and how those interactions change their properties. We need to check the distance between our agents and if they are close to an infected agent. If an uninfected agent is close to an infected one we will let the disease transfer and change the uninfected agents status to infected. We iterate this process as our agents move around and that gives us everything we need to build our simulation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ywNjHXRtkAneQLbSl02k-g.jpeg" /><figcaption>Figure 2: Representation of agents in a disease spread model.</figcaption></figure><p>Before going into simulation building, we will overview the theory behind disease spread.</p><h3>Theory of Disease Spread</h3><p>Mathematically, the spread of disease can be modeled with the <a href="https://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model">SIR model</a>, which stands for <strong>S</strong>usceptible, <strong>I</strong>nfectious, <strong>R</strong>ecovered. The model is a set of differential equations that keep track of the number of people who are susceptible to being infected, actively infectious and have recovered from previously been infected. The governing set of equations and a plot of their output is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*7UuqCULcUXLN2iptwReZZQ.png" /><figcaption>Figure 3: Equations and plot of SIR model.</figcaption></figure><p>We can see these equations calculate the change in the susceptible, infected, and recovered population in respect to time. Here, model parameters β and<strong> </strong>γ are the infection rate and recovery rate. We can understand the differential equations from their line plot. The susceptible population (blue line) decreases as more people get infected until all of the population has been infected. Conversely, the infected population (red line) increases as the susceptible population decreases (get infected) but the infected population will decrease as people start to recover (black line).</p><p>This gives the infected population the skewed hump because it is controlled by how many people are infected vs how many people are recovered. At first no one in the infected population has had the time to recover, so it shoots up, but over time they will start to recover and there will be less and less susceptible population to infect because they have already been infected; thus the infected population tapers off.</p><p>With the general theory of disease spread in mind, we can get into the modeling.</p><h3><strong>Class Implementation</strong></h3><p>Classes are the ideal data object to create an agent-based model. A <a href="https://docs.python.org/3/tutorial/classes.html">class is a templet to store values and methods that can easily be replicated</a>. In our case, we will use classes to create our agents since classes allow us to create data structures that store the same kind of information over and over again.</p><p>The following subsections will detail how to create a class that represents our agents as well as outside functions to model their interactions. A lot of code is shown below but much of it is the same or similar code with an added feature onto it. By the end we will have a fully functioning model to simulate the spread of disease.</p><h4>Initialize Agents</h4><p>In our first snippet of code we will create our agent class and give all of our agents an x and y coordinate. Additionally, we create a utility function that will retrieve the positions of all of agents. All we need to do is create as many agents as we want in a loop and then plot where they are seen in figure 4.</p><pre>#Agent class<br>class Agent():<br>    def __init__(self,x,y):<br>        self.x = x<br>        self.y = y<br><br>def getPosition(agents):<br>    positions = []<br><br>    for agent in agents:<br>        positions.append([agent.x,agent.y])<br><br>    return np.array(positions)<br><br>#Make Agents<br>agents = []<br>for i in range(0,100):<br>    x = np.random.uniform(0,100)<br>    y = np.random.uniform(0,100)<br>    agents.append(Agent(x,y))<br><br>#Get agent positions<br>positions = getPosition(agents)<br><br>#Plot Agents<br>plt.figure(figsize=(6,6))<br>plt.scatter(positions[:,0] , positions[:,1])<br>plt.tick_params(left = False, right = False , labelleft = False,labelbottom = False, bottom = False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*hAuL4fXo7xgUYO5-JYEzmQ.png" /><figcaption>Figure 4: Initial position of all Agents.</figcaption></figure><h4>Add Movement</h4><p>Next, we add a movement function to our agents which will make them move around the environment randomly. Here we need to address our boundary conditions as well (what our agents do when they get to the edge of our simulation); we simply check to see if they are trying to move past the boundary and set them at the boundary for that movement step. We make another utility function that will go through all of our agents and have them move one step and then we call that function for our desired number of steps. We can see our agents moving in figure 5.</p><pre>#Agent Class<br>class Agent():<br>    def __init__(self,x,y):<br>        #initalize position<br>        self.x = x<br>        self.y = y<br>        <br>    def movement(self,stepSize,xBounds,yBounds):<br>        #step<br>        self.x += stepSize*np.random.uniform(-1,1)<br>        self.y += stepSize*np.random.uniform(-1,1)<br>        <br>        #check boundaries<br>        if self.x &lt; xBounds[0]:<br>            self.x = xBounds[0]<br>        elif self.x &gt; xBounds[1]:<br>            self.x = xBounds[1]<br>        <br>        if self.y &lt; yBounds[0]:<br>            self.y = yBounds[0]<br>        elif self.y &gt; yBounds[1]:<br>            self.y = yBounds[1]<br><br>&quot;&quot;&quot;<br>Previous functions<br>&quot;&quot;&quot;<br><br>def moveAgents(agents,stepSize,xBounds,yBounds):<br>    for i in range(0,len(agents)):<br>        agents[i].movement(stepSize,xBounds,yBounds)<br>        <br>    return agents<br><br>#Make Agents<br>agents = []<br>for i in range(0,100):<br>    x = np.random.uniform(0,100)<br>    y = np.random.uniform(0,100)<br>    agents.append(Agent(x,y))<br><br>#Move Agents<br>stepSize = 1<br>xBounds = [0,100]<br>yBounds = [0,100]<br><br>frames = []<br>for i in range(0,200):<br>    <br>    agents = moveAgents(agents,stepSize,xBounds,yBounds)<br>    positions = getPosition(agents)<br>    frames.append([positions[:,0] , positions[:,1]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*7CBNLflKzHNIL74fQXjrWQ.gif" /><figcaption>Figure 5: Gif of moving agents.</figcaption></figure><h4>Add Infect Status</h4><p>Since we are modeling the spread of disease, we need to add an infected status to our agents and write a utility function that will record the status of each of our agents. Figure 6 shows a mix of infected (red) and healthy agents (green) initialized in our model.</p><pre>#Agent Class<br>class Agent():<br>    def __init__(self,x,y,infected):<br>        #initalize position<br>        self.x = x<br>        self.y = y<br>        self.infected = infected<br>    &quot;&quot;&quot;<br>    Movement function<br>    &quot;&quot;&quot;<br>&quot;&quot;&quot;<br>Previous functions<br>&quot;&quot;&quot;<br><br>def getInfected(agents):<br>    infected  = []<br>    for agent in agents:<br>        infected.append(agent.infected)<br>    return infected<br>#Make Agents<br>agents = []<br>for i in range(0,100):<br>    x = np.random.uniform(0,100)<br>    y = np.random.uniform(0,100)<br>    agents.append(Agent(x,y,np.random.randint(0,2)))<br>#Get positions and infected status<br>positions = getPosition(agents)<br>infected = getInfected(agents)<br>#plot agents<br>plt.figure(figsize=(6,6))<br>plt.scatter(positions[:,0] , positions[:,1], c = infected, cmap = &quot;RdYlGn_r&quot;)<br>plt.tick_params(left = False, right = False , labelleft = False,labelbottom = False, bottom = False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*QTXXngExUTaUsQzmOpX0VQ.png" /><figcaption>Figure 6: Mix of healthy and infected agents.</figcaption></figure><h4>Add Disease spread</h4><p>With our agents having an infected status, we have to be able to spread the infection. Every agent now gets a resistance and an infect function which will be used every time a healthy agent contacts an infected agent. The infect function rolls a random number and if that number is greater than the agents resistance, the agent will become infected. This allows us to play with difference resistance values in our population, say some agents are masked or vaccinated and we want to study the effects.</p><p>We need a couple new utility functions as well to make our agents spread disease. The first function we need is a function to find all agents who are close to one another to see which agents are at risked of being infected. This method calculates a <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance_matrix.html">distance matrix</a> that contains the pair-wise distance for all agents in our simulation. We can then look at any agents that are close to each other (set at a distance threshold of our choice) and see if infection can spread. The roll infect function does this for us by using the infect function on all agents close to an infected agent if they are healthy. We can see the spread of disease from agent to agent in figure 7.</p><pre>#Agent Class<br>class Agent():<br>    def __init__(self,x,y,infected,resistance):<br>        #initalize position<br>        self.x = x<br>        self.y = y<br>        self.infected = infected<br>        self.resistance = resistance<br>    &quot;&quot;&quot;<br>    Movement function<br>    &quot;&quot;&quot;<br>    def infect(self):<br>        infectRoll = np.random.uniform()<br>        <br>        if self.infected == False and infectRoll &gt; self.resistance:<br>            self.infected = True<br>&quot;&quot;&quot;<br>Previous functions<br>&quot;&quot;&quot;<br>#Check if any agents are within infecting distance<br>def getCloseAgents(distanceMatrix,agentNumber):<br>    sort = np.argsort(distanceMatrix[agentNumber])<br>    closeMask = distanceMatrix[agentNumber][sort] &lt; 5<br>    closeAgents = np.argsort(distanceMatrix[agentNumber])[closeMask][1:]<br>    return closeAgents<br><br>#Go through close agents and roll to see if they get infected<br>def rollInfect(agents):<br>    positions = getPosition(agents)<br>    distanceMatrix = distance_matrix(positions,positions)<br>    <br>    for i in range(0,len(agents)):<br>        closeAgents = getCloseAgents(distanceMatrix,i)<br>        for j in closeAgents:<br>            if agents[j].infected == True:<br>                agents[i].infect()<br>    return agents<br><br>#Make agents<br>agents = []<br>for i in range(0,100):<br>    x = np.random.uniform(0,100)<br>    y = np.random.uniform(0,100)<br>    agents.append(Agent(x,y,0,.5))<br> <br>for i in range(0,3):<br>    agents[i].infected = True<br>#Seed a few agents with infection<br>stepSize = 1<br>xBounds = [0,100]<br>yBounds = [0,100]<br>#Move Agents<br>frames = []<br>for i in range(0,200):<br>    agents = moveAgents(agents,stepSize,xBounds,yBounds)<br>    agents = rollInfect(agents)<br>    positions = getPosition(agents)<br>    infected = getInfected(agents)<br>    frames.append([positions[:,0] , positions[:,1], infected])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*HSeBytScXl4Eko4YLu6Erg.gif" /><figcaption>Figure 7: Infection spreading among agents.</figcaption></figure><h4>Add Recovery (Final Full Agent)</h4><p>To complete our agents to run a full SIR style simulation we need our agents to be able to recover from infection. To do this, we add an infected counter to the agent. When a agent is infected the counter is set at some value and every time step the counter start ticks down. Once the counter gets to zero the agent becomes healthy again. We can also change the resistance value after recovery so agents that have once been infected have less of a chance to be reinfected. Our fully implemented agents can be seen in figure 8.</p><pre>#Agent Class<br>class Agent():<br>    def __init__(self,x,y,infected,resistance,infectedCounter = 0):<br>        #initalize position<br>        self.x = x<br>        self.y = y<br>        self.infected = infected<br>        self.resistance = resistance<br>        self.infectedCounter = infectedCounter <br>        <br>    def movement(self,stepSize,xBounds,yBounds):<br>        #step<br>        self.x += stepSize*np.random.uniform(-1,1)<br>        self.y += stepSize*np.random.uniform(-1,1)<br>        <br>        #check boundaries<br>        if self.x &lt; xBounds[0]:<br>            self.x = xBounds[0]<br>        elif self.x &gt; xBounds[1]:<br>            self.x = xBounds[1]<br>        <br>        if self.y &lt; yBounds[0]:<br>            self.y = yBounds[0]<br>        elif self.y &gt; yBounds[1]:<br>            self.y = yBounds[1]<br>            <br>        #Tick down infeced counter<br>        if self.infected == True:<br>            self.infectedCounter -= 1<br>            if self.infectedCounter &lt;= 0:<br>                self.infected = False<br>        <br>    def infect(self):<br>        infectRoll = np.random.uniform()<br>        <br>        if self.infected == False and infectRoll &gt; self.resistance:<br>            self.infected = True<br>            self.infectedCounter = 50<br>            self.resistance *= 1.5<br>&quot;&quot;&quot;<br>Previous functions<br>&quot;&quot;&quot;<br><br>#Make Agents<br>agents = []<br>for i in range(0,100):<br>    x = np.random.uniform(0,100)<br>    y = np.random.uniform(0,100)<br>    agents.append(Agent(x,y,0,.5))<br>#Seed infected<br>for i in range(0,3):<br>    agents[i].infected = 1<br>    agents[i].infectedCounter = 50<br>#Move Agents<br>stepSize = 1<br>xBounds = [0,100]<br>yBounds = [0,100]<br><br>frames = []<br>for i in range(0,200):<br>    agents = moveAgents(agents,stepSize,xBounds,yBounds)<br>    agents = rollInfect(agents)<br>    positions = getPosition(agents)<br>    infected = getInfected(agents)<br>    frames.append([positions[:,0] , positions[:,1], infected])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*oERYYQ7ubWBpSlWm_ETw4Q.gif" /><figcaption>Figure 8: Full agents that implement the SIR model.</figcaption></figure><p>Our agents now have all the properties and functionality to run a simulation which we will do in the final section.</p><h3>Simulation</h3><p>We see our full simulation play out in figure 9. The simulation parameters are the following: 500 agents, 10 infected, uniform 30% resistance to infection, agents can infect those who are within 10 steps of them and they stay infected for 50 time steps with the entire simulation being 500 time steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5Qt4FpcIRNQI2TCNu8t8Dg.gif" /><figcaption>Figure 9: Full simulation</figcaption></figure><p>Keeping track of the number of infected agents over time we get the following curve seen in figure 10. As we can see, this curve fits well to the expected theoretical infected curve seen in figure 3 which proves we have constructed a valid model. We have also create a malleable model that can have its parameters changed to study many scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6hCa_UQp8zb74BPJYV7z7A.png" /><figcaption>Figure 10: Infection cure.</figcaption></figure><h3><strong>Full Code</strong></h3><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import imageio<br>from scipy.spatial import distance_matrix<br><br>class Agent():<br>    def __init__(self,x,y,infected,resistance,infectedCounter = 0):<br>        #initalize position<br>        self.x = x<br>        self.y = y<br>        self.infected = infected<br>        self.resistance = resistance<br>        self.infectedCounter = infectedCounter <br>        <br>    def movement(self,stepSize,xBounds,yBounds):<br>        #step<br>        self.x += stepSize*np.random.uniform(-1,1)<br>        self.y += stepSize*np.random.uniform(-1,1)<br>        <br>        #check boundaries<br>        if self.x &lt; xBounds[0]:<br>            self.x = xBounds[0]<br>        elif self.x &gt; xBounds[1]:<br>            self.x = xBounds[1]<br>        <br>        if self.y &lt; yBounds[0]:<br>            self.y = yBounds[0]<br>        elif self.y &gt; yBounds[1]:<br>            self.y = yBounds[1]<br>            <br>        #Tick down infeced counter<br>        if self.infected == True:<br>            self.infectedCounter -= 1<br>            if self.infectedCounter &lt;= 0:<br>                self.infected = False<br>        <br>    def infect(self):<br>        infectRoll = np.random.uniform()<br>        <br>        if self.infected == False and infectRoll &gt; self.resistance:<br>            self.infected = True<br>            self.infectedCounter = 50<br>            self.resistance *= 1.5<br><br>def getPosition(agents):<br>    positions = []<br>    for agent in agents:<br>        positions.append([agent.x,agent.y])<br>    positions = np.array(positions)<br>    return positions<br><br>def moveAgents(agents,stepSize,xBounds,yBounds):<br>    for i in range(0,len(agents)):<br>        agents[i].movement(stepSize,xBounds,yBounds)<br>    return agents<br><br>def getInfected(agents):<br>    infected  = []<br>    for agent in agents:<br>        infected.append(agent.infected)<br>    return infected<br><br>def getCloseAgents(distanceMatrix,agentNumber):<br>    sort = np.argsort(distanceMatrix[agentNumber])<br>    closeMask = distanceMatrix[agentNumber][sort] &lt; 10<br>    closeAgents = np.argsort(distanceMatrix[agentNumber])[closeMask][1:]<br>    return closeAgents<br><br>def rollInfect(agents):<br>    positions = getPosition(agents)<br>    distanceMatrix = distance_matrix(positions,positions)<br>    for i in range(0,len(agents)):<br>        closeAgents = getCloseAgents(distanceMatrix,i)<br>        for j in closeAgents:<br>            if agents[j].infected == True:<br>                agents[i].infect()<br>    return agents<br><br>def makeGif(frames,name):<br>    !mkdir frames<br>    <br>    counter=0<br>    images = []<br>    for i in range(0,len(frames)):<br>        plt.figure(figsize = (6,6))<br>        plt.scatter(frames[i][0],frames[i][1], c = frames[i][2], cmap = &quot;RdYlGn_r&quot;)<br>        plt.title(&quot;Infected = &quot; + str(np.sum(frames[i][2])))<br>        plt.tick_params(left = False, right = False , labelleft = False,labelbottom = False, bottom = False)<br>        plt.savefig(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;)<br>        images.append(imageio.imread(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;))<br>        counter += 1<br>        plt.close()<br>        <br>    imageio.mimsave(name, images)<br>        <br>    !rm -r frames<br><br>agents = []<br>for i in range(0,500):<br>    x = np.random.uniform(0,500)<br>    y = np.random.uniform(0,500)<br>    agents.append(Agent(x,y,0,.3))<br>    <br>for i in range(0,10):<br>    agents[i].infected = 1<br>    agents[i].infectedCounter = 50<br>    <br>stepSize = 5<br>xBounds = [0,500]<br>yBounds = [0,500]<br><br>frames = []<br>for i in range(0,500):<br>    agents = moveAgents(agents,stepSize,xBounds,yBounds)<br>    agents = rollInfect(agents)<br>    positions = getPosition(agents)<br>    infected = getInfected(agents)<br>    frames.append([positions[:,0] , positions[:,1], infected])<br>    <br>makeGif(frames,&quot;Simulation.gif&quot;)</pre><h3>References</h3><p>[1] Modeling Disease Spread BioInteractive <a href="https://www.biointeractive.org/classroom-resources/modeling-disease-spread">https://www.biointeractive.org/classroom-resources/modeling-disease-spread</a></p><p>[2] The SIR Model for Spread of Disease <a href="https://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model">https://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model</a></p><p>[3] SIR Model Schematic Representation <a href="https://www.researchgate.net/figure/SIR-model-Schematic-representation-differential-equations-and-plot-for-the-basic-SIR_fig1_47676805">https://www.researchgate.net/figure/SIR-model-Schematic-representation-differential-equations-and-plot-for-the-basic-SIR_fig1_47676805</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17307f2de2f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulation 101: Conductive Heat Transfer]]></title>
            <link>https://medium.com/data-science/simulation-101-conductive-heat-transfer-a4f09b3e16b4?source=rss-b34fcbf59198------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4f09b3e16b4</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[computation]]></category>
            <category><![CDATA[simulation]]></category>
            <dc:creator><![CDATA[Le Nguyen]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 01:56:17 GMT</pubDate>
            <atom:updated>2023-08-05T14:13:09.266Z</atom:updated>
            <content:encoded><![CDATA[<h4>A gentle introduction to computational physics</h4><p>Conduction, or heat transfer between objects, is something we experience everyday. Putting a pan on the stove or sitting on a hot park bench gives us an intuitive sense of conductive heat transfer but here we will formalize the process and build a basic computational framework to simulate it. Conduction is an excellent first simulation problem to tackle because it uses the basic tools found in many computational physics problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*QuoqFXtUw81jcwKaeXL8Vw.gif" /></figure><p>In this article we will:</p><ul><li>Create a mesh grid to represent materials</li><li>Learn basic heat transfer equations and their computational equivalents</li><li>Update the values in our mesh grid based on the underlying physics</li><li>Simulate conductive heat transfer</li></ul><h3>Creating a Mesh Grid</h3><p>A mesh grid is a computational tool used to discretize a continuous space. That is, we can’t perform calculations on all time and space in our problem, so we chose a representative subset of points, usually at regular intervals, to look at instead.</p><p>In figure 1 below we can see an example of a mesh grid. Here a space is subdivided into evenly spaced cells which is common practice is physics simulation. Instead of running calculations/simulation on the entire surface we can now work with only our grid points which makes our problem more feasible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*pSWMxJzKC3PiN4xs.png" /><figcaption>Figure 1: <a href="https://www.javatpoint.com/numpy-meshgrid">Example of a mesh grid</a>. In a simulation we break up our space into such a grid and compute values at every dotted grid point.</figcaption></figure><p>The mesh grid above was created using Python’s <a href="https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html">numpy meshgrid</a> function which can take in a set of 1 dimensional arrays and create a mesh grid for us. For our simulation, we want to model a 2 dimensional surface, so we are going to generate 2 arrays filled with the starting values we want with a length of how many intervals we want to evaluate our simulation on. See the code snippet below where we create a 100x100 mesh grid of zeros as the basis of our simulation.</p><pre>import numpy as np<br><br>#Define how many intervals we want per axis<br>resolution = 100<br><br>#Create x and Y arrays of zeros of length 100<br>x = np.zeros(resolution)<br>y = np.zeros(resolution)<br><br>#Create a mesh grid from above arrays. Outputs are all x and Y values in grid<br>gridX, gridY = np.meshgrid(x,y)</pre><p>Before moving on from mesh grids, it’s important to note that every point on our grid is typically not a single value. Usually at every grid point we want an array of values that represent the properties we will be working with. In our heat transfer simulation we will need to know material properties as well as the temperature at every point on our mesh grid. So all the points on our grid will be an array that contains information like temperature, material density, material conductivity and anything else we need to know.</p><p>An easy way to make a mesh grid that is an array of arrays is to create multiple mesh grids that contain a single value at each point and then stack then together as seen in figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*RnwEm_ssMq6aaw3pM_xjSA.png" /><figcaption>Figure 2: Stacking 2 mesh grids to create a new mesh grid that contain multiple values per point.</figcaption></figure><p>Numpy comes in handy here again with the <a href="https://numpy.org/doc/stable/reference/generated/numpy.dstack.html">dstack function</a> which will stack two arrays element wise for us. Below is a code snippet that will create 2 mesh grids and stack them.</p><pre>import numpy as np<br><br>#Define how many intervals we want per axis<br>resolution = 100<br><br>#Create x and Y arrays of zeros of length 100<br>x1 = np.zeros(resolution)<br>y1 = np.zeros(resolution)<br><br>x2 = np.full(resolution, 1)<br>y2 = np.full(resolution, 1)<br><br>#Create a mesh grids from above arrays. Outputs are all x and Y values in grid<br>gridX, gridY = np.meshgrid(x1,y1)<br>gridX2, gridY2 = np.meshgrid(x2,y2)<br><br>#Stack both of the mesh grids we have created so every element is [0,1]<br>fullGridX = np.dstack([gridX,gridX2])<br>fullGridY = np.dstack([gridY,gridY2])</pre><p>With the tools to create our own mesh grid to represent our simulation environment, we can move on to the physics.</p><h3>Basics of Heat Transfer</h3><p>We will first start with the 1 dimensional time dependent heat conduction equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*zWnWVpV2n_QaViYDOkmz-w.png" /><figcaption>Equation 1: <a href="http://geodynamics.usc.edu/~becker/teaching/557/problem_sets/problem_set_fd_explicit.pdf">1-dimensional time dependent heat conduction equation</a>.</figcaption></figure><p>The equation states the the change in temperature over time is based on the material’s thermal properties scaled by the change in temperature across the material (technically the change of the change of the temperature since it is a 2nd derivative). We don’t need to worry about the thermal properties of the material since they can be found in<a href="https://www.engineersedge.com/heat_transfer/thermal_diffusivity_table_13953.htm"> look up tables</a>. What we need to do is convert the derivatives in the equation into something we can handle computationally. Luckily for us, this can be done with the <a href="https://en.wikipedia.org/wiki/Finite_difference_method">finite difference method</a> which will convert equation 1 into equation 2 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*Y4n0PwBGtlJLzkcpSt5K0w.png" /><figcaption>Equation 2: Computational <a href="http://geodynamics.usc.edu/~becker/teaching/557/problem_sets/problem_set_fd_explicit.pdf">1-dimensional time dependent heat conduction equation</a>.</figcaption></figure><p>Equation 2 is a computational equivalent of the time dependent heat conduction equation that we can use to update the temperature in our simulation. Going through each cell in our mesh grid, we can update the temperature of that cell by its current temperature plus the difference in temperature between that cell and its neighboring cells (here i represents the mesh grid index) scaled by the thermal properties of the material and a time step of our choosing.</p><p>Equation 1 &amp; 2 are the 1-dimenstional heat equation but we want to run our simulation in 2-dimensions. Adding in a 2nd dimension is straight forward, especially having the computational version of the heat equation, we just need to add in all neighboring cells as seen below in equation 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*nxlukM326VV361aiKpYXNQ.png" /><figcaption>Equation 3: <a href="https://resources.system-analysis.cadence.com/blog/msa2022-using-the-2d-finite-difference-method-for-heat-transfer-analysis">Computational 2-dimenstional time dependent heat conduction equation</a>.</figcaption></figure><p>Now that we have translated the time dependent heat conduction equation into a computational expression, we can use it to update our mesh grid.</p><h3>Updating Our Mesh Grid</h3><p>Let’s first initialize a mesh grid using the tools we have developed so far. We know we need at least 2 features to plug into our temperature equation which is a current temperature and a thermal diffusivity constant for a material of our choosing. We will start with our material being at room temperature (20°C), and our material will be copper which has a thermal diffusivity of 1.11x10^-2 cm²/s. We fill 2 mesh grids with these values and stack them to make our overall mesh.</p><pre>import numpy as np<br><br>#Define how many intervals we want per axis<br>resolution = 100<br>startingTemperature = 20<br>thermalDiffusivity = 1.11*10**-2<br><br>#Create x and Y arrays of zeros of length 100<br>x1 = np.full(resolution, 20)<br>y1 = np.full(resolution, 20)<br><br>x2 = np.full(resolution, 1.11*10**-2)<br>y2 = np.full(resolution, 1.11*10**-2)<br><br>#Create a mesh grids from above arrays. Outputs are all x and Y values in grid<br>gridX, gridY = np.meshgrid(x1,y1)<br>gridX2, gridY2 = np.meshgrid(x2,y2)<br><br>#Stack both of the mesh grids we have created so every element is<br>#[20,1.11*10**-2]<br>fullGridX = np.dstack([gridX,gridX2])<br>fullGridY = np.dstack([gridY,gridY2])</pre><p>In our specific case, our mesh grid is symmetric (the feature values are the same in the x and y direction), so defining our x and y grid separately is not needed but it is still good practice because we will not always have such symmetry when we simulate. Now that we have our material represented by a mesh grid we need to add heat to it (as we saw in our physics equations, there has to be a difference in temperature for heat to transfer). To add heat to our material, we need to select the cells in our mesh grid we want to heat up and add value to their temper index. We will continue to keep things basic and add heat, let’s say 1000°C, in a square from index 35–65 in both the X and Y direction. The code to do this and a resulting plot of this can be seen below.</p><pre>import matplotlib.pyplot as plt<br><br>#fullGridX[:,:,0] gets the first index of every element in our mesh grid<br>#fullGridX[:,:,0][35:65,35:65] selects a box of values<br>fullGridX[:,:,0][35:65,35:65] += 1000<br><br>plt.imshow(fullGridX[:,:,0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*ghLES36vw7taDuacc0cHBA.png" /><figcaption>Figure 3: Visualization of added heat to our mesh grid.</figcaption></figure><p>We’ve added a patch of heat to our mesh grid, which is a good start but now we need to evolve our system through time to see how the heat transfers. We will need to develop a few more tools to do this. The first will be a find neighbors’ temperature function, which given a cell can get the temperature off all neighboring cells. This function is given below and loops over all 8 bordering cells of a given cell but ignores the corners to only retrieve cells that are up, down, left and right. Another thing we have to consider when looking at all of a cell’s neighbors is <strong>boundary conditions </strong>or what we want to do when we hit the end of our grid. If we are at a grid cell that is already at the edge of the grid, looking for all of its neighbors will throw an error since they don’t all exist. We can handle this with a try except statement in our loop which will give our boundary condition when we try to look for a cell that does not exist. Our boundary condition can be filled with the temperature we want to assume outside of our grid. In our simulation, we are going to say this is room temperature, so when we calculate the heat transfer at our mesh grid edges, room temperature will always be given as a neighboring value to an edge cell.</p><pre>def getNeighborsTemperature(grid, point, boundaryTemp):<br>    #List to collect all neighboring temperatures<br>    neighbors = []<br>    #Loop over all neighboring cells<br>    for i in range(-1,2):<br>        for j in range(-1,2):<br>            try:<br>                #Ignore corner cells<br>                if abs(i) != abs(j):<br>                    neighbors.append(grid[point[0] + i][point[1]+ j])<br>            except:<br>                #Apply boundary condition<br>                neighbors.append(boundaryTemp)<br>          <br>    return neighbors</pre><p>The next function we have to develop will implement the 2-dimensional time dependent heat conduction equation we found in the last section. We solved for the computational equivalent for this equation so the implementation is straight forward and given below. The function completes the heat conduction equation by taking in the temperature of a given cell, the temperature of the cells around it, a time step of our choosing, and the thermal diffusivity of the cell material.</p><pre>def calculateHeat(cellTemp, neighborTemps, timeStep, thermalDiffusivity):<br>    #Converting equation 3 into code<br>    cellTemp = cellTemp + timeStep*thermalDiffusivity*((neighborTemps[0] -2*cellTemp + neighborTemps[-1]) + <br>                                                       (neighborTemps[1] -2*cellTemp + neighborTemps[-2]))<br>    return cellTemp</pre><p>The last function we need will combine the two previous functions to loop over every cell in our mesh grid and update its temperature. For every cell in our grid we first run “getNeighbors” to get all of the neighboring temperatures and then we pass the neighboring temperatures plus the current cell temperature and other arguments to update the cell’s temperature.</p><pre>def heatTransfer(grid, timeStep, boundaryTemp):<br>    #Loop over all grid cells <br>    for i in range(0,len(grid)):<br>        for j in range(0,len(grid)):<br>            #Get neighboring cell temperatures<br>            neighbors = getNeighborsTemperature(grid[:,:,0], (i,j), boundaryTemp)<br>            #Update current cell temperature<br>            grid[:,:,0][i][j] = calculateHeat(grid[:,:,0][i][j], neighbors, timeStep, grid[:,:,1][i][j])<br>              <br>    return grid</pre><p>Finally, we can use our heat transfer equation to update our original mesh grid. The final code snippet will update our grid with a 30 second time step and compare the before and after.</p><pre>#Applying our heat transfer equation on current grid with a 30 secound time step<br>nextGrid = heatTransfer(fullGridX.copy(),30, 20)<br><br>#Matplotlib subplots to show the original and updated mesh grid<br>plt.figure(figsize = (12,6))<br><br>plt.subplot(1,2,1)<br>plt.imshow(fullGridX[:,:,0])<br>plt.title(&quot;t = 0&quot;)<br><br>plt.subplot(1,2,2)<br>plt.imshow(nextGrid[:,:,0])<br>plt.title(&quot;t = 30&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyNisjb8MiwgFu07hYW_xA.png" /><figcaption>Figure 4: Updating our mesh grid with our heat transfer heat with a 30 second time step.</figcaption></figure><p>We now have all the tools need to run conductive heat transfer simulations, we will run a few in the next section.</p><h3>Simulation</h3><p>With all of out simulation tools created, all we have to do is put our heat transfer equation inside of a loop and evolve the system for as many time steps as we want. The code to do this is given as well as a function to visualize our simulation as a gif.</p><pre>import imageio<br>&quot;&quot;&quot;<br>This make gif function takes in a set of images and turns them into a gif!<br>Give the frames as an array of mesh grids (only the temperature)and a name <br>for the gif as well as the temperature bounds for the heat map.<br>&quot;&quot;&quot;<br>def makeGif(frames,name,minTemp,maxTemp):<br>    !mkdir frames<br>    <br>    counter=0<br>    images = []<br>    for i in range(0,len(frames)):<br>        plt.figure()<br>        plt.imshow(frames[i], cmap = &quot;inferno&quot;, vmin = minTemp, vmax = maxTemp)<br>        plt.savefig(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;)<br>        images.append(imageio.imread(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;))<br>        counter += 1<br>        plt.close()<br>        <br>    imageio.mimsave(name, images)<br>        <br>    !rm -r frames</pre><pre>#RUNNING SIMULATION<br>#Keep track of our mesh grid frames to make into gif<br>frames = [fullGridX[:,:,0].copy()]<br><br>timeStep = 30<br>boundaryTemp = 20<br><br>#Run for 500 time steps<br>for t in range(0,500):<br>    fullGridX = heatTransfer(fullGridX.copy(),timeStep,boundaryTemp)<br>    frames.append(fullGridX[:,:,0].copy())<br><br>makeGif(frames,&quot;simulation.gif&quot;,20,500)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*R3Wq4vaFBUDRADsJsqkiYw.gif" /><figcaption>Figure 5: Gif of our conductive heat transfer simulation</figcaption></figure><p>And there we have it. We have ran a simulation of conductive heat transfer and visualized it (with the cool “inferno” color map). With the generalized set of tools we developed, we can run many different simulations with different time steps, starting temperatures, materials and geometries. The next and final section will show off a couple more scenarios made with our tools.</p><h3>Example Scenarios</h3><h4>Welding</h4><p>The following is a simulation of a sheet of brass and steel being welded together. What is interesting is the brass (left side) has about 3x the thermal conductivity as steel (right side) and we can see the difference in the material properties as the heat dissipates.</p><p>Note that we can add heat into out simulation iteratively as well by adding to the temperature layer of our mesh grid inside of our simulating loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1XinmbVYK56q9mTT1fDD_g.gif" /><figcaption>Figure 6: Simulation of welding brass and steel together.</figcaption></figure><h4>Bruner</h4><p>Here a stove top burner is being simulated by adding a circular patch of heat to the mesh grid. The heat is being added gradually (3°C per second) until the burner is turned off and allowed to cool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*SEJt0rByXipx10FxTWXFfw.gif" /><figcaption>Figure 7: Simulation of a stove top burner being heated up and turned off.</figcaption></figure><h3>Full Code</h3><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import imageio<br><br>def getNeighborsTemperature(grid, point, boundaryTemp):<br>    neighbors = []<br>    for i in range(-1,2):<br>        for j in range(-1,2):<br>            try:<br>                if abs(i) != abs(j):<br>                    neighbors.append(grid[point[0] + i][point[1]+ j])<br>            except:<br>                neighbors.append(boundaryTemp)<br>          <br>    return neighbors<br><br>def calculateHeat(cellTemp, neighborTemps, timeStep, thermalDiffusivity):<br>    cellTemp = cellTemp + timeStep*thermalDiffusivity*((neighborTemps[0] -2*cellTemp + neighborTemps[-1]) + <br>                                                       (neighborTemps[1] -2*cellTemp + neighborTemps[-2]))<br>    return cellTemp<br><br>def heatTransfer(grid, timeStep, boundaryTemp):<br>    <br>    for i in range(0,len(grid)):<br>        for j in range(0,len(grid)):<br>            neighbors = getNeighborsTemperature(grid[:,:,0], (i,j), boundaryTemp)<br>            grid[:,:,0][i][j] = calculateHeat(grid[:,:,0][i][j], neighbors, timeStep, grid[:,:,1][i][j])<br>              <br>    return grid<br><br>def makeGif(frames,name,minTemp,maxTemp):<br>    !mkdir frames<br>    <br>    counter=0<br>    images = []<br>    for i in range(0,len(frames)):<br>        plt.figure()<br>        plt.imshow(frames[i], cmap = &quot;inferno&quot;, vmin = minTemp, vmax = maxTemp)<br>        plt.savefig(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;)<br>        images.append(imageio.imread(&quot;frames/&quot; + str(counter)+ &quot;.png&quot;))<br>        counter += 1<br>        plt.close()<br>        <br>    imageio.mimsave(name, images)<br>        <br>    !rm -r frames<br><br>#Make mesh grid<br>resolution = 100<br>startingTemperature = 20<br>thermalDiffusivity = 1.11*10**-2<br><br>x1 = np.full(resolution, 20)<br>y1 = np.full(resolution, 20)<br><br>x2 = np.full(resolution, 1.11*10**-2)<br>y2 = np.full(resolution, 1.11*10**-2)<br><br>gridX, gridY = np.meshgrid(x1,y1)<br>gridX2, gridY2 = np.meshgrid(x2,y2)<br><br>fullGridX = np.dstack([gridX,gridX2])<br>fullGridY = np.dstack([gridY,gridY2])<br><br>#Add heat<br>fullGridX[:,:,0][35:65,35:65] += 1000<br><br>#Run simulation<br>frames = [fullGridX[:,:,0].copy()]<br><br>timeStep = 30<br>boundaryTemp = 20<br><br>for t in range(0,500):<br>    fullGridX = heatTransfer(fullGridX.copy(),timeStep,boundaryTemp)<br>    frames.append(fullGridX[:,:,0].copy())<br><br>#Make Gif, saves as &quot;simulation.gif&quot;<br>makeGif(frames,&quot;simulation.gif&quot;,20,500)</pre><h3>References</h3><p>[1]Finite difference example: 1D explicit heat equation <a href="http://geodynamics.usc.edu/~becker/teaching/557/problem_sets/problem_set_fd_explicit.pdf">http://geodynamics.usc.edu/~becker/teaching/557/problem_sets/problem_set_fd_explicit.pdf</a></p><p>[2] Using the 2D Finite Difference Method for Heat Transfer Analysis <a href="https://resources.system-analysis.cadence.com/blog/msa2022-using-the-2d-finite-difference-method-for-heat-transfer-analysis">https://resources.system-analysis.cadence.com/blog/msa2022-using-the-2d-finite-difference-method-for-heat-transfer-analysis</a></p><p>[3] Heat Conduction Equation <a href="https://cecs.wright.edu/~sthomas/htchapter02.pdf">https://cecs.wright.edu/~sthomas/htchapter02.pdf</a></p><p>[4] Unless otherwise cited, all figures in this article were created by the author.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4f09b3e16b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/simulation-101-conductive-heat-transfer-a4f09b3e16b4">Simulation 101: Conductive Heat Transfer</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>
    </channel>
</rss>