Shapely Documentation

repository·main·Indexed 26 days ago

https://github.com/shapely/shapely

A Python package for the manipulation and analysis of planar geometric objects in the Cartesian plane. Shapely wraps the GEOS library to provide a high-level Geometry interface and high-performance NumPy ufuncs for array-based operations. It implements interfaces based on the OGC's simple feature access specification, supporting geometry types such as Point, LineString, LinearRing, and Polygon.

Tokens
37.5K
Snippets
115
Records
228
Agent score
85%

What's inside Shapely

  1. Understand the Shapely architecture layers

    main

    Shapely's architecture is composed of four distinct layers that separate the high-level Python interface from the low-level C++ algorithms:

    1. Python geometry classes: Located in shapely.geometry, these provide the user-facing API.
    2. Implementation registry: An abstraction layer that allows for different geometry engines. The default registry is located in shapely.impl.
    3. GEOS implementations: The specific implementations of registry methods, found in shapely.geos.
    4. libgeos: The underlying C++ library containing the core algorithms.
  2. Understand the Shapely Spatial Data Model

    main

    Shapely's spatial data model is based on three fundamental geometric types: points, curves, and surfaces. Each type is defined by three mutually exclusive sets of points: interior, boundary, and exterior.

    • Point: A topological dimension of 0. It has one point in its interior, no points in its boundary, and all other points in its exterior.
    • Curve: A topological dimension of 1. It consists of infinitely many points along its length (interior), two end points (boundary), and all other points in its exterior. In Shapely, curves are approximated by linear splines (no smooth curves).
    • Surface: A topological dimension of 2. It consists of points within the area (interior), one or more curves (boundary), and all other points in its exterior (including points within holes).

    Class Mappings:

    • Point: Point class.
    • Curve: LineString and LinearRing classes.
    • Surface: Polygon class.
    • Collections: MultiPoint (points), MultiLineString (curves), and MultiPolygon (surfaces).
  3. Identify Shapely geometry classes and their hierarchy

    main

    Shapely implements interfaces based on the OGC's simple feature access specification. Geometry classes are organized into modules within shapely.geometry following their type name.

    All geometry classes derive from shapely.geometry.base.BaseGeometry.

    Examples of module/class mappings:

    • Point is in shapely.geometry.point
    • MultiPolygon is in shapely.geometry.multipolygon

    Methods called on these objects (like .area) are dispatched via a class variable named impl which points to the registered implementation function.

  4. Spatial Relationships and Operations in Shapely

    main

    Shapely provides two main categories of geometric interaction:

    1. Spatial Relationships (Predicates): Natural language relationships used to determine how objects relate to one another, such as contains, intersects, overlaps, and touches. These are based on the DE-9IM theoretical framework.
    2. Operations:
      • Constructive operations: Create new geometries, e.g., buffer, convex hull.
      • Set-theoretic operations: Combine or compare geometries, e.g., intersection, union.
  5. Create NumPy arrays of geometry objects robustly

    main

    When creating NumPy arrays containing Shapely geometry objects (using dtype=object), NumPy may attempt to 'unpack' geometries that are still sequence-like in Shapely 1.x, causing issues or warnings.

    Best Practice: To ensure compatibility across all Shapely and NumPy versions, create an empty array first and then fill it. If using Shapely 1.8, you may need to suppress ShapelyDeprecationWarning to avoid noise during this specific operation.

    import numpy as np
    import warnings
    from shapely.geometry import Point
    from shapely.errors import ShapelyDeprecationWarning
    
    geoms = [Point(0, 0), Point(1, 1), Point(2, 2)]
    
    # Robust two-step creation:
    arr = np.empty(len(geoms), dtype="object")
    
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=ShapelyDeprecationWarning)
        arr[:] = geoms
  6. Convert geometry coordinates to NumPy arrays

    main

    Directly converting a geometry object to a NumPy array (e.g., np.asarray(line)) is deprecated and will be removed in Shapely 2.0. The array_interface() method and ctypes attribute are also being removed.

    Migration Path: Convert the .coords attribute to a NumPy array instead.

    import numpy as np
    from shapely.geometry import LineString
    
    line = LineString([(0, 0), (1, 1), (2, 2)])
    
    # Correct way for Shapely 2.0:
    coords_array = np.array(line.coords)
  7. Construct Shapely geometries

    main

    You can create geometry objects in Shapely using direct class constructors or by importing from WKT (Well-Known Text) or WKB (Well-Known Binary) representations.

    Note: Geometry objects are immutable. Any operation performed on a geometry will return a new object rather than modifying the existing one in place.

  8. Install Shapely from source with a custom GEOS library

    main

    If you need to use a specific GEOS version or a GEOS distribution already present on your system (e.g., for compatibility with cartopy or osgeo.ogr), you must compile Shapely from source and instruct pip to ignore binary wheels.

    Linux:

    1. Install GEOS development headers (if not already present).
    2. Install Shapely using --no-binary.

    macOS:

    1. Install GEOS via Homebrew (if not already present).
    2. Install Shapely using --no-binary.

    Windows: Windows does not have a direct recipe, but you can build it by:

    1. Getting a C compiler for your Python version.
    2. Installing a GEOS binary (e.g., via OSGeo4W).
    3. Setting GEOS_INCLUDE_PATH and GEOS_LIBRARY_PATH environment variables.
    4. Running pip install shapely --no-binary.
    5. Ensuring GEOS .dll files are on your PATH.
    # Linux
    $ sudo apt install libgeos-dev
    $ pip install shapely --no-binary shapely
    
    # macOS
    $ brew install geos
    $ pip install shapely --no-binary shapely
  9. Access multi-part geometry components via .geoms

    main

    In Shapely 1.x, multi-part geometries (like MultiPoint, MultiLineString, MultiPolygon, and GeometryCollection) behaved like sequences, allowing iteration, indexing, and len(). In Shapely 2.0, these features are removed.

    Migration Path: Use the .geoms property to access the constituent parts of a multi-part geometry.

  10. Apply affine transformations using shapely.affinity

    main

    The shapely.affinity module provides functions to return transformed geometries. These functions work with all geometry types except GeometryCollection. 3D types are either preserved or supported by 3D transformations.

    Available transformations:

    • affine_transform(geom, matrix): Uses a custom transformation matrix.
    • rotate(geom, angle, origin='center', use_radians=False): Rotates a 2D geometry.
    • scale(geom, xfact=1.0, yfact=1.0, zfact=1.0, origin='center'): Scales a geometry along each dimension.
    • skew(geom, xs=0.0, ys=0.0, origin='center', use_radians=False): Shears a geometry along x and y dimensions.
    • translate(geom, xoff=0.0, yoff=0.0, zoff=0.0): Shifts a geometry by offsets.
  11. Install Shapely in Conda environments

    main

    If you are using a conda environment, avoid installing Shapely via pip. Shapely versions < 2.0 use ctypes to load GEOS shared libraries, which often leads to conflicts when multiple GEOS libraries exist on a system or when installing from PyPI into a conda environment.

    Recommendation: Conda users should always install Shapely from conda-forge to ensure the correct GEOS library is linked.

  12. Install Shapely via pip or conda

    main

    For most users, the easiest way to install Shapely is using built distributions which do not require compiling dependencies.

    Using pip (PyPI): Install the binary wheel for Linux, macOS, or Windows.

    Using conda: Install via the conda-forge channel.