Skip to content

PERF: vectorize shapely_to_path coordinate extraction#2693

Merged
QuLogic merged 1 commit into
SciTools:mainfrom
greglucas:perf/vectorize-shapely-to-path
Jul 14, 2026
Merged

PERF: vectorize shapely_to_path coordinate extraction#2693
QuLogic merged 1 commit into
SciTools:mainfrom
greglucas:perf/vectorize-shapely-to-path

Conversation

@greglucas

Copy link
Copy Markdown
Contributor

Rather than pulling out each sub-geometry .xy's coordinates, we can do one get_coordinates() call and fill in the codes all at once. Using cumsum to incrementally keep track of which ring we are in for the code placement.

I get about 50-100x speedup in the following example.

import time
import numpy as np, shapely.geometry as sgeom
from cartopy.mpl.path import shapely_to_path

t = np.linspace(0, 2 * np.pi, 50_000)
holes = [np.column_stack([np.cos(t[::100]), np.sin(t[::100])]) * 2 + [x, 0]
            for x in np.linspace(-40, 40, 20)]
poly = sgeom.Polygon(np.column_stack([np.cos(t), np.sin(t)]) * 100, holes)

t0 = time.perf_counter()
shapely_to_path(poly)
t1 = time.perf_counter()
print(f"Time taken: {t1 - t0:.5f} seconds")

Comment thread lib/cartopy/mpl/path.py
return Path(np.empty([0, 2]))
elif isinstance(shape, sgeom.LinearRing):
return Path(np.column_stack(shape.xy), closed=True)
return Path(shapely.get_coordinates(shape), closed=True)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

get_coordinates() defaults to 2d arrays, so we can use it directly here even if someone passes a geometry with Z.

https://shapely.readthedocs.io/en/2.1.2/reference/shapely.get_coordinates.html

Comment thread lib/cartopy/tests/mpl/test_path.py Outdated
Rather than pulling out each sub-geometry .xy's coordinates, we
can do one get_coordinates() call and fill in the codes all
at once.
@greglucas
greglucas force-pushed the perf/vectorize-shapely-to-path branch from 539102e to a0f8fd4 Compare July 7, 2026 02:43
@QuLogic QuLogic closed this Jul 14, 2026
@QuLogic QuLogic reopened this Jul 14, 2026
@QuLogic
QuLogic merged commit 5750040 into SciTools:main Jul 14, 2026
30 of 42 checks passed
@QuLogic QuLogic added this to the Next Release milestone Jul 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants