<?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 Ross Wilhite on Medium]]></title>
        <description><![CDATA[Stories by Ross Wilhite on Medium]]></description>
        <link>https://medium.com/@wilhiteross?source=rss-4e7a72add68f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*T3zahYQ4J-oCg7NyXCnq7g.jpeg</url>
            <title>Stories by Ross Wilhite on Medium</title>
            <link>https://medium.com/@wilhiteross?source=rss-4e7a72add68f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:58:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wilhiteross/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[Simulating a Drone’s Self Localization with A Particle Filter]]></title>
            <link>https://wilhiteross.medium.com/simulating-a-drones-self-localization-with-a-particle-filter-84da419671ba?source=rss-4e7a72add68f------2</link>
            <guid isPermaLink="false">https://medium.com/p/84da419671ba</guid>
            <category><![CDATA[autonomous-vehicles]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[cognitive-computing]]></category>
            <category><![CDATA[probabilistic-programming]]></category>
            <dc:creator><![CDATA[Ross Wilhite]]></dc:creator>
            <pubDate>Thu, 17 Jun 2021 11:32:05 GMT</pubDate>
            <atom:updated>2021-06-17T11:32:05.461Z</atom:updated>
            <content:encoded><![CDATA[<p>A Particle filter is a localization algorithm based on sampling random points and calculating the probability that your points represent the true location of the object being tracked. In this implementation, I created a simulation environment using python which contains the following functionality:</p><ol><li>Read and Draw an image from a file</li><li>Calculate a Grid based on the image</li><li>Pick a random location to simulate a drone flying over the image</li><li>Pick N more random locations for particles</li><li>Take photos of the ground below using a square aperture of size N from the location of the drone and all the particles</li><li>Compare the photos using an RGB histogram intersection</li><li>Normalize the intersection values so they Sum up to 1</li><li>Display the map with particles sized by weight</li><li>Regenerate the particles using a Low Variance Re-sampler</li><li>Move the drone by a random vector with magnitude 1</li><li>Add noise to drone movement to simulate wind</li><li>Move the particles with the drone’s velocity vector</li><li>Repeat from step 5 indefinitely</li></ol><p>This article is more about my optimization than an intro to a particle filter. While I will give a brief overview of how the system works, for a more comprehensive overview, I would read <a href="https://web.mit.edu/16.412j/www/html/Advanced%20lectures/Slides/Hsaio_plinval_miller_ParticleFiltersPrint.pdf">other resources</a>.</p><h4>Particle Filter</h4><p>A particle filter is an algorithm used in various fields of computing, such as cognitive computing and signal processing. It was originally developed in 1996 by Del Moral [1], and the name is a reference to probability equations which have been used in fluid mechanics since the 1960’s. It was also further categorized as a Sequential Monte Carlo method in 1998 by Liu and Chen [2].</p><p>This specific application and example represent a common way particle filters can be used in computer vision applications. In it’s simplest form, a particle filter involves randomly sampling a possible set of solutions, calculating the probability that each one is correct based on some form of observation, and then resampling a new set based on the old set, and then repeating to develop a more accurate estimation.</p><p>if you prefer a quick visual explanation, here are a few frames of my algorithm in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2mK9ZzsaTKQb4jLcxZMNA.png" /><figcaption>Example, Initial State</figcaption></figure><p>In the initial state, we generate a random location on the map. The location is marked by a dark blue circle with a white outline. In the first step, we generate N random evenly-distributed points on the map as an estimate of where we believe the drone to be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rl268cKJuFx3AhWppQKYtw.png" /><figcaption>Example, Generated particles</figcaption></figure><p>The particles are marked by light blue circles. In my application, the radius of the circle represents the probability that a random selected point is the location of the drone. So here we can see that there are a few locations where the drone might be. One timestep is definitely not enough to locate the drone.</p><p>Now, every timestep from here, we resample the particles. The particles with a higher distribution are more likely to be selected. Then we recalculate the probability of each resampled point. We also add a bit of noise to the resampling, in terms of x,y offset from the original samples point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1MW3WXF74VBsfx9xq-neg.png" /><figcaption>Example, resampled particles</figcaption></figure><p>From here, we can see that the second timestep greatly improves our estimation of the location. We have a few particles resampled around each of the circles from the first step that were considered highly probable. We also know the speed of the drone so after resampling, we can move all of the particles with the same speed as the drone. After that, we recalculate the probability given the new locations of the particles, we can see the algorithm was able to narrow it down even further.</p><p>How we calculate the probabilities and how to improve the basic functionality will be covered later in the article.</p><h4>How to Run the Script</h4><p>Download the repository from <a href="https://github.com/Wilhite-r/ParticleFilterSimulation">my repository</a>, navigate to the directory called “SimulationEnvironment”, and run python3 SimulationEngine.py on the command line (You must have python 3 installed already). To run this locally, you will need a number of libraries. I did not collect all the libraries necessary, but the most important ones are numpy and opencv. There are many guides online to install these, but I used “pip install” commands for both of them.</p><h3>Implementation</h3><h4>Drone Movement</h4><p>Drone Movement is based on a randomly generated vector, with calculations to limit it from pushing the drone off of the map grid.<br> First I calculate the limits of the movement based on the grid, current position and velocity magnitude as [Xmin, Xmax], [Ymin, Ymax]. Then I run the following calculations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*3HWx5gF-Pk4EXqSR1P7zzw.png" /><figcaption>Calculations for the X and Y velocity</figcaption></figure><p>A new velocity is generated every second and determines the movement for the drones and the particles. However, the drone also has a noise calculation. This is implemented with a random value selected from normal distribution for each x and y positions. Similar to the velocity vector, before applying noise, we check the movement boundaries and only generate noise that won’t put us over the edge of the map. For most tests, I used a variance squared of 0.2 position units. I did this because I found that a lower variance helps me to localize faster, and 0.2 seemed to be a realistic value of noise from motors and moderate wind.</p><h4>Location Generation</h4><p>The initial drone location generation uses the same code as the particle location generation. It is very basic and just consists of grabbing a value from a uniform distribution, somewhere within the map’s boundaries.</p><h4>Particle Weight Calculation and Movement</h4><p>The most complicated part of my specific filter is the weight calculation for the particles. Since there is a lot going on here, I will walk through the weight calculation step-by-step.</p><ol><li>On all iterations except the first one, the first thing we do is move the particles according to the drone movement. This is as simple as adding the calculated Xvel and Yvel scalars to the X and Y location of the particles. <a href="https://github.com/Wilhite-r/ParticleFilterSimulation/blob/main/ParticleFilter/ParticleFilter.py#L61">Line Here</a></li><li>Then rescan the area around the particle using the same aperture size as the drone. This is done by taking a subset of the total image based on the particles location and aperture size. <a href="https://github.com/Wilhite-r/ParticleFilterSimulation/blob/main/ImageProcessing/ImageLoader.py#L13">Line here</a></li><li>Next, we call the function DetermineWeights inside of the ParticleFilter.py class. The first thing that happens here is we cycle through all of the particles and get a weight for each one. As we cycle we track the max, min, and sum of all the weights. <a href="https://github.com/Wilhite-r/ParticleFilterSimulation/blob/main/ParticleFilter/ParticleFilter.py#L146">Loop here</a></li><li>Determining the weights happens via an RGB histogram correlation function. We convert both the drone’s scan and the particles scan to RGB, group the histogram values into a parameterized number of bins, then run a correlation function according to OpenCv’s library. Documentation on that can be found here: <a href="https://docs.opencv.org/4.5.1/d8/dc8/tutorial_histogram_comparison.html">OpenCV: Histogram Comparison</a>. <a href="https://github.com/Wilhite-r/ParticleFilterSimulation/blob/main/ImageProcessing/ImageLoader.py#L21">My implementation is here</a></li><li>Since this function returns values between -1 and 1, the first thing I do with this value is set all negative results to 0. In my original implementation, I scaled the results from 0 to 1, but I actually found the filter to be better optimized by just dropping all the negative weights to 0. <a href="https://github.com/Wilhite-r/ParticleFilterSimulation/blob/main/ParticleFilter/ParticleFilter.py#L29">Line here</a></li><li>After this I square the weights, I do this to give a bigger contrast between the low and high weight. This is the first step which exploits the functionality of the resample algorithm. As we are now artificially more likely to choose the higher weights during resampling, causing localization to happen quicker.</li><li>Once I’ve done this for all the particles, I Normalize the weights for the first time. Three things happen here: I scale all the weights back (by dividing the individual weights by the total weight sum) so they sum to 1, but they keep their same relative values. <a href="https://github.com/Wilhite-r/ParticleFilterSimulation/blob/main/ParticleFilter/ParticleFilter.py#L35">Function here</a></li><li>Here you can see I also calculate an alternate weight, which I have labelled as visualWeight. The original purpose of this weight was to make the rendered map more interesting, however I found this value to be very valuable in calculations as well. The VisualWeight is simply all the weights (after scaling) distributed from 0 to 1, and it indicates the percentile of each individual particles weight within the range of weight values. I do this because I use this value to scale the particles by multiplying the visual weight by 15.</li><li>I also implemented a low-weight cutoff, where I automatically scale back all particles with a visual weight less than a certain amount to 0. This again helps narrow down bad predictions quickly, as I dump all of the particles with weights in the bottom N% of the range. I optimized this value to be 60%, through testing. <a href="https://github.com/Wilhite-r/ParticleFilterSimulation/blob/main/ParticleFilter/ParticleFilter.py#L44">Line here</a></li><li>Now that we’ve dropped some weights, I need to rescale the particles again. I do this by running the same function as before, but skipping the cutoff step.</li></ol><h4>Particle Location Regeneration</h4><p>After we calculate the particle locations, we can resample the particles to narrow down which particles most likely represent our location. In my system, particle regeneration happens after the image gets displayed, so it is the first thing to happen in every loop of the main function. In this project, I use the low variance sampler algorithm taken Thrun, Burgard, and Fox’s textbook [3].</p><p>I exploit some of the functionalities of the resampler when I calculate weights, but the only thing additional that isn’t described in the textbook is my resample noise generation. When I regenerate the noise particles, I add a bit of variance to the regeneration, to account for errors in the velocity of the drone, as well as increase the area for initial calculation of the drone’s location.</p><p>The noise is generated in the form of a velocity vector where both the x and y velocity and selected from a normal distribution with a variance that is inverse to the particles weight in the previous step. I also have a scaling parameter to affect noise regeneration for all particles. The equation looks somewhat like this:</p><pre>Xvel = N(0, ((1 - ωadj) * F) 2)<br>Yvel = N(0, ((1 - ωadj) * F) 2)</pre><p><a href="https://github.com/Wilhite-r/ParticleFilterSimulation/blob/9f476e963bae73e4431ae43b323fad7464fe2720/ParticleFilter/ParticleFilter.py#L71">Found here in the code</a></p><p>The purpose of using the inverse of the weight is so that particles with higher probabilities 𝑃(𝑧𝑡|𝑥𝑡) will have less variance when regenerating. If a particle has a weight near 1, the noise will be negligible. It’s worth noting that I don’t use the regular weight, but instead I use ω𝑎𝑑𝑗, my custom, adjusted weight, known as visualWeight. F is a parameterized scaling factor. My most optimized version uses a scaling factor of 0.8. Ideally, a lower factor means the end result will be more accurate, however it also reduces our chances of localizing to the particle in the first few steps, and it makes the filter vulnerable to losing the particle’s location if the RNG gives the particle a high velocity noise for any given step.</p><h3>Observation</h3><h4>Measurement</h4><p>So how do we measure how accurate our particle is, mathematically? I chose to follow two routes, the <a href="https://www.statisticshowto.com/average-deviation/#:~:text=The%20average%20deviation%20is%201.09.%20Absolute%20Deviation%20is,spreads%20can%20produce%20the%20exact%20same%20absolute%20deviation.">absolute average deviation</a>, which I refer to mostly as bias, and the Variance. In the real world, without the actual location, the absolute average deviation would be impossible to measure, and the variance would be a better option, but we can use it, since it’s a simulation. The deviation formula I am using is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*aHvNSHR-FFOzBIXZAwvKqQ.png" /><figcaption>Absolute average deviation equation</figcaption></figure><p>In this equation, xp is the particle position, and xis the actual drone location.</p><p>For the variance, I use numpy’s built in variance function. I take the variance of both the location and the weights. For weight, I take the variance of an array filled with the weight values; for location, I take the variance of an array filled with X values, and one filled with Y values, then I perform Pythagorean theorem on those variances to get the total location variance.</p><p><a href="https://github.com/Wilhite-r/ParticleFilterSimulation/blob/9f476e963bae73e4431ae43b323fad7464fe2720/ParticleFilter/ParticleFilter.py#L175">Metrics function here</a></p><h4>Initial Test</h4><p>I wanted to test my initial filter, then iterate on it, to try to reduce the variance and bias. I started with 500 particles, 50 pixels aperture, movement magnitude of 1, and using histogram intersection as my comparison function</p><p>This test was very indicative of how the filter went in initial tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HXQNe5XWlZsESz0uV9HyA.png" /><figcaption>Initial test, initial state</figcaption></figure><p>The first state shows the fault of this setup already. There are not many particles over the whole image. While we got lucky and a particle was generated right on top of the drone, but there are many areas where the drone could exist where there are no particles nearby. After 5 steps the particles get moved to these locations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMMl-Rd_Bxf7TLiw3mpyGQ.png" /><figcaption>Initial test, step 5</figcaption></figure><p>So far, the drone has flown only over land, and it shows in the map that we have removed almost all of the particles over water. However, we haven’t quite localized the particle. It is flying over the forest and the building area near the south, I don’t imagine it will localize enough to be usable. After running for 10 more steps I can see that it was a fairly accurate assumption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtkQinKliBXIds4ROBFXfw.png" /><figcaption>Initial test, step 15</figcaption></figure><p>Here we can see that many particles have clumped around the drone, however there are still many other clumps in the main town on the Eastern side of the harbor, and there are still some particles in the forest to the southwest. Really the particle hasn’t been localized at all, and the system would be fairly useless in this iteration, even after 15 units of time have passed. Below I plot the variance and deviation of the particles at each step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ig2BAR5jxYFbWS2Z9AHPTQ.png" /><figcaption>Step 15, Bias = 51, Variance = 40</figcaption></figure><p>While the bias and variance may still decrease, I am not completely happy with the rate at which they have gone down. I want a bias of less than 1 by the 5th step.</p><h3>Optimization</h3><p>The first idea for improvement is the easiest, increasing the particle count. First, I would like to try doubling the particle count to 1000. Let’s see how this runs.</p><h4>Doubling the Particle Count</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20YXCHDSZaFpErN6sZkO3Q.png" /><figcaption>1000 particle count test</figcaption></figure><p>So the result here speaks for itself. We have decreased both variance and bias. But we still haven’t localized the particle. We are somewhat certain that the particle is in the eastern town section, but we don’t know where in this town it is. We have basically localized it to the entire town. I think we need to increase the filter’s image recognition algorithm. I have two ideas to implement for this.</p><p>First, I want to use Correlation, instead of intersection. It produces a greater variance for half matches than full matches, and I will increase the amount of histogram bins to give us more data for each math. In theory this should increase the accuracy of all predictions.</p><h4>RGB Histogram Correlation and Increase in Histogram Bins</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vwoc3pWmqI0QOMmBZTjqCQ.png" /><figcaption>RGB correlation and increased bins</figcaption></figure><p>After using Correlation and more bins per color channel (16 instead of 8), the image recognition becomes more strict. The Variance has decreased slightly and the bias has decreased quite a bit, but not as much as I would hope. We have localized even further to the town, but the bias is still too large for us to be certain where the drone is. Here I want to try to square the weights, which will increase the contrast, and therefore the variance between the weights, but should make the particle regeneration more strict. I estimate that this will remove the low weight particles that are outside of the town.</p><h4>Squared Weights</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIJyj2fKBufLco6k8l_pVA.png" /><figcaption>Squared Weights</figcaption></figure><p>This had a much bigger effect than I expected. But it is very telling about how increasing the variance in the particles to influence the resampling functionality can make a huge difference in the overall bias. You can see how the variance and bias increases at first, but once a good selection is made, the Bias and Variance shoots down, quickly eliminating low ranking weights. I am very happy with this progress, but I had a few more ideas to see if I can increase the rate at which the bias decreases. I still want to beat a bias of 1 by step 5.</p><p>I am going to see if I can get rid of some of the noise by manually removing particles. Actually removing the particles will create a possibility where we end up with 0 particles. Instead, once we normalize particles, I will set the lowest 25% of the particles to a weight of 0, so they get removed automatically by the re-sampling algorithm.</p><h4>Minimum Particle Weight Cutoff</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjza4c32zxdix0KMwFvtqA.png" /><figcaption>Minimum particle weight cutoff</figcaption></figure><p>This was the final key in quick localization. It quickly gets rid of the low weighted particles and the bias drops to nearly 0 in 4 steps. The center of the mass of particles is very near the drone. The variance is also lower than any other method, in fact, I don’t think the variance can get any lower due to the resampling noise, which has a variance itself of 1.0. So of course, the next thing I thought to do was limit the resampling noise.</p><h4>Lower Re-sampling Noise</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WtlJHucoIF6hu1VNq1EEQ.png" /><figcaption>Lower resampling noise</figcaption></figure><p>This is the first time where I think the adjustments had an adverse effect. Our bias is much higher than the previous instance, but more importantly, I had to triple the amount of particles, which was detrimental to the performance of the filter, and could possibly keep it from operating in real time. I had to do this because the variance of the resampling was so small, that we would only “find” the drone’s location if it started with a particle right below it, and it was possible to lose the drone, since the drones velocity noise could be the same magnitude as the resampling noise. In a real world solution, I could relocate the drone by regenerating samples over the center of particles with a variance related to the weight variance, which acts as a gauge of uncertainty, though I did not implement that functionality for this project.</p><p>Another problem is these solutions only work well over the town. If I try to do the same thing over the ocean or the forest in the northwest, the results are very different. We never localize using these methods. I will reset the parameters changed in this iteration and show what happens when we start over the ocean.</p><h4>Results Over Ocean</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQKAu4RUIwBR4DFYIla65A.png" /><figcaption>Ocean test</figcaption></figure><p>We never quite locate the exact spot of the drone. We do find the general area in the ocean where it’s located, but I think a slight improvement can be made. It’s notable that the weight variance only drops below 10 once. While we do a decent job of locating the particle. We will actually have to make the image identification more sensitive to distinguish the similar hues of blues.</p><h4>Further Tuning Values</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V69pY0pwIpCWRPJ7uC2R2Q.png" /></figure><p>In this final Iteration. I tuned some of the parameters I introduced in the earlier iterations to make the identification work very well on water. The final parameters are as follows:</p><p>- Number of particles: 1000<br>- Aperture Size: 75<br>- Resample noise = η(0, (0. 8) * (1 − ω%)), where ω% is the percentage of the particle’s weight, in the range of all the particle weights<br>- Particle cutoff: ω% &lt; 60%<br>- Drone Movement Noise variance = η(0, (0. 2)) <br>- Drone Velocity Magnitude = 1.0<br>- Bins per color channel: 64</p><p>Thank you for reading this article. I encourage you to use these strategies to optimize your own particle filters.</p><p>Also check out my code here: <a href="https://github.com/Wilhite-r/ParticleFilterSimulation/tree/9f476e963bae73e4431ae43b323fad7464fe2720">Wilhite-r/ParticleFilterSimulation at 9f476e963bae73e4431ae43b323fad7464fe2720 (github.com)</a><br>All of this code is original so if you use any of it, please send me a private message. and credit me. Thank you!</p><h3>Bibliography</h3><p>[1] Del Moral, Pierre (1996). <a href="http://people.bordeaux.inria.fr/pierre.delmoral/delmoral96nonlinear.pdf">“Non Linear Filtering: Interacting Particle Solution”</a> (PDF). <em>Markov Processes and Related Fields</em>. <strong>2</strong> (4): 555–580.</p><p>[2] Liu, Jun S.; Chen, Rong (1998–09–01). “Sequential Monte Carlo Methods for Dynamic Systems”. <em>Journal of the American Statistical Association</em>. <strong>93</strong> (443): 1032–1044. <a href="https://en.wikipedia.org/wiki/Doi_(identifier)">doi</a>:<a href="https://doi.org/10.1080%2F01621459.1998.10473765">10.1080/01621459.1998.10473765</a>. <a href="https://en.wikipedia.org/wiki/ISSN_(identifier)">ISSN</a> <a href="https://www.worldcat.org/issn/0162-1459">0162–1459</a>.</p><p>[3] Josh Bongard; <em>Probabilistic Robotics</em>. Sebastian Thrun, Wolfram Burgard, and Dieter Fox. (2005, MIT Press.) 647 pages. <em>Artif Life</em> 2008; 14 (2): 227–229. doi: <a href="https://doi.org/10.1162/artl.2008.14.2.227">https://doi.org/10.1162/artl.2008.14.2.227</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84da419671ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identifying System Malfunctions Using Bayes Theorem]]></title>
            <link>https://wilhiteross.medium.com/identifying-system-malfunctions-using-bayes-theorem-9a81a87eb8d0?source=rss-4e7a72add68f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a81a87eb8d0</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[autonomous-vehicles]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Ross Wilhite]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 12:40:05 GMT</pubDate>
            <atom:updated>2021-02-23T12:40:05.661Z</atom:updated>
            <content:encoded><![CDATA[<p>An Intro to Probabilistic Robotics</p><p>Modern robotics engineers are becoming increasingly interested in making fully autonomous systems. Technologies such as self-driving cars, drones, industrial robotics, or similar systems all need to read their surroundings and respond accordingly. To make sense of the highly variable environments they work in, these systems utilize modern concepts such as neural networks, sensor fusion, and probabilistic robotics. To understand how autonomous system’s decision making processes work, an engineer must be familiar with a few concepts in probability theory and statistics. This article gives a basic overview of Baye’s theorem, a standard in probabilities, and a real world application to aid in understanding.</p><h4>Probability Theory Syntax</h4><p>P(x) — In probability theory, you will see this formatting very often. Similar to function syntax in calculus, P(x) represents the probability of a variable A equaling x. If you wanted to represent the probability of a value equaling n, you would write P(n).</p><p>P(x,y) — Represents the state of two variables. This is identical to the boolean property AND . To represent the probability that A = n and B = x , you would write P(n,x) .</p><p>P(x|y) — This symbol is the basis of Baye’s theorem. It is known as conditional probability. It is often read as “The probability of x, given y”. This is notably different than P(x,y).</p><h4>Our System to Solve</h4><p>In this example, we will imagine a theoretical robotic system. To keep things simple, we will have one single variable, though of course in the real world there will be much more than one variable. Let’s imagine a sensor on a robot that is trying to read its operating temperature in celsius to determine if it should active it’s cooling cycle. To simplify the system even further, let’s imagine that the temperatures follow an even distribution from 0–30. This means you are just as likely to have a temperature of 3 as you are to have a temperature of 29. While this does not represent a realistic distribution, it will help us better understand the theorem.</p><p>However, the manufacturer has warned us that there is a chance that our sensor is faulty, as their recent QA in the factory determined that a small percent of their sensors are only returning a temperature between 0 and 10.</p><p>In their testing, they have estimated that around .05% of their sensors are having this fault, and recommend testing the sensor. In order to test our sensor, we have decided to gather data from the sensor, once per hour. Every time we read the data, we are getting readings between 0 and 10, however, our manager has told us that we should only contact the sensor manufacturer if we are 95% sure that the sensor is faulty, as replacing the sensors on the system is a huge expense. How many times do we need to read the temperature, before we can be 95% sure the sensor is broken?</p><h4>Baye’s Theorem</h4><p>This is an example of when Baye’s theorem will come in handy. By running this equation recursively N number of times, we can find out how many readings we need to take before we are 95% sure that the sensor is broken.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*S5xcUsDDTv7zWDiX5ZXPTQ.png" /><figcaption>Baye’s Theorem in discrete case</figcaption></figure><p>Baye’s theorem is used to discuss the probability of an event occurring, given specific evidence. There are many <a href="https://brilliant.org/wiki/bayes-theorem/#:~:text=Bayes%27%20theorem%20is%20a%20formula%20that%20describes%20how,a%20wide%20range%20of%20problems%20involving%20belief%20updates.">formulations</a> and <a href="http://www.hep.upenn.edu/~johnda/Papers/Bayes.pdf#:~:text=Proof%20of%20Bayes%20Theorem.%20The%20probability%20of%20two,of%20B%20given%20that%20A%20has%20occurred%2C%20P%28B%7CA%29.">proofs</a> online, if you want further information beyond application of the theorem. Later in this article, in the Conclusions section, I will come back to what Baye’s theorem is representing.</p><p>To use Baye’s theorem accurately, we need 3 things: a hypothesis, evidence, and a the probability of our evidence occurring. In this case, our hypothesis is the probability that the sensor is broken, our evidence is the temperature reading below 10, and the probability of the temperature reading below ten is 1/3, or about 33.3%.</p><p>Here are a few terms you will run into when reading or solving statistical inferences:</p><p>Prior — P(H)</p><p>This is our hypothesis of the probability of a value, prior to the system running. In the equation above, this is represented by P(H), and is our hypothesis of how often the sensors are faulty from the factory.</p><p>Observation — E</p><p>This is the real world representation of our estimation. In this system, it represents the actual temperature in the real world. So P(E) represents how often the temperature is E .</p><p>Posterior — P(H|E)</p><p>This is the value that we are solving for, it is the probability (or in some cases the distribution of probabilities) of our hypothesis being true, given the real world observations.</p><p>Generative Model — P(E|H)</p><p>In this case, our generative model is the probability of our observation, given the hypothesis.</p><p>There is another important theorem we will be using here, this is the <strong>theorem of total probability</strong>. This states the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*1oRv1DmpR6e0Xl8sTOMeUw.png" /><figcaption>theorem of total probability in the discrete case</figcaption></figure><p>This is based off of the definition of conditional probability. This theorem states that the probability of x can be known using the conditional probabilities of y, each with a known probability itself. There are also formulations of this theorem <a href="https://byjus.com/maths/total-probability-theorem/">readily available online</a>.</p><p>Substituting this for P(E) in Baye’s theorem, and swapping the comprehension-friendly E, and I for the more technical x , and y , we will get the following equation which we will use with the initial conditions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*1eJ97poc3uAKzg7RzhFr9g.png" /><figcaption>Discrete Baye’s theorem with theorem of total probability</figcaption></figure><h4>Initial conditions</h4><p>Our initial conditions for this system are very important. These are the numbers we will be plugging into Baye’s theorem. We have the following variables:</p><p>A — Whether our system is faulty or not, so P(faulty) represents the probability our system is faulty.</p><p>T — The observed temperature. Since we do not know the real world temperature, we will only be using the observed temperature to solve this system.</p><p>B — Whether the temperature is between 0–10 in our observations. So P(T&lt;10) would represent the probability that we observe a temperature below 10.</p><p>For ease of reading and mathematics, instead of percentages, I will be using decimals. In other words:</p><pre>∑P(A) = 1 or ∫P(A)dA = 1 in a continuous system</pre><p>Here are the initial conditions represented in an observation model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*3c6Ui7c9tIPpqxWZl8cRaw.png" /><figcaption>Initial conditions</figcaption></figure><p>The columns represent the collection of probabilities given A , the sensor state, and the rows represent the collection of probabilities given B , the state of the temperature being below or above 10 degrees. Each cell individually represents the probability of B occurring. A text representation of the bottom left cell would be the following: P(T&lt;10|not faulty) = .6667 (rounded to 4 significant figures. The cells in this square therefore represent our P(y|x) that we need to plug into Baye’s theorem.</p><p>Our other initial conditions are as follows:</p><p>P(faulty)= 0.0005 — These are the manufacturer’s estimations of how likely a given sensor is faulty. This value gives us P(x) in the initial state. But in every iteration we will replace this with what Baye’s theorem gave us in the previous iteration.</p><p>P(not faulty) = 0.9995 — This is just 1 - P(faulty) and will be used in the denominator of our equation.</p><p>Substituting our variables into Baye’s theorem, we get the equation that we will need to recursively solve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2KSvqY1wuFG3rCVuis9Ag.png" /><figcaption>Probability that our sensor is faulty</figcaption></figure><h4>Iterating the Conditions</h4><p>To solve this, I put the equation into Matlab:</p><pre>solutions = [];<br>step = 1;</pre><pre>Pfaulty = 0.0005;<br>Pnotfaulty = 0.0005;<br>PTl10faulty = 1;<br>PTl10notfaulty = 1/3;</pre><pre>while Pfaulty &lt; 0.95 || step == 100<br>   Pfaulty = (PTl10faulty * Pfaulty) ...<br>      / ((PTl10faulty * Pfaulty) + (PTl10notfaulty * (1 - Pfaulty)));</pre><pre>   solutions(step) = Pfaulty;<br>   step = step + 1;<br>end</pre><pre>plot(solutions);</pre><p>This code will allow us to run through N iterations on the algorithm we came up with earlier. When the loop stops, we will have our result, and step will equal N, or how many iterations we went through to find the answer. We also develop a plot of the P(faulty) data. After we run this, we see that after 10 iterations, we have a 96.73% certainty that the sensor is faulty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c86e4pcdOvDFmvov9XMWYA.jpeg" /><figcaption>Our certainty after each iteration</figcaption></figure><p>If we let the process continue, it will continue to approach 1, but here, we can be 95% certain, which should be enough to swap out the sensors.</p><h4>Conclusions</h4><p>Now we can gain a complete understanding of why Baye’s theorem is useful. Most people’s natural reaction to solve this problem would to be to find out how likely it is to receive a reading of T&lt;10 N times in a row, and subtract from 1 the solution. This does one thing right, it tells you when you have reached a 5% chance of receiving T&lt;10 N times in a row, and this can be useful to indicate there may be something wrong. However, with this method, you will be missing a key variable; the likelihood that the sensor is broken would still be lower than the likelihood of receiving those readings.</p><p>Here is a graph I made using a binomial distribution function in Matlab, which shows the likelihood of getting a T&lt;10 reading, N times in a row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqThF4nYR1mpEDV-FyM7OA.jpeg" /><figcaption>Likelihood of reading T&lt;10 N times in a row, plotted over N</figcaption></figure><p>You can see that after 3 rolls we have a likelihood below 5%, if we were to follow the binomial distribution method, we would’ve said that the sensor was faulty, when there was actually only a 1.33% chance the sensor was faulty, using Baye’s theorem. So why are we so uncertain that the sensor is fauly, even when there is a 95% chance that we would <strong>not</strong> receive 3 consecutive readings of T&lt;10 .</p><p>This is the key factor we are forgetting, that the absolute likelihood of a faulty sensor is .05%, which is still much lower than the 5% chance of consecutive readings. While we are in an unlikely state, it is still much more unlikely that the sensor is broken. In fact, this is what Baye’s theorem is measuring, it is essentially comparing these two numbers and telling us which we should trust more.</p><p>We can see solid evidence of this when we compare the probabilities of both measurements after 7 iterations. The absolute probability of a broken sensor is still .05%, and the probability of 7 successive readings of T&lt;10 is .0457%. This is the pivotal moment when the probabilities of both are almost the same, and what does Baye’s theorem give us? About 50%.</p><p>So now we can see what Baye’s theorem is <em>really</em> measuring, it’s just:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNVz0ZpyXrcumP3VkR-W6w.png" /><figcaption>The true measurement of Baye’s theorem revealed</figcaption></figure><p>This shows why Baye’s theorem is so wonderful, it can reveal many misconceptions of statistics, allowing us to compare two probabilities, rather than make conclusions on one single probability.</p><h4>Other Applications</h4><p>There are many other applications to this theorem, and if you ever choose to study probability theory you will see it used widely. You will see this often in medicine for problems such as “the percentage that a patient has rheumatoid arthritis”. In this example we would be comparing the probability that a patient has the symptoms of rheumatoid arthritis without actually having the ailment, to the probability of having that ailment. It is also used in <a href="https://corporatefinanceinstitute.com/resources/knowledge/other/bayes-theorem/#:~:text=Example%20of%20Bayes%E2%80%99%20Theorem%201%20P%20%28A%29%20%E2%80%93,given%20the%20stock%20price%20has%20increased%20by%205%25.">corporate finance</a>. If you are interested in more applications of the theorem, I recommend searching online, there are numerous videos and articles which show further use of this theorem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a81a87eb8d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating My Own Inverse Kinematics Equations For Our Robotic Arm, Using Simple Trigonometry]]></title>
            <link>https://medium.com/analytics-vidhya/creating-my-own-inverse-kinematics-equations-for-our-robotic-arm-using-simple-trigonometry-51ef5ab40967?source=rss-4e7a72add68f------2</link>
            <guid isPermaLink="false">https://medium.com/p/51ef5ab40967</guid>
            <category><![CDATA[inverse-kinematics]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Ross Wilhite]]></dc:creator>
            <pubDate>Tue, 02 Feb 2021 14:42:04 GMT</pubDate>
            <atom:updated>2021-02-05T16:49:19.632Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago, I was working on a project to create a robotic arm using my Raspberry Pi 0 and cheap servos. After a lively virtual brainstorming session, we proposed the ambitious idea of a <a href="https://www.youtube.com/watch?v=h8TLEYDdmHY">calligraphy</a> robot. We had 1 week to design, CAD, program, build, debug, and test the robot. Over the call we came up with a rudimentary design, then went off to build our respective parts of the robot.</p><h4>Creating Flexible Code</h4><p>Since I was the designated software engineer on the team, I decided to start writing the code as soon as possible so that we could start debugging once we put the bot together. We had the layout of our servos planned, however had not settled on the dimensions of the arm yet, so I had to design a system that would work with any dimensions.</p><p>The system design for the code was simple, I would hardcode the dimensions of the robot, then calculate a 2d-grid on which we could draw on the paper below the arm, based on the limitations of the system. Using that grid, we should be able to pass an (x,y) coordinate to a function, and run inverse kinematics to determine the angle each servo needs to be. This way, everything in the code can be dynamic except for the hardcoded dimensions.</p><p>The key to all of this was writing the inverse kinematics equations. There are a few well-established ways to do this (the one I recommend the most is the <a href="https://robotacademy.net.au/lesson/denavit-hartenberg-notation/">Denavit-Hartenberg convention</a>), but I saw that the way we had designed the robot, I would be able to come up with my own inverse kinematics equations for our arm, which seemed like an interesting and exciting geometry problem to challenge myself with.</p><h4>Solving Inverse Kinematics With Elementary Trigonometry</h4><p>Before directly jumping into my diagrams, let’s look at the Cad.</p><figure><img alt="Cad design of our robotic arm" src="https://cdn-images-1.medium.com/max/1013/1*K3-1aRupywOWAu8cTvWXDA.png" /><figcaption>Cad diagram of our robotic arm</figcaption></figure><p>You can see our simple robotic arm design here. We nicknamed it “The Water Tower”, due to its design being similar to a water tower. The pen (Shown as a yellow cylinder) is loosely held by the robot, so that small changes in height do not remove the pencil from the page. The individual servos I will refer to as the following: Shoulder, ElbowY, and ElbowX respectively, moving down the arm from the top.</p><p>After observation, I identified 4 important triangles in the arm design. Using the fixed lengths and two parameters (the X and Y distance, in inches, from the origin, which I’ve identified as the shoulder servo.), I should be able to calculate three angles (Θ, Θ1, and Θ2) which correspond the angles of each servo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*-bqO438Ef0nAI0JFt-apgQ.png" /><figcaption>Triangle for the forearm, drawn parallel to the plan that the arm is on</figcaption></figure><p>The first triangle is a right triangle which exists on the plane that is parallel to the arm. It is important to note that this triangle is not always on the XY plane which is parallel to the paper, but can be affected by the angle of the elbowY servo, however we do not need to know that angle to solve this triangle. Our first input parameter is marked here by X: this is the lateral distance, in cm, from the shoulder servo. From here we need to find the angle Θ and the forearm Y distance (labelled here as Y) which will be used for our next calculations.</p><p>Here is the python code I wrote to find these measurements:</p><pre>forearmYLengthRelative = math.sqrt(ForearmLength**2 - xdis**2) </pre><pre>elbowXAngle = math.degrees(math.acos(xdis / ForearmLength))</pre><p>This is just based off of pythagorean theorem and basic trigonometry. (** is python for exponents, if you aren’t familiar)</p><p>This is simple so far, but it gets more complicated when we move to the plane perpendicular to the ground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*do7Wf1y3DoKWn75Ozrg5kA.png" /><figcaption>The other angles to solve for</figcaption></figure><p>When I first looked at this arm, I saw the initial 2 triangles (labeled 2 and 3 here) and couldn’t figure out how to calculate the angles of the servos. Then I realized there are two more implied triangles here. There is the big triangle, which is a combination of triangles 2, 3 and 4, and the small rectangle in the bottom, then there is the implied triangle 4.</p><p>Now that we have visualized the diagrams on the arm, let’s move them to a white background and label the sides and unknown angles to solve for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*j-h32nVmI0QZw7QsqxQe6Q.png" /><figcaption>The three triangles the arm makes at any point</figcaption></figure><p>Here we have the following known variables: variables B, D, and E, and value Yd. B, D, and E are fixed variables; the bicep length, the distance of the shoulder servo to the ground, and the length of the elbow joint, respectively. Value Yd is an input parameter; the distance in cm from the shoulder servo. Using Yd and D, I could find the hypotenuse of the large triangle, labeled H on the diagram.</p><pre>hypoteneuseLength = math.sqrt(DrawHeight**2 + ydis**2)</pre><p>That alone is useless though, until I pull in the calculated forearm Y variable from the first triangle. Adding E and Y, and using B, I can get the angles in triangle 4. Then we can get triangle 4’s Θ1 and Θ2 using the <a href="https://en.wikipedia.org/wiki/Law_of_cosines">Law of Cosines</a>.</p><pre>additionalTriangleTheta1 = math.degrees(math.acos(((ElbowLength + forearmYLengthRelative)**2 + hypoteneuseLength**2 - BicepLength**2)/(2 * hypoteneuseLength*(ElbowLength + forearmYLengthRelative))))</pre><pre>additionalTriangleTheta2 = math.degrees(math.acos((hypoteneuseLength**2 + BicepLength**2 - (ElbowLength + forearmYLengthRelative)**2)/(2 * BicepLength * hypoteneuseLength)))</pre><p>Now if we get the angles of the big triangle (called bigTheta1 and bigTheta2 in the code), which we also have all the sides for, we can get Θ1 ( shoulderAngle) of triangle 2 by subtracting triangle 4’s Θ2.</p><pre>bigTheta1 = math.degrees(math.asin(DrawHeight/hypoteneuseLength))</pre><pre>bigTheta2 = math.degrees(math.asin(ydis/hypoteneuseLength))</pre><pre>shoulderAngle = bigTheta2 - additionalTriangleTheta2</pre><p>The last angle we need is Θ3 ( elbowYAngle) of triangle 3. This is not one of the 3 angles of the triangle, so to get this we can use the line that extends from B to imagine that triangle 2’s Θ1 exists in triangle 3. Since we know all of the other angles in triangle 3 (one is a right angle, one is Θ2), we can get triangle 3’s Θ3.</p><pre>elbowYAngle = (90 - (bigTheta1 - additionalTriangleTheta1)) - shoulderAngle</pre><p>Now we have the equations for the servo angles at any point on the plane.</p><h4>Restrictions Cut The Plan Short</h4><p>At this point there were a number of delays that delayed our progress. Our first problem was that designing, printing, and building the bot took more time than expected. We then realized the initial design would cause a fairly limited drawing space so we changed the design and had to re-print and build everything again. Eventually, we had all the final dimensions and design put together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCJvYuHvudtJy8CAZ4bsFQ.png" /><figcaption>The new, improved design</figcaption></figure><p>Here are the final fixed dimensions:</p><pre>Dimensions (in cm)<br>BicepLength = 9<br>ElbowHeight = 1.25<br>ElbowLength = 3.3<br>ForearmLength = 10<br>ShoulderHeight = 14.25<br>hoverHeight = 4.0 (the height that the &quot;hand&quot; will hover above the paper)</pre><p>Unfortunately, even after the redesign, our system retained some constricting physical limitations. One of our constraints was the arm interacting with the base, and the other was the limited range where our arm would actually make contact with the page. Unfortunately some of our design limitations came from miscommunication, as such is expected in the pandemic era, where our design session were facilitated through video conferencing technologies.</p><p>We also were working on a limited budget, using essentially the cheapest materials we had access to, so our servos had a minimum resolution of only 1 degree. Using our hand-measured physical range, our 2d drawing grid had the following resolution:</p><pre>X Range<br>0, 145<br>Y Range<br>0, 58</pre><p>This resolution would not be enough for our calligraphy idea. At this point we would just settle for writing legibly.</p><h4>Results</h4><p>After working all night the day before the project was due, we had our completed arm. The arm would vibrate and overshoot when going to a point, and we had spent so much time trying to calibrate the arm, that we had to hard code our initials into the arm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*2Ut5mdcxbPb8Ga0kizmMgw.gif" /><figcaption>The original, tedious video was so slow, this is 3 times faster</figcaption></figure><p>Overall, we were happy with what we had designed within the restrictions. We were severely limited in time and money, and encumbered with grad school classes. Though there are many changes we could make to improve the precision, another major change to make would be to use springs to weigh down the pen. Given more time, I would also have implemented a system which would be able to convert any text to instructions for the arm.</p><h4>Conclusion</h4><p>If you ever decide to do your own robotics projects, I recommend using a more established form of inverse kinematics, such as the Denavit-Hartenberg conventions I mentioned earlier. But you can come up with your own inverse kinematics if you want a challenge. It’s important to remember that for many systems, there are <a href="https://www.researchgate.net/figure/Inverse-kinematics-often-has-multiple-solutions_fig2_259234959">more than one inverse kinematics solution</a> so you should decide a range for one of the servos to make it easier to develop a working system that forces one solution. Also, there are some systems which have infinite solutions, these are much harder to calculate by hand, but if you force one fixed angle for a servo, it makes it much easier.</p><p>Thank you for reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*WK-ECsawKSVNUs5DArw_TQ.gif" /><figcaption>We also taught the bot to wave</figcaption></figure><p><em>For all code associated with this project, </em><a href="https://github.com/Wilhite-r/AnthropoArmP1"><em>go to my github</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51ef5ab40967" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/creating-my-own-inverse-kinematics-equations-for-our-robotic-arm-using-simple-trigonometry-51ef5ab40967">Creating My Own Inverse Kinematics Equations For Our Robotic Arm, Using Simple Trigonometry</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>