7. Computational Geometry I

Introduction

Be aware of:

This course simplifies this by using integer cartesian grids and avoiding division, square roots, trig etc.

Sidenote - basic matplotlib example:

import matplotlib.pyplot as plt
vertices = [(0,0), (1,2), (2,4)]
vx, vy = zip(*vertices) # Unzip the array into x and y components
axes = plt.axes()
axes.plot(vx, vy, color="blue", marker="o")
plt.show()

Points, Vectors & Lines

Definitions

Point:

Vector:

Basic Operations

Points:

Vectors:

Vector Operations

Dot Product:

Signed Area/Turn Direction

The area of parallelogram is:

pxqypyqx=pqsinθ p_x q_y-p_y q_x=|p\|q|\sin{\theta}

This is equivalent to the magnitude of the cross product where pp, qq are two edge vectors for vectors BB and CC respectively, relative to the point AA.

The area of triangle is half of this.

The area is positive if bb is ‘counterclockwise’ to cc, centered around aa and zero when the points are collinear (parallel).

Checking if PP is on the line (A,B)(A,B):

Turn Direction:

Line Segment Intersection:

Degenerate cases:

Simple Polygons

By convention, vertices are in counter-clockwise order.

Convex Polygons:

Point Inclusion Test

Convex Polygon

For a convex polygon, a point is in a polygon (PiP) if it is on the left side of every edge for an anticlockwise traversal of the polygon:

all([isCCW(vertex[i], vertex[(i + 1) % len(vertex)], P) for i in range(len(vertex))])

Simple Polygon

Special cases:

The correct way to solve this is to:

The hacky solution: all vertices are on an integer grid, so simply move PP up by a very small amount (e.g. 10810^{-8}).

Improvements:

Convex Hull Problem

For a finite set of points, the convex hull is the smallest convex polygon enclosing all points. The convex hull:

Naïve solution:

Gift Wrap Algorithm

Graham-Scan Algorithm

An O(nlogn)O(n\log{n}) algorithm. First construct a simple closed path that includes all points:

Sorting without calculating angles

We don’t need to know the angle: only the ordering. This can be done using isCCW, Python’s built in sort function (which will be nlognn\log{n}), and from functools import cmp\_to\_key or by defining a SortKey class with a custom __lt__ operator and converting the point to that class in the sort function’s key lambda.

Consider edge cases:

Concavities:

Initialize a stack with [P0,P1,P2][P_0, P_1, P_2]:

Complexity: