import numpy as np
from shapely import Polygon, MultiPolygon
from spatialpandas.geometry import PolygonArray, MultiPolygonArray
polygon_shell = np.array([[89.97223, -58.302593],
[89.98285, -58.29493],
[89.97226, -58.27778],
[89.95511, -58.27485],
[89.92737, -58.28543],
[89.93793, -58.30258],
[89.97223, -58.302593]])
p = Polygon(polygon_shell)
p
exterior_coords = np.asarray(p.exterior.coords)
exterior_coords
array([[ 89.97223 , -58.302593], [ 89.98285 , -58.29493 ], [ 89.97226 , -58.27778 ], [ 89.95511 , -58.27485 ], [ 89.92737 , -58.28543 ], [ 89.93793 , -58.30258 ], [ 89.97223 , -58.302593]])
The following snippet shows the constructing of a PolygonArray
containing three identical polygons
p_arr_shapely = PolygonArray([p, p, p])
p_arr_coords = PolygonArray.from_exterior_coords([exterior_coords, exterior_coords, exterior_coords])
We can see the resulting results are equivalent.
np.all(p_arr_shapely == p_arr_coords)
True
The main motivation for constructing from exterior coordinates is performance.
N = 100000
p_list = [p for i in range(N)]
exterior_coord_list = [exterior_coords for i in range(N)]
%%time
p_arr_shapely = PolygonArray(p_list)
CPU times: total: 828 ms Wall time: 2.82 s
%%time
p_arr_coords = PolygonArray.from_exterior_coords(exterior_coord_list)
CPU times: total: 31.2 ms Wall time: 135 ms
np.all(p_arr_shapely == p_arr_coords)
True
We can do the same with a MultiPolygonArray.
mp = MultiPolygon(polygons=[p, p])
mp_arr_shapely = MultiPolygonArray([mp])
mp_arr_coords = MultiPolygonArray.from_exterior_coords([[exterior_coords, exterior_coords]])
np.all(mp_arr_shapely == mp_arr_coords)
True
N = 100000
mp_list = [mp for i in range(N)]
exterior_coord_list = [[exterior_coords, exterior_coords] for i in range(N)]
%%time
mp_arr_shapely = MultiPolygonArray(mp_list)
CPU times: total: 1.22 s Wall time: 7.01 s
%%time
mp_arr_coords = MultiPolygonArray.from_exterior_coords(exterior_coord_list)
CPU times: total: 15.6 ms Wall time: 296 ms
np.all(mp_arr_shapely == mp_arr_coords)
True