Geometry from scratch

Points, lines and polygons with Shapely — what each object stores, how its area, length and centroid are computed, and how to ask whether two shapes touch.

Maps, robot workspaces, floor plans and sensor footprints are all made of a few geometric objects: points, lines and polygons. The Python library Shapely wraps GEOS, the C++ geometry engine behind PostGIS and QGIS, so a few lines of Python give exact answers to questions such as how long is this road or does this obstacle overlap that path.

The repository has one notebook, shapely_geometric_objects.ipynb, which builds every basic object type and reads off its attributes. The first three lessons follow it and open up the calculations behind those attributes. The fourth goes beyond the notebook to spatial predicates — intersects, touches, contains — which are the reason most people reach for Shapely in the first place.

Prerequisites

Running the code

cd geometry_from_scratch
pip install shapely
jupyter notebook shapely_geometric_objects.ipynb

Every value quoted in these lessons was checked with Shapely 2.2. Shapely works in a flat plane: it measures in whatever units the coordinates are in, and knows nothing about the curvature of the Earth — a point lesson 1 returns to.

Lessons

  1. 1 Points and linesShapely's Point and LineString, what distance means in a flat plane, and why a line's centroid is not the average of its vertices.
  2. 2 Polygons and holesHow Shapely stores a polygon, how its area is computed with the shoelace formula, and what a hole does to area and centroid.
  3. 3 Collections, convex hulls and validityMultiPoint, MultiLineString and MultiPolygon; computing a convex hull; and why the notebook's MultiPolygon is invalid.
  4. 4 Spatial predicatesAsking whether two shapes intersect, touch, overlap or contain each other — and the DE-9IM matrix that answers all of these at once.

Browse this course's code on GitHub →