Computational Geometry in Python
Computational Geometry is a field of mathematics that seeks the development of efficient algorithms to solve problems described in terms of basic geometrical objects. We differentiate between Combinatorial Computational Geometry and Numerical Computational Geometry.
-
Combinatorial Computational Geometry deals with interaction of basic geometrical objects: points, segments, lines, polygons, and polyhedra. In this setting we have three categories of problems:
-
Static Problems: The construction of a known target object is required from a set of input geometric objects.
-
Geometric Query Problems: Given a set of known objects (the search space) and a sought property (the query), these problems deal with the search of objects that satisfy the query.
-
Dynamic Problems: Similar to problems from the previous two categories, with the added challenge that the input is not known in advance, and objects are inserted or deleted between queries/constructions.
-
-
Numerical Computational Geometry deals mostly with representation of objects in space described by means of curves, surfaces, and regions in space bounded by those.
Before we proceed to the development and analysis of the different algorithms in those two settings, it pays off to explore the basic background: Plane Geometry.
Plane Geometry
The basic Geometry capabilities are usually treated through the Geometry module
of the sympy
libraries. Rather than giving an academical description of all
objects and properties in that module, we discover the most useful ones through
a series of small self-explanatory python
sessions.
Points, Segments
We start with the concepts of point and segment. The aim is to illustrate how easily we can check for collinearity, compute lengths, midpoints, or slopes of segments, for example. We also show how to quickly compute the angle between two segments, as well as deciding whether a given point belongs to a segment or not. The next diagram illustrates an example, which we follow up with code.
Lines
The next logical geometrical concept is the line. We can perform more interesting operations with lines, and to that effect we have a few more constructors. We can find their equations, compute the distance between a point and a line, and many other operations.
Circles
The next geometrical concept we are to explore is the circle. We may define a circle by its center and radius, or by three points on it. We can easily compute all of its properties.
Computing intersections with other objects, checking whether a line is tangent to a circle, or finding the tangent lines through an non-interior point, are simple tasks too:
Triangles
The most useful basic geometric concept is the triangle. We need robust and fast algorithms to manipulate and extract information from them. Let us show first the definition of one, together with a series of queries to describe its properties:
Next, note how easily we can obtain representation of the different segments, centers, and circles associated with triangles, as well as the medial triangle (the triangle with vertices at the midpoints of the segments).
Some other interesting operations with triangles:
- Intersection with other objects
- Computation of the minimum distance from a point to each of the segments.
- Checking whether two triangles are similar.
The other basic geometrical objects currently coded in the Geometry module are
LinearEntity
. This is a superclass (which we never use directly), with three subclassesSegment
,Line
andRay
.
LinearEntity
enjoys the following basic methods:
are_concurrent(o1, o2, ..., on)
are_parallel(o1, o2)
are_perpendicular(o1, o2)
parallel_line(self, Point)
perpendicular_line(self, Point)
perpendicular_segment(self, Point)
Ellipse
. An object with a center, together with horizontal and vertical radii.Circle
is, as a matter of fact, a subclass ofEllipse
with both radii equal.Polygon
. A superclass we can instantiate by listing a set of vertices. Triangles are a subclass ofPolygon
, for example. The basic methods ofPolygon
are
area
perimeter
centroid
sides
vertices
RegularPolygon
. This is a subclass ofPolygon
, with extra attributes:
apothem
center
circumcircle
exterior_angle
incircle
interior_angle
radius
For more information about this module, refer to the officialsympy
documentation at docs.sympy.org/dev/modules/geometry.html
Curves
There is also a non-basic geometric object: A Curve
, which we define by
providing parametric equations, together with the interval of definition of the
parameter. It currently does not have many useful methods, other than those
describing its constructors. Let us illustrate how to deal with these objects.
For example, a three-quarters arc of an ellipse could be coded as follows:
Affine Transformations
To end the exposition on basic objects from the geometry module in the sympy
library, we must mention that we may apply any basic affine transformations to
any of the previous objects. This is done by combination of the methods
reflect
, rotate
, translate
and scale
.
With these basic definitions and operations, we are ready to address more complex situations. Let us explore these new challenges next.
Combinatorial Computational Geometry
Also called algorithmic geometry, the applications of this field are plenty: in robotics, these are used to solve visibility problems, and motion planning, for instance. Similar applications are employed to design route planning or search algorithms in geographic information systems (GIS).
Let us describe the different categories of problems, making emphasis on the
tools for solving them that are available in the scipy
stack.
Static Problems
The fundamental problems in this category are the following:
- Convex hulls: Given a set of points in space, find the smallest convex polyhedron containing them.
- Voronoi diagrams: Given a set of points in space (the seeds), compute a partition in regions consisting of all points closer to each seed.
- Triangulations: Partition the plane with triangles, in a way that two triangles are either disjoint, or otherwise they share an edge or a vertex. There are different triangulations depending on the input objects, or constraints on the properties of the triangles.
- Shortest paths: Given a set of obstacles in a space, and two points, find the shortest path between the points that does not intersect any of the obstacles.
The problems of computation of convex hulls, basic triangulations, and Voronoi diagrams are intimately linked. The theory that explains this beautiful topic is explained in detail in a monograph in Computer Science titled Computational Geometry, written by Franco Preparata and Michael Shamos. It was published by Springer-Verlag in 1985.
Convex Hulls
While it is possible to compute the convex hull of a reasonably large set of
points in the plane through the geometry module of the library sympy
, this is
not recommendable. A much faster and reliable code is available in the module
scipy.spatial
through the routine ConvexHull
, which is in turn a wrapper to
qconvex
, from the Qhull
libraries www.qhull.org. This
routine also allows the computation of convex hulls in higher dimensions. Let
us compare both methods, with the famous Lake Superior polygon,
superior.poly
.
poly
files represent planar straight line graphs—a simple list of vertices and edges, together with information about holes and concavities, in some cases. The running example can be downloaded from people.math.sc.edu/blanco/superior.poly. It contains a polygonal description of the coastline of Lake Superior, with 7 holes (for the islands), 518 vertices, and 518 edges. For a complete description of thepoly
format, refer to www.cs.cmu.edu/~quake/triangle.poly.html. With that information, we can write a simple reader without much effort. This is an example:
Voronoi Diagrams
Computing the Voronoi diagram of a set of vertices (our seeds) can be done
with the routine Voronoi
(and its companion voronoi_plot_2d
for
visualization) from the module scipy.spatial
. The routine Voronoi
is in
turn a wrapper to the function qvoronoi
from the Qhull
libraries, with the
following default qvoronoi
controls: qhull_option='Qbb Qc Qz Qx'
if the
dimension of the points is greater than 4, and qhull_options='Qbb Qc Qz'
otherwise. For the computation of the furthest-site Voronoi diagram, instead
of the nearest-site, we would use the extra control Qu
.
- The small dots are the original seeds with
x
-coordinates between0.45
and0.50
, andy
-coordinates between-0.40
and-0.35
. We access those values either from the original listvertices_ls
, or fromvor.points
. - The plane gets partitioned into different regions (the Voronoi cells), one for
each seed. These regions contain all points in the plane which are closest to
its seed. Each region receives an index, which is not necessarily the same
index as the index of its seed in the
vor.points
list. To access the corresponding region to a given seed, we usevor.point_region
.
- Each Voronoi cell is defined by its delimiting vertices and edges (also known
as ridges in Voronoi jargon). The list with the coordinates of the computed
vertices of the Voronoi diagram can be obtained with
vor.vertices
. These vertices were represented as bigger dots in the previous image, and are easily identifiable because they are always at the intersection of at least two edges — while the seeds have no incoming edges.
- For each of the regions, we can access the set of delimiting vertices with
vor.regions
. For instance, to obtain the coordinates of the vertices that delimit the region around the 4th seed, we could issue
Care must be taken with the previous step: Some of the vertices of the Voronoi
cells are not actual vertices, but lie at infinity. When this is the case,
they are identified with the index -1
. In this situation, to provide an
accurate representation of a ridge of these characteristics we must use the
knowledge of the two seeds whose contiguous Voronoi cells intersect on said
ridge—since the ridge is perpendicular to the segment defined by those two
seeds. We obtain the information about those seeds with vor.ridge_points
The first entry of vor.ridge_points
can be read as follows: There is a ridge
perpendicular to both the first and second seeds.
There are other attributes of the object vor
that we may use to inquire
properties of the Voronoi diagram, but the ones we have described should be
enough to replicate the previous image. We leave this as a nice exercise:
- Gather the indices of the seeds from
vor.points
that have theirx
- andy
-coordinates in the required window. Plot them. - For each of those seeds, gather information about vertices of their corresponding Voronoi cells. Plot those vertices not at the infity with a different style as the seeds.
- Gather information about the ridges of each relevant region, and plot them as simple thin segments. Some of the ridges cannot be represented by their two vertices. In that case, we use the information about the seeds that determine them.
Triangulations
A triangulation of a set of vertices in the plane is a division of the convex hull of the vertices into triangles, satisfying one important condition. Any two given triangles:
- must be disjoint, or
- must intersect only at one common vertex, or
- must share one common edge.
These plain triangulations have not much computational value, since some of its triangles might be too skinny — this leads to uncomfortable rounding errors, or computation or erroneous areas, centers, etc. Among all possible triangulations, we always seek one where the properties of the triangles are somehow balanced.
With this purpose in mind, we have the Delaunay triangulation of a set of vertices. This triangulation satisfies an extra condition: None of the vertices lies in the interior of the circumcircle of any triangle. We refer to triangles with this property as Delaunay triangles.
For this simpler setting, in the module scipy.spatial
, we have the routine
Delaunay
, which is in turn a wrapper to the function qdelaunay
from the
Qhull
libraries, with the qdelaunay
controls set exactly as for the Voronoi
diagram computations.
It is possible to generate triangulations with imposed edges too. Given a collection of vertices and edges, a constrained Delaunay triangulation is a division of the space into triangles with those prescribed features. The triangles in this triangulation are not necessarily Delaunay.
We can accomplish this extra condition sometimes by subdivision of each of the imposed edges. We call this triangulation conforming Delaunay, and the new (artificial) vertices needed to subdivide the edges are called Steiner points.
A constrained conforming Delaunay triangulation of an imposed set of vertices and edges satisfies a few more conditions, usually setting thresholds on the values of angles or areas of the triangles. This is achieved by introducing a new set of Steiner points, which are allowed anywhere, not only on edges.
To achieve these high-level triangulations, we need to step outside of the
scipy
stack. We have apython
wrapper to the amazing implementation of mesh generators www.cs.cmu.edu/~quake/triangle.html by Richard Shewchuck . This wrapper, together with examples and other related functions, can be installed by issuing pip install triangle For more information on this module, refer to the documentation online from its author, Dzhelil Rufat, at dzhelil.info/triangle/index.html
Let us compute those different triangulations for our running example. We use
once again the poly
file with the features of Lake Superior, which we read
into a dictionary with all the information about vertices, segments and holes.
The first example is that of the constrained Delaunay triangulation (cndt
).
We accomplish this task with the flag p
(indicating that the source is a
planar straight line graph, rather than a set of vertices).
The next step is the computation of a conforming Delaunay triangulation
(cfdt
). We enforce Steiner points on some segments to ensure as many Delaunay
triangles as possible. We achieve this with extra flag D
.
>>> cfdt = triangulate(lake_superior, 'pD')
But slight or no improvements with respect to the previous diagram can be
observed in this case. The real improvement arises when we further impose
constraints in the values of minimum angles on triangles (with the flag q
), or
in the maximum values of the areas of triangles (with the flag ‘a’). For
instance, if we require a constrained conforming Delaunay triangulation
(cncfdt
) in which all triangles have a minimum angle of at least 20 degrees,
we issue the following command
For the last example to conclude this section, we further impose a maximum area on triangles.
Shortest Paths
We will use the last example to introduce a special setting of the problem of
shortest paths. We pick a location in the North-West coast of the lake (say,
the vertex indexed as 370
in the original poly
file), and the goal is to
compute the shortest path to the furthest South-East location on the shore, at
the bottom-right corner—this is the vertex indexed as 179
in the original
poly
file. By a path in this setting, we mean a chain of edges of the
triangulation.
In the scipy
stack we accomplish the computation of shortest paths on a
triangulation (and in some other similar geometries that can be coded by means
of graphs) by relying on two modules:
scipy.sparse
to store a weighted-adjacency matrixG
representing the triangulation. Each non-zero entryG[i,j]
of this adjacency matrix is precisely the length of the edge from vertexi
to vertexj
.scipy.sparse.csgraph
, the module that deals with compressed sparse graphs. This module contains routines to analyze, extract information or manipulate graphs. Among these routines, we have several different algorithms to compute shortest paths on a graph.
For more information on the module
scipy.sparse.csgraph
, refer to the online documentation at docs.scipy.org/doc/scipy/reference/sparse.csgraph.html For the theory and applications of Graph Theory, one of the best sources is the introductory book by Reinhard Diestel, Graph Theory, published by Springer-Verlag.
Let us illustrate this example with proper code. We start by collecting the indices of the vertices of all segments in the triangulation, and the lengths of these segments.
We now create the weighted-adjacency matrix, which we store as a lil_matrix
,
and compute the shortest path between the requested vertices. We gather in a
list all the vertices included in the computed path, and plot the resulting
chain overlaid on the triangulation.
Geometric Query Problems
The fundamental problems in this category are the following:
- Point Location.
- Nearest neighbor.
- Range searching.
Point Location
The problem of point location is fundamental in Computational Geometry—given a partition of the space into disjoint regions, we need to query the region that contains a target location.
The most basic point location problems are those where the partition is given by
a single geometric object: a circle, or a polygon, for example. For those simple
objects that have been constructed through any of the classes in the module
sympy.geometry
, we have two useful methods: .encloses_point
and .encloses
.
The former checks whether a point is interior to a source object (but not on the border), while the latter checks whether another target object has all its defining entities in the interior of the source object.
Of special importance is this simple setting where the source object is a
polygon. The routines in the sympy.geometry
module get the job done, but at
the cost of too many resources and time. A much faster way to approach this
problem is by using the Path
class from the libraries of matplotlib.path
.
Let us see how with a quick session: first, we create a representation of a
polygon as a Path
.
We may ask now whether a point (respectively, a sequence of points) is interior
to the polygon. We accomplish this with either attribute contains_point
or
contains_points
.
More challenging point location problem arise when our space is partitioned by a
complex structure. For instance, once a triangulation has been computed, and a
random location is considered, we need to query for the triangle where our
target location lies. In the module scipy.spatial
we have handy routines to
perform this task over Delaunay triangulations created with
scipy.spatial.Delaunay
. In the following example, we track the triangles that
contain a set of 100 random points in the domain.
The same result is obtained with the method .find_simplex
of the Delaunay
object tri
.
Note that, when a triangle is found, the routine reports its corresponding index in
tri.simplices
. If no triangle is found (which means the point is exterior to the convex hull of the triangulation), the index reported is-1
.
Nearest Neighbors
The problem of finding the Voronoi cell that contains a given location is equivalent to the search for the nearest neighbor in a set of seeds. We can always perform this search with a brute force algorithm — and this is acceptable in some cases — but in general, there are more elegant and less complex approaches to this problem. The key lies in the concept of k-d trees: a special case of binary space partitioning structures for organizing points, conductive to fast searches.
In the scipy
stack we have an implementation of k-d trees, the python
class
KDTree
, in the module scipy.spatial
. This implementation is based on ideas
published in 1999 by Maneewongvatana and Mount. It is initialized with the
location of our input points. Once created, it can be manipulated and queried
with the following methods and attributes:
-
Methods:
data
: it presents the inputleafsize
: the number of points at which the algorithm switches to brute- force. This value can be optionally offered in the initialization of theKDTree
object.m
: The dimension of the space where the points are located.n
: The number of input points.maxes
: It indicates the highest values of each of the coordinates of the input points.mins
: It indicates the lowest values of each of the coordinates of the input points.
-
Attributes:
query(self, Q, p=2.0)
: The attribute that searches for the nearest- neighbor or a target locationQ
, using the structure of the k-d tree, with respect to the Minkowskip
-distance.query_ball_point(self, Q, r, p=2.0)
: A more sophisticated query that outputs all points within Minkowskip
-distancer
from a target locationQ
query_pairs(self, r, p=2.0)
: Find all pairs of points whose Minkowskip
-distance is at mostr
.query_ball_tree(self, other, r, p=2.0)
: similar toquery_pairs
, but this attribute finds all pairs of points from two different k-d trees, which are at a Minkowskip
-distance of at leastr
.sparse_distance_matrix(self, other, max_distance)
: Computes a distance matrix between two k-d trees, leaving as zero any distance greater thanmax_distance
. The output is stored in a sparsedok_matrix
.count_neighbors(self, other, r, p=2.0)
: This attribute is an implementation of the Two-point correlation designed by Gray and Moore, to count the number of pairs of points from two different kd-trees, which are at a Minkowskip
-distance not larger thanr
. Unlikequery_ball
, this attribute does not produce the actual pairs.
There is a faster implementation of this object created as an extension type in
cyton
, the cdef
class cKDTree
. The main difference is in the way the
nodes are coded on each case:
- For
KDTree
, the nodes are nestedpython
classes (node
being the top class, andleafnode
,innernode
being subclasses that represent different kinds of nodes in the tree). - For
cKDTree
, the nodes areC
-type malloc’d structs, not classes. This makes the implementation much faster, at a price of less control over a possible manipulation of the nodes.
Let use this idea to solve a point location problem, and at the same time revisit the Voronoi diagram from Lake Superior.
First, we query for the previous dataset of 100 random locations, the seeds that are closer to each of them
Note the output is a tuple with two numpy.array
: the first one indicates the
distances the each point closest seed (their nearest-neighbors), and the second
one indicates the index of the corresponding seed.
We may use this idea to represent the Voronoi diagram without a geometric description in terms of vertices, segments and rays.
Range Searching
A range searching problem tries to determine which objects of an input set intersect with a query object (that we call the range).
For example, given a set of points in the plane, which ones are contained inside
a circle of radius r
centered at a target location Q
. We can solve this
sample problem easily with the attribute query_ball_point
from a suitable
implementation of a k-d tree. We can go even further: if the range is an object
formed by the intersection of a sequence of different balls, the same attribute
gets the job done, as the following code illustrates.
This gives the following diagram, where the small dots represent the locations of the search space, and the circles are the range. The query is, of course, the points located inside of the circles, that our algorithm computed.
Problems in this setting vary from trivial to extremely complicated, depending on the input object types, range types, and query types. An excellent exposition of this subject is the survey paper Geometric Range Searching and its Relatives, published by Pankaj K. Agarwal and Jeff Erickson in 1999, by the American Mathematical Society Press, as part of the Advances in Discrete and Computational Geometry: proceedings of the 1996 AMS-IMS-SIAM joint summer research conference, Discrete and Computational Geometry.
Dynamic Problems
A dynamic problem is regarded as any of the problems in the previous two settings (static or query), but with the added challenge that objects are constantly being inserted or deleted. Besides solving the base problem, we need to take extra measures to assure that the implementation is efficient with respect to these changes.
To this effect, the implementations wrapped from the Qhull
libraries in the
module scipy.spatial
are equiped to deal with insertion of new points. We
accomplish this by stating the option incremental=True
, which basically
suppresses the qhull
control 'Qz'
, and prepares the output structure for
these complex situations.
Let us illustrate with a simple example. We start with the first ten vertices of Lake Superior, and inserting ten vertices at a time, update the corresponding triangulation and Voronoi diagrams.
Numerical Computational Geometry
This field arose simultaneously among different groups of researchers seeking solutions to a priori non-related problems. As it turns out, all the solutions they posed did actually have an important common denominator: they were obtained upon representing objects by means of parametric curves, parametric surfaces, or regions bounded by those. These scientists ended up unifying their techniques over the years, to finally define the field of Numerical Computational Geometry. In this journey, the field received different names: Machine Geometry, Geometric Modeling, and the most widespread Computer Aided Geometric Design (CAGD).
It is used in computer vision, for example, for 3D reconstruction and movement
outline. It is widely employed for the design and qualitative analysis of the
bodies of automobiles, aircraft, or watercraft. There are many computer aided
design software packages (CAD) that facilitate interactive manipulation and
solution of many of the problems in this area. In this regard, any interaction
with python
gets relegated to being part of the underlying computational
engine behind the visualization or animation—which are none of the strengths of
scipy
. For this reason, we will not cover visualization or animation
applications in this book, and focus on the basic mathematics instead.
In that regard, the foundation of Numerical Computational Geometry is based on three key concepts: Bézier surfaces, Coons patches, and B-spline methods. In turn, the theory of Bézier curves plays a central role in the development of these concepts. They are the geometric standard for the representation of piecewise polynomial curves. In this section we focus solely on the basic development of the theory of plane Bézier curves.
The rest of the material is also beyond the scope of
scipy
, and we therefore leave its exposition to more technical books. The best source in that sense is, without a doubt, the book Curves and Surfaces for Computer Aided Geometric Design—A Practical Guide (5th ed.), by Gerald Farin, published by Academic Press under the Morgan Kauffman Series in Computer Graphics and Geometric Modeling.
Bézier Curves
It all starts with the de Casteljau Algorithm to construct parametric
equations of an arc of a polynomial of order 3. In the submodule
matplotlib.path
we have an implementation of this algorithm using the class
Path
, which we can use to generate our own user-defined routines to generate
and plot plane Bézier curves.
For information about the class
Path
and its usage within thematplotlib
libraries, refer to the official documentation at matplotlib.org/api/path_api.html#matplotlib.path.Path , as well as the very instructive tutorial at matplotlib.org/users/path_tutorial.html. In this section, we focus solely on the necessary material to deal with Bézier curves.
Before we proceed, we need some basic code to represent and visualize Bézier curves:
-
The de Casteljau algorithm for arcs of polynomials of order 2 is performed by creating a
Path
with the three control points as vertices, and the list[Path.MOVETO, Path.CURVE3, Path.CURVE3]
as code. This ensures that the resulting curve starts atP1
in the direction given by the segmentP1P2
, and ends atP3
with direction given by the segmentP2P3
. If the three points are collinear, we obtain a segment containing them all. Otherwise, we obtain an arc of parabola. -
The de Casteljau algorithm for arcs of polynomials of order 3 is performed in a similar way to the previous case. We have four control points, and we create a
Path
with those as vertices. The code is the list[Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]
, which ensures that the arc starts atP1
with direction given by the segmentP1P2
. It also ensures that the arc ends atP4
in the direction of the segmentP3P4
.
Let us test it with a few basic examples:
Higher degree curves are computationally expensive to evaluate. When complex paths are needed, we rather create them as a piecewise sequence of low order Bézier patched together—we call this object a Bézier spline. Notice it is not hard to guarantee continuity on these splines. It is enough to make the end of each path the starting point of the next one. It is also easy to guarantee smoothness (at least up to the first derivative), by making the last two control points of one curve be aligned with the first two control points of the next one. Let us illustrate this with an example.
A clear advantage of representing curves as Bézier splines arises when we need to apply an affine transformation to a curve. For instance, if we required a counter-clockwise rotated version of the last curve computed, instead of performing the operation over all points of the curve, we simply apply the transformation to the control points, and repeat the de Casteljau algorithm on the new controls.
Summary
we have developed a brief incursion in the field of Computational Geometry, and
we have mastered all the tools coded in the scipy
stack to effectively address
the most common problems in this topic.