<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Sai Panyam.NET &#187; Algorithms</title>
	<atom:link href="http://www.saipanyam.net/tag/algorithms/feed" rel="self" type="application/rss+xml" />
	<link>http://www.saipanyam.net</link>
	<description>On all things .NET &#38; Software Engineering</description>
	<lastBuildDate>Thu, 05 Jan 2012 16:42:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Gale Shapley Algorithm for Stable Matching</title>
		<link>http://www.saipanyam.net/2011/09/gale-shapley-algorithm.html</link>
		<comments>http://www.saipanyam.net/2011/09/gale-shapley-algorithm.html#comments</comments>
		<pubDate>Wed, 14 Sep 2011 02:24:15 +0000</pubDate>
		<dc:creator>Sai Panyam</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Stable Marriage Problem]]></category>

		<guid isPermaLink="false">http://www.saipanyam.net/?p=651</guid>
		<description><![CDATA[Achieving Stable Matching between two sets of entities with various preferences for each other is a real world problem (a.k.a Stable Marriage Problem). Examples include dating sites, matching medical students to hospital jobs (National Resident Matching Program) etc. How can we ensure that there is a stable matching (defined as any pairings, such that no [...]]]></description>
			<content:encoded><![CDATA[<p>Achieving Stable Matching between two sets of entities with various preferences for each other is a real world problem (a.k.a Stable Marriage Problem). Examples include dating sites, matching medical students to hospital jobs (National Resident Matching Program) etc. How can we ensure that there is a stable matching (defined as any pairings, such that no entity can find any one they would rather be with, who would rather be with them)? Such a matching would be stable (or in equilibrium) because any further change would be detrimental to the entities involved in terms of their stated preferences. Some questions that arise are whether such a matching actually exists? If it exists, how do we find it? How can we be confident that the solution that we get is the &#8216;best&#8217; among all possible matchings? These issues are not trivial and when the elements of the entity sets increase, it soon becomes an intractable problem to solve by trial and error.</p>
<p>Thankfully in answer to the question of whether a stable matching exists, we have a theorem that guarantees exactly that! It states that:<br />
&#8220;For any number entities of two disjoint sets (having equal number of elements), no matter how they rank each other, there always <strong>exists</strong> at least <strong>one stable matching</strong>&#8221;</p>
<p>While the solution is stable, it is not necessarily optimal from all individuals&#8217; points of view. The traditional form of the algorithm is optimal for the initiator (suitor) of the proposals and the stable, suitor-optimal solution may or may not be optimal for the acceptor of the proposals. It will be acceptor pessimal.</p>
<p>To find the solution, we have the Gale-Shapley Algorithm. In 1962,&nbsp;&nbsp;<a title="David Gale" href="http://en.wikipedia.org/wiki/David_Gale">David Gale</a>&nbsp;and&nbsp;<a title="Lloyd Shapley" href="http://en.wikipedia.org/wiki/Lloyd_Shapley">Lloyd Shapley</a>&nbsp;proved that, for any equal number of suitors and acceptors, it is always possible to solve the Stable Marriage Problem.</p>
<p>&nbsp;</p>
<pre>The Gale-Shapely Algorithm:
Each suitor proposes to his highest preferred acceptor. If the acceptor is not already matched, we automatically match suitor to acceptor. If the acceptor is previously matched; acceptor picks the most preferred suitor. The rejected suitor moves on to his next preferred acceptor. When each suitor is matched the problem is solved.</pre>
<h3>Download</h3>
<p>Download&nbsp;<a href="http://www.saipanyam.net/wp-content/downloads/StableMatching.zip" target="_new">source code</a>. It is an implementation of the algorithm in .NET 4 using Visual Studio 2010 and C#.</p>
<pre>
/Here Optimal Entity is the Suitor and Pessimal Entity is the acceptor
//The function that implements the Gale-Shapley algorithm in .NET is shown
public static SortedDictionary&lt;T,U&gt; Match(HashSet&lt;SuitorEntity&lt;T, U&gt;&gt; optimalEntities, HashSet&lt;AcceptorEntity&lt;U, T&gt;&gt; pessimalEntities)
        {
            Dictionary&lt;AcceptorEntity&lt;U, T&gt;, SuitorEntity&lt;T, U&gt;&gt; matching = new Dictionary&lt;AcceptorEntity&lt;U, T&gt;, SuitorEntity&lt;T, U&gt;&gt;();
            Stack&lt;SuitorEntity&lt;T,U&gt;&gt; processStack = new Stack&lt;SuitorEntity&lt;T, U&gt;&gt;(optimalEntities);
            while(processStack.Count&gt;0)
            {

                //Store each suitor in a Stack.
                SuitorEntity&lt;T, U&gt; suitorEntity = processStack.Pop();
                // Match the optimal entity to its first preference
                //If its first preference is not previously matched then automatically match and dequeue
                SuitorEntity&lt;T, U&gt; matchedEntity;
                AcceptorEntity&lt;U, T&gt; acceptorEntity = suitorEntity.Preferences.Dequeue();
                if(!matching.TryGetValue(acceptorEntity,out matchedEntity))
                {
                    matching.Add(acceptorEntity, suitorEntity);
                }
                else//Else
                {
                    foreach (SuitorEntity&lt;T,U&gt; entity in acceptorEntity.Preferences)
                    {
                        if(matchedEntity == entity)
                        {
                            //The Pessimal Entity makes a choice: If it already has a better preference then it keeps it
                            processStack.Push(suitorEntity);
                            break;
                        }
                        // Replace the matching of the acceptor with the most preferred new suitor
                        if (suitorEntity != entity) continue;
                        matching[acceptorEntity] = suitorEntity;
                        //Push the previously matched suitor who is now rejected on to the stack for further processing
                        processStack.Push(matchedEntity);
                        break;
                    }

                }

            }
            SortedDictionary&lt;T,U&gt; result = new SortedDictionary&lt;T, U&gt;();
            foreach (KeyValuePair&lt;AcceptorEntity&lt;U, T&gt;, SuitorEntity&lt;T, U&gt;&gt; keyValuePair in matching)
            {
                result.Add(keyValuePair.Value.Entity,keyValuePair.Key.Entity);
            }
            return result;
        }</pre>
<h3>References</h3>
<p><a title="Stable Marriage Problem" href="http://mathsite.math.berkeley.edu/smp/smp.html" target="_blank">Interactive Flash Demonstration of Stable Marriage Problem</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.saipanyam.net/2011/09/gale-shapley-algorithm.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stochastic Algorithms &#8211; Clever Algorithms in Python</title>
		<link>http://www.saipanyam.net/2011/06/stochastic-algorithms-1.html</link>
		<comments>http://www.saipanyam.net/2011/06/stochastic-algorithms-1.html#comments</comments>
		<pubDate>Sat, 25 Jun 2011 04:50:50 +0000</pubDate>
		<dc:creator>Sai Panyam</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Clever Algorithms]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Stochastic Algorithms]]></category>

		<guid isPermaLink="false">http://www.saipanyam.net/?p=416</guid>
		<description><![CDATA[This is a multi part series on implementing Clever Algorithms by Jason Brownlee in Python. See overview, Part 2. Stochastic Algorithms are primarily global optimization algorithms. A stochastic process is one whose behavior is non-deterministic. The system&#8217;s subsequent state is determined both by the process&#8217; predictable actions and by a random element. The main strategy (with some exceptions) are [...]]]></description>
			<content:encoded><![CDATA[<p>This is a multi part series on implementing <a title="Clever Algorithms" href="http://www.cleveralgorithms.com/" target="_blank">Clever Algorithms</a> by Jason Brownlee in Python. See <a title="Clever Algorithms in Python" href="http://www.saipanyam.net/2011/06/clever-algorithms-python.html">overview</a>, <a title="Stochastic Algorithms : Part 2 – Clever Algorithms in Python" href="http://www.saipanyam.net/2011/06/stochastic-algorithms-2.html">Part 2</a>.</p>
<p>Stochastic Algorithms are primarily global optimization algorithms. A <strong><a title="Stochastic process" href="http://en.wikipedia.org/wiki/Stochastic_process" target="_blank">stochastic process</a></strong> is one whose behavior is non-deterministic. The system&#8217;s subsequent state is determined both by the process&#8217; predictable actions and by a random element. The main strategy (with some exceptions) are based on sampling the search space, calculating the &#8216;cost&#8217; and using that to improve on the result. This can be either through a random process, changing search direction or step size. There is no &#8216;inspiring&#8217; system, either natural or biological on which these are based.  The first part details the implementation in python of four algorithms: Random Search (RS), Adaptive Random Search (ARS), Stochastic Hill Climbing (SHC) and Scatter Search (SC).  Out of these except for Stochastic Hill Climbing , the remaining three use the same objective function for calculating the cost.</p>
<p>The objective function I chose for RS, ARS and SC was a variation on the one provided by Jason. He used a function that was a &#8216;sum of squares&#8221; , I used a variation that would provide a non trivial solution value, while keeping the structure of the function the same.</p>
<div id="attachment_427" class="wp-caption alignnone" style="width: 621px"><img class="size-full wp-image-427  " title="Original Basin Function" src="http://www.saipanyam.net/wp-content/uploads/2011/06/SA-Original.png" alt="Basin Function" width="611" height="263" /><p class="wp-caption-text">Objective function used in Clever Algorithms</p></div>
<p>&nbsp;</p>
<div id="attachment_428" class="wp-caption alignnone" style="width: 623px"><img class="size-full wp-image-428 " title="My Basin Function" src="http://www.saipanyam.net/wp-content/uploads/2011/06/SA-Variation.png" alt="My Basin Function" width="613" height="236" /><p class="wp-caption-text">Objective Function that I used</p></div>
<p>The optimal solution (minimum) for  my basin function can be found at the value -10. The input value would be 2.</p>
<p>For SHC I used the same &#8216;<a title="One Max" href="http://tracer.lcc.uma.es/problems/onemax/onemax.html" target="_blank">One Max</a>&#8216; Problem from the original Clever Algorithms book.</p>
<h3>Download</h3>
<p>Download <a href="http://www.saipanyam.net/wp-content/downloads/CleverAlgorithms.rar" target="_new">source code</a>. Unzip and import the attached folder in to your Eclipse workspace. It includes a test suite for exercising the algorithms</p>
<h3><strong>Random Search (RS)</strong></h3>
<p>Random search has no memory of previous search candidates. So it might revisit previously considered candidate solutions. The advantage is, it is a minimal solution. Its worst case performance is worse than a straight linear approach. But it has its uses in a domain where the values are continuous. Most commonly it is used as an embedded heuristic in other search algorithms for refining a local optima. It is one of the building blocks for other more advanced search techniques.</p>
<h3><strong><strong>Adaptive Random Search (ARS)</strong></strong></h3>
<p>Adaptive Random Search seeks to avoid the problems of localized random search by sampling with larger or smaller step sizes. We keep trying larger step sizes as long as we have improvement in the result. We go back to smaller step sizes if we don&#8217;t see an improvement in the result after a preset max count. The initial starting point is selected similar to that of RS.</p>
<h3><strong>Scatter Search (SC)</strong></h3>
<p>Scatter search is a global optimization algorithm, which has some Evolutionary computation features. The premise of SC is that the desired result is present in some combination of a diverse set of high quality candidate sets. By combining and recombining the values from a reference set of elite solutions to create &#8216;offsprings&#8217;. We then test these offsprings for best values by applying the objective function to them. We use an embedded heuristic of RS for refining a local candidate solution.</p>
<h3><strong>Stochastic Hill Climbing (SHC)</strong></h3>
<p>Stochastic Hill Climbing iterates the process by randomly selecting a neighbor of a local candidate solution and evaluating it. It is an improvement on RS, where we don&#8217;t sample randomly, but near neighbors of randomly selected candidate solution. I noticed an error in the code listing provided by Jason Brownlee. Specifically on page 40 last line. ( mutant[pos] = (mutant[pos]==&#8217;1&#8242;) ? &#8217;0&#8242; : &#8217;1&#8242; ) . It should instead check for &#8217;0&#8242; and replace it with &#8217;1&#8242;. I believe it is a typo in the book. I also tried to evaluate the search efficacy for the OneMax problem. Since the idea is to replace all zeros in the bitstring with 1. A search efficacy metric can be defined as (FinalOneMaxCount &#8211; InitialOneMaxCount)/finalIteration. If we set our max iterations to the length of the initial bitstring, we get a nice metric for measuring the search efficacy.</p>
<h4><strong>Visualization of the two objective functions: </strong></h4>
<div style="width: 620;">
<div style="float: left;">
<div id="attachment_430" class="wp-caption alignleft" style="width: 252px"><img class="size-full wp-image-430 " title="Original Basin Function Graph" src="http://www.saipanyam.net/wp-content/uploads/2011/06/SA-OriginalFunction.png" alt="Original Basin Function Graph" width="242" height="342" /><span style="font-size: 11px; line-height: 17px;">Visualizing the original basin function</span></dt>
</dl>
</div>
<div style="float: right;">
<dl id="attachment_432" class="wp-caption alignright" style="width: 323px;">
<dt class="wp-caption-dt"><img class="size-full wp-image-432 " title="My Basin Function Graph" src="http://www.saipanyam.net/wp-content/uploads/2011/06/SA-Function1.png" alt="My Basin Function Graph" width="313" height="643" /><p class="wp-caption-text">Visualizing my basin function</p></div>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.saipanyam.net/2011/06/stochastic-algorithms-1.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clever Algorithms in Python</title>
		<link>http://www.saipanyam.net/2011/06/clever-algorithms-python.html</link>
		<comments>http://www.saipanyam.net/2011/06/clever-algorithms-python.html#comments</comments>
		<pubDate>Sat, 25 Jun 2011 03:11:41 +0000</pubDate>
		<dc:creator>Sai Panyam</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Clever Algorithms]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.saipanyam.net/?p=408</guid>
		<description><![CDATA[Ever since I got hold of Clever Algorithms &#8211; Nature Inspired Programming Recipes by Jason Brownlee, I had a desire to assimilate it. Jason has done us a great service by researching, collating and proposing a unified template for understanding &#8220;Nature inspired algorithms&#8221;.  The nature of the subject itself spans varied fields, is relatively new, [...]]]></description>
			<content:encoded><![CDATA[<p>Ever since I got hold of <a title="Clever Algorithms" href="http://www.cleveralgorithms.com/" target="_blank">Clever Algorithms</a> &#8211; Nature Inspired Programming Recipes by Jason Brownlee, I had a desire to assimilate it. Jason has done us a great service by researching, collating and proposing a unified template for understanding &#8220;Nature inspired algorithms&#8221;.  The nature of the subject itself spans varied fields, is relatively new, fragmented, incomplete, spread across various papers and is not amenable to understand as a whole. So I was naturally (no pun intended) excited when I saw this book.</p>
<p>My first attempt at reading through it was frustrating to say the least. It was not Jason&#8217;s writing style per-se, but the nature of the subject itself. It is not amenable for reading as a programming book. Jason himself cautions in the first paragraph: &#8220;rather than being read cover to cover&#8221;, it is a handbook and a technique guide-book. In-spite of that warning I plunged in trying to gather as much as possible. Only later I realized that to make this knowledge my own, I needed to go slow and experiment with each algorithm. But blindly copying what he had done, would be of no avail.</p>
<p>So I set myself up with the following goals:</p>
<p><strong>Goal 1:</strong> I will try to implement the algorithms in a language that I have no familiarity with.</p>
<p><strong>Goal 2:</strong> I will try to stick to the original pseudo code as far as possible to increase my understanding of the technique</p>
<p><strong>Goal 3:</strong> I will try to question and verify every line in the code listing provided by him, so that my implementation would be from understanding, rather than duplicating, or worse copying.</p>
<p><strong>Goal 4:</strong> Have an alternate (or accompanying, if you will) source for people who come across this book, with more contextual information on implementing these algorithms. (sort of standing on the shoulders of giants!)</p>
<p><strong>Goal 5:</strong> Provide a narrative of my experience, implementing these excellent algorithmic techniques.</p>
<p>To realize <strong>goal 1</strong>, I chose python as the language to implement the algorithms. As you can see I am a .NET guy throughout my career. So trying to implement the algorithms in python would force me to re-evaluate every line of code that I write. The problem is compounded by the fact that Jason&#8217;s original code listing is in Ruby. I had to learn just enough Ruby to understand <strong>his </strong>code and translate that in to python!. This has a dual advantage: one i get to learn a new language while applying it to a non trivial problem, two it forced me to look at each line of code from an algorithmic stand point.</p>
<p>To realize <strong>goal 2</strong>, I changed my implementation functions and structure to reflect the pseudo code listing that he provided. This makes it easy to follow how the pseudo code translates to implementation. In all fairness to Jason, he did a great job of it. But I wanted to take it one step further and make it more consumable. The subject matter is hard enough, I wanted to remove any further obstacles to assimilating this seminal work from Jason.</p>
<p>To realize <strong>goal 3</strong>, I changed some of the objective functions that he provided to others where possible. I also made some changes to some data structures and input variables to further kick the tires. I also included a test suite that exercises the algorithms. So anyone who just want to see how the algorithms behave for different inputs, can do so easily. I also put in a lot more comments in places where I ran in to difficulties. I hope it would make it more valuable to someone trying to follow along.</p>
<p>To realize <strong>goal 4</strong>, I want people to see how the algorithms play out in a different language. By writing this in a language that I am unfamiliar with, I hope it gives one confidence to attempt them in your language of choice. Each .py file also has a header which lays out the Name, Taxonomy, Strategy and Heuristics of the algorithm. (This is mostly from Jason&#8217;s Clever Algorithms book and algorithm template that he designed). The reason I chose to do so was, while understanding one algorithm, I wanted the code and the algorithm context at the same place. I found that very helpful in understanding and assimilating each algorithm.</p>
<p>To realize<strong> goal 5</strong>, I would be blogging about this. His 45 algorithms are divided in to <a title="Stochastic Algorithms – Clever Algorithms in Python" href="http://www.saipanyam.net/2011/06/stochastic-algorithms-1.html">Stochastic Algorithms</a>, Evolutionary Algorithms, Physical Algorithms, Probabilistic Algorithms, Swarm Algorithms, Immune Algorithms and Neural Algorithms. As I finish implementing each category of algorithms, I will write a blog describing it.</p>
<p>I would like to sincerely thank Jason Brownlee for making available his Clever Algorithms. (By the way, Jason Brownlee did his Phd from the same university that I went to: Swinburne University Melbourne (I am from class of 2000)</p>
<p>Note: I tried as far as possible to write the code in a &#8216;pythonic&#8217; way. Since I was learning python for this, I would like to beg forgiveness in advance from expert python developers. Any suggestions are always welcome to improve my code.</p>
<p>I am using <a title="Python 2.7.2" href="http://python.org/download/releases/2.7.2/" target="_blank">Python 2.7.2</a> with <a title="Eclipse IDE" href="http://www.eclipse.org/downloads/packages/eclipse-ide-java-developers/indigor" target="_blank">Eclipse IDE for Java Developers</a> Version: Helios Service Release 2. I have the <a title="PyDev Plugin for Eclipse" href="http://pydev.org/updates" target="_blank">PyDev</a> ver 2.1.0xxx plugin for eclipse to work in python.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.saipanyam.net/2011/06/clever-algorithms-python.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Algorithms in Computational Geometry – Part 2</title>
		<link>http://www.saipanyam.net/2010/04/computational-geometry-part-2.html</link>
		<comments>http://www.saipanyam.net/2010/04/computational-geometry-part-2.html#comments</comments>
		<pubDate>Fri, 09 Apr 2010 05:01:58 +0000</pubDate>
		<dc:creator>Sai Panyam</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Computational Geometry]]></category>
		<category><![CDATA[Expression Design]]></category>

		<guid isPermaLink="false">http://www.saipanyam.net/?p=277</guid>
		<description><![CDATA[In Part 1 we discussed the base technique for determining relative orientation. We used that to answer the first two questions: To find relative orientation of two points and two directed segments with a common end point. In Part 2 we answer the next two questions: Given two line segments p0p1 and p1p2, if we [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.saipanyam.net/2010/04/computational-geometry-part-1.html">Part 1</a> we discussed the base technique for determining relative orientation. We used that to answer the first two questions: To find relative orientation of two points and two directed segments with a common end point. In Part 2 we answer the next two questions:</p>
<ul>
<li>Given two line segments p<sub>0</sub>p<sub>1</sub> and p<sub>1</sub>p<sub>2</sub>, if we traverse from p<sub>0</sub> to p<sub>2</sub>, did we make a left, right or no turn at p<sub>1</sub>?</li>
<li>Do line segments p<sub>1</sub>p<sub>2</sub> and p<sub>3</sub>p<sub>4</sub> intersect?</li>
</ul>
<p>We build on what we learned in <a href="http://www.saipanyam.net/2010/04/computational-geometry-part-1.html">Part 1</a>, the <strong>cross product</strong>. </p>
<p>Download the demo application <a href="http://www.saipanyam.net/code-center/computational-geometry">here</a></p>
<p><strong>Determining whether consecutive segments turn left or right</strong></p>
<p>Given two line segments p<sub>0</sub>p<sub>1</sub> and p<sub>1</sub>p<sub>2</sub> we simply check whether the directed segment p<sub>0</sub>p<sub>2</sub> is clockwise or counterclockwise relative to directed segment p<sub>0</sub>p<sub>1</sub>. This is similar to the solution to question 2 in <a href="http://www.saipanyam.net/2010/04/computational-geometry-part-1.html">Part 1</a>. If the cross product is negative, then p<sub>0</sub>p<sub>2</sub> is counterclockwise to p<sub>0</sub>p<sub>1</sub>. Hence we should turn <strong>left</strong> when we reach p<sub>1</sub> to reach p<sub>2</sub> while traversing p<sub>0</sub>, p<sub>1</sub> and p<sub>2</sub>. If the cross product is <strong>0</strong> (boundary condition) then it means all the three points are <strong>collinear</strong> (on the same line). The image below shows the three possible scenarios<br />
<div id="attachment_287" class="wp-caption alignnone" style="width: 610px"><img src="http://www.saipanyam.net/wp-content/uploads/2010/04/Consecutive-Segments1-e1270768161354.png" alt="Consecutive Segments Cross Product" title="Consecutive Segments" width="600" height="375" class="size-full wp-image-287" /><p class="wp-caption-text">Using the cross product to determine how p0p1 and p1p2 turn at p1</p></div></p>
<p><strong>Determining whether two line segments intersect</strong></p>
<p>Two line segments intersect if and only if either or both of the following conditions are true:</p>
<ul>
<li>Each line segment straddles the other line segment.</li>
<li>An end point of one line segment is on the other line segment</li>
</ul>
<p>A line segment p<sub>1</sub>p<sub>2</sub> <strong>straddles</strong> another line if p<sub>1</sub> and p<sub>2</sub> are on opposite sides of the line. A boundary condition occurs when one of the end points is <strong>on</strong> the other line.</p>
<p><strong>Algorithm</strong></p>
<p>Calculate the orientation (using cross product!) d<sub>i</sub> for each point of one segment w.r.t the end points of the other segment. For line segments p<sub>1</sub>p<sub>2</sub> and p<sub>3</sub>p<sub>4</sub> we will get d<sub>1</sub>, d<sub>2</sub>, d<sub>3</sub> and d<sub>4</sub>.</p>
<p>if none of the d<sub>i</sub> are collinear (i.e. d<sub>i</sub> !=0) we check if d<sub>1</sub> and d<sub>2</sub> <strong>and</strong> d<sub>3</sub> and d<sub>4</sub> have opposite orientations (if one is clockwise,other should be counterclockwise). If this condition is true then we know that the line segments <strong>straddle</strong> each other and hence <strong>intersect</strong>. If it is false we can straight away say they <strong>don&#8217;t intersect</strong>.</p>
<p>If any d<sub>i</sub> is collinear (boundary condition) and the corresponding p<sub>i</sub> is <strong>on</strong> the other line segment, the lines <strong>intersect</strong>.<br />
<div id="attachment_306" class="wp-caption alignnone" style="width: 610px"><img src="http://www.saipanyam.net/wp-content/uploads/2010/04/Intersects-e1270789093105.png" alt="Intersect cases" title="Intersects" width="600" height="375" class="size-full wp-image-306" /><p class="wp-caption-text">Shows the different cases that we encounter visually</p></div></p>
<pre>
bool Intersects(p<sub>1</sub>, p<sub>2</sub>, p<sub>3</sub>, p<sub>4</sub>)
{
    d<sub>1</sub> = CrossProduct (p<sub>1</sub>p<sub>3</sub>, p<sub>1</sub>p<sub>2</sub>)
    d<sub>2</sub> = CrossProduct (p<sub>1</sub>p<sub>4</sub>, p<sub>1</sub>p<sub>2</sub>)
    d<sub>3</sub> = CrossProduct (p<sub>3</sub>p<sub>1</sub>, p<sub>3</sub>p<sub>4</sub>)
    d<sub>4</sub> = CrossProduct (p<sub>3</sub>p<sub>2</sub>, p<sub>3</sub>p<sub>4</sub>)

    if( ((d<sub>1</sub> > 0 and d<sub>2</sub><0) or (d<sub>2</sub> > 0 and d<sub>1</sub><0)) <strong>and </strong> ((d<sub>3</sub> > 0 and d<sub>4</sub><0) or (d<sub>4</sub> > 0 and d<sub>3</sub><0)))
    {
      then return <strong>true</strong>
    }
    else if (d<sub>1</sub> = 0 <strong>and</strong> PointOnLine (p<sub>3</sub>, p<sub>4</sub>, p<sub>1</sub>))
    {
       then return <strong>true</strong>
    }
    else if (d<sub>2</sub> = 0 <strong>and</strong> PointOnLine (p<sub>3</sub>, p<sub>4</sub>, p<sub>2</sub>))
    {
       then return <strong>true</strong>
    }
    else if (d<sub>3</sub> = 0 <strong>and</strong> PointOnLine (p<sub>1</sub>, p<sub>2</sub>, p<sub>3</sub>))
    {
       then return <strong>true</strong>
    }
    else if (d<sub>4</sub> = 0 <strong>and</strong> PointOnLine (p<sub>1</sub>, p<sub>2</sub>, p<sub>4</sub>))
    {
       then return <strong>true</strong>
    }
    else
    {
       return <strong>false</strong>
    }
}

bool PointOnLine (p<sub>i</sub>, p<sub>j</sub>, p<sub>k</sub>)
{
    if ( Min (x<sub>i</sub>, x<sub>j</sub>)<= x<sub>k</sub> <= Max (x<sub>i</sub>, x<sub>j</sub>) <strong>and</strong> Min (y<sub>i</sub>, y<sub>j</sub>)<= y<sub>k</sub> <= Max (y<sub>i</sub>, y<sub>j</sub>) )
    {
        return <strong>true</strong>
    }
    else
    {
        return <strong>false</strong>
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.saipanyam.net/2010/04/computational-geometry-part-2.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Algorithms in Computational Geometry &#8211; Part 1</title>
		<link>http://www.saipanyam.net/2010/04/computational-geometry-part-1.html</link>
		<comments>http://www.saipanyam.net/2010/04/computational-geometry-part-1.html#comments</comments>
		<pubDate>Thu, 08 Apr 2010 18:52:32 +0000</pubDate>
		<dc:creator>Sai Panyam</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[.NET 3.5]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Computational Geometry]]></category>
		<category><![CDATA[Expression Design]]></category>

		<guid isPermaLink="false">http://www.saipanyam.net/?p=219</guid>
		<description><![CDATA[Computational Geometry (CG) deals with algorithms for solving geometric problems. It is used in computer graphics, robotics, computer aided design,statistics among others. A typical CG problem takes as input a set of geometric objects like a set of points, a set of line segments etc. The output is most commonly finding certain attributes of the [...]]]></description>
			<content:encoded><![CDATA[<p>Computational Geometry (CG) deals with algorithms for solving geometric problems. It is used in computer graphics, robotics, computer aided design,statistics among others. A typical CG problem takes as input a set of geometric objects like a set of points, a set of line segments etc. The output is most commonly finding certain attributes of the geometric objects. For e.g. we are interested in answering the following questions in two dimensions (in a plane):</p>
<ol>
<li>Given two points p<sub>1</sub> &amp; p<sub>2</sub> in a co-ordinate plane, is the directed segment p<sub>0</sub>p<sub>1</sub> clockwise, counterclockwise or colinear to directed segment p<sub>0</sub>p<sub>2</sub>? Where p<sub>0</sub> is the <em>origin</em> of the co-ordinate plane</li>
<li>Given two directed segments p<sub>0</sub>p<sub>1</sub> and p<sub>0</sub>p<sub>2</sub>, is p<sub>0</sub>p<sub>1</sub> clockwise, counterclockwise or colinear to p<sub>0</sub>p<sub>2</sub> with respect to the common end point p<sub>0</sub>?</li>
<li>Given two line segments p<sub>0</sub>p<sub>1</sub> and p<sub>1</sub>p<sub>2</sub>, if we traverse from p<sub>0</sub> to p<sub>2</sub>, did we make a left, right or no turn at p<sub>1</sub>?</li>
<li>Do line segments p<sub>1</sub>p<sub>2</sub> and p<sub>3</sub>p<sub>4</sub> intersect?</li>
</ol>
<p>Download the demo application <a href="http://www.saipanyam.net/code-center/computational-geometry">here</a></p>
<p>Before we proceed any further a few definitions. <strong>Clockwise </strong>and <strong>Counterclockwise </strong>are intuitively easy to understand. They have the usual colloquial meaning. There is one thing to note though. A co-ordinate plane is not a <em>watch face</em>! Here we are determining the <em>relative orientations</em> of one segment w.r.t the other. Instead of trying to explain it in words, I will show you a picture (should replace a thousand words!).</p>
<div style="float: left;">
<div id="attachment_225" class="wp-caption alignnone" style="width: 310px"><img class="size-medium wp-image-225" title="Orientation" src="http://www.saipanyam.net/wp-content/uploads/2010/04/Orientation-300x225.png" alt="Orientation" width="300" height="225" /><p class="wp-caption-text">The darkly shaded orientation region contains vectors counterclockwise relative to p. The lightly shaded region contains vectors clockwise to p </p></div>
</div>
<p>Two vectors are <strong>colinear</strong> if they are pointing in the same or opposite direction. In the picture all vectors that lie along the diagonal will be colinear to p.</p>
<p>With definitions out of the way, let us proceed to answer the initial queries that we posed. A brute force method of computing whether two line segments intersect, would be to find the line equations of the form y=mx + c where m is the slope and c the y-intercept and then compute the point of intersection, and verify whether this point lies on both lines. This involves a lot of expensive computational resources. Further this involves division which is sensitive to round-off errors depending upon the precision of the division operation. For e.g. almost parallel line segments will give incorrect results.</p>
<p>The algorithms given here will only use additions, multiplications, subtractions and comparisons ! No trigonometry also !<br />
We do this by computing the <strong>cross product</strong>. This is a fundamental technique that is at the base of most CG algorithms. Let me say that again. <strong>Cross Product</strong> is a most fundamental and important technique for solving CG problems. A <strong>cross product</strong> p<sub>1</sub> X p<sub>2</sub> is defined as the determinant of the matrix comprising of x and y values of the points.</p>
<div style="float: left;">
<div id="attachment_255" class="wp-caption alignnone" style="width: 310px"><img class="size-medium wp-image-255" title="Determinant of Matrix" src="http://www.saipanyam.net/wp-content/uploads/2010/04/Determinant1-300x225.png" alt="Determinant" width="300" height="225" /><p class="wp-caption-text">Determinant of the above matrix will be equal to (x1y2-x2y1)</p></div>
</div>
<p>If the <strong>cross product </strong>is positive then p<sub>1</sub> is clockwise to p<sub>2</sub>. A boundary condition occurs if the cross product is <strong>0</strong>. In that case p<sub>1</sub> and p<sub>2</sub> are <strong>colinear</strong>.</p>
<p><strong>Proof</strong>: We use trigonometric function <strong>tan</strong> on the angle formed by the point (x,y), origin (0,0) and (x,0) for both the points. If the ratio of one tangent to other determines orientation depending upon whether the value is greater than 1 or not.</p>
<pre>//Clockwise:
x1y2-x2y1&gt;0

//So
x1y2&gt;x2y1

//alternatively
(x1y2)/(x2y1)&gt;1

//rearranging the terms
(y2/x2)/(y1/x1)&gt;1

//Notice that tan θ is the ratio of opposite side by adjacent side
//in a right-angled triangle
//so the numerator of the above fraction is tan θ<sub>2</sub> and
//denominator tan θ<sub>1</sub>

(tan θ<sub>2</sub>)/(tan θ<sub>1</sub>)&gt;1

<strong>If the angle θ<sub>2</sub> is greater than θ<sub>1</sub>
then we have proved that p<sub>1</sub> is clockwise to p<sub>2</sub></strong></pre>
<p>The above technique of using cross product makes for an easy and efficient way to answer <strong>Question 1</strong>.<br />
To answer <strong>Question 2</strong> just involves an extra pre-processing step before doing the cross product. To determine whether two directed segments p<sub>0</sub>p<sub>1</sub> and p<sub>0</sub>p<sub>2</sub>, is p<sub>0</sub>p<sub>1</sub> clockwise, counterclockwise or colinear to p<sub>0</sub>p<sub>2</sub> with respect to the common end point p<sub>0</sub> we just translate the axis to use p<sub>0</sub> as the origin and use the cross product as above.</p>
<pre>// To translate the origin to the common end point p<sub>0</sub>
//We let p<sub>1</sub>' (p prime) be the point where 

x<sub>1</sub>' =x<sub>1</sub> - x<sub>0</sub> and
y<sub>1</sub>' =y<sub>1</sub> - y<sub>0</sub>

//We do the above for  p<sub>2</sub> and calculate its prime: p<sub>2</sub>' 

x<sub>2</sub>' =x<sub>2</sub> - x<sub>0</sub> and
y<sub>2</sub>' =y<sub>2</sub> - y<sub>0</sub>

//Then we calculate the cross product of p<sub>1</sub>' x p<sub>2</sub>' 

<strong>If it is positive then the directed segment p<sub>0</sub>p<sub>1</sub> is clockwise to
directed segment p<sub>0</sub>p<sub>2</sub></strong></pre>
<p>In <a href="http://www.saipanyam.net/2010/04/computational-geometry-part-2.html">Part 2</a> we will answer <strong>questions 3 &amp; 4</strong> using the techniques and principles learned here.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.saipanyam.net/2010/04/computational-geometry-part-1.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

