Understanding the Wolfram Demonstration "Distance of a Point to a Polygon"

162 Views Asked by At

I've recently came across a neat Wolfram Demonstration script by Jaime Rangel-Mondragon that calculates the minimum distance from a point to an arbitrary convex or non-convex polygon:

http://demonstrations.wolfram.com/DistanceOfAPointToAPolygon/

Here's the basic script that computes point-to-polygon distances:

dis[{a_, b_}, p_] := Module[{pz, az, bz, z},
  If[a == b, {a, Norm[p - a]},
   {pz, az, bz} = Map[First[#] + I Last[#] &, {p, a, b}];
   z = (pz - az)/(bz - az);
   If[Not[0 <= Re[z] <= 1], d1 = Norm[p - a]; d2 = Norm[p - b]; 
    If[d1 < d2, {a, d1}, {b, d2}],
    {a + Re[z] (b - a), Norm[Im[z] (b - a)]}]]]

p = {1, 1};
poli = {{-3, -3}, {0, -1}, {3, -1}, {3, 3}, {0, 1}, {-2, 1}};

f = Map[dis[#, p] &, Partition[poli, 2, 1, 1]];
{closestPointOnPolygon, distPointToPolygon} = First[Sort[f, Last[#1] <= Last[#2] &]]

Where we provide two inputs, the first being an arbitrary two-dimensional point p, and the second being a 2D polygon poli. This then yields two outputs, closestPointOnPolygon and distPointToPolygon (or c and d, respectively, in the author's original notation).

I read through the source code, and looked through the notes, however, I'm still not sure if I understand what the author is doing. Would anyone here be able to provide a higher level description of what the author is doing?

1

There are 1 best solutions below

0
On

The main part is dis[{a_, b_}, p_] which finds the distance from point $p$ to the line segment $[a,b]$. It does so with complex arithmetics, by using a complex linear transformation that sends $a$ to $0$ and $b$ to $1$. Let $p'$ be the image of $p$ under this transformation. $\DeclareMathOperator{\re}{Re}$

  • If $\re p'<0$, then $0$ is the closest point to $p'$. Hence $a$ is the closest point to $p$.
  • If $\re p'>0$ is greater than $1$, then $1$ is the closest point to $p'$. Hence $b$ is the closest point to $p$.
  • Otherwise, $\re p'$ is the closest point on $[0,1]$ to $p'$. From here one determines the closest point on $[a,b]$ to $p$.

The very last line applies the above to every side of the polygon, and takes the smallest distance.

Important: this algorithm returns the distance to the boundary of polygon, not to the polygon itself. If $p$ is outside of the polygon, there is no difference. But if $p$ is inside the polygon, the algorithm returns a positive number (distance to the boundary) instead of $0$.