diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/OCC/Extend/__pycache__/LayerManager.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/OCC/Extend/__pycache__/LayerManager.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4a697ee237a1a2a855ebde19b37e9f29b8617e2 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/OCC/Extend/__pycache__/LayerManager.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/OCC/Extend/__pycache__/TopologyUtils.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/OCC/Extend/__pycache__/TopologyUtils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11a7a9bacc8c4695c4444ef6b754fabd8d203153 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/OCC/Extend/__pycache__/TopologyUtils.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/__init__.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8668dc56cdd21a0d409b2c7afa0592be06fe0654 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_coverage.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_coverage.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cd721eb14e98b553c7d491045740603528c3da3 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_coverage.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_enum.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_enum.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d125cefa2b224ec138ef4d7dcfb5ec31b8b743e3 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_enum.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_geometry.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_geometry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..496b4f638bac2e0978f8383e08e82ebde649669d Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_geometry.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_ragged_array.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_ragged_array.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca30f2c93514efabee1384cb20ed2c4b1fbbe180 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_ragged_array.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_version.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3648cd78bfd80805865b7caf7d625b342d845a24 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/_version.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/affinity.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/affinity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25657200d70c8f58de0cc4cec188ca9c381b5f4c Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/affinity.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/conftest.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/conftest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..610abecd978ec1a878c358afe53a88f213f3a82c Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/conftest.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/constructive.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/constructive.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb5e82c476c290f0c128231e45f9fc86fc204235 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/constructive.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/coordinates.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/coordinates.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91cbe21352196b442f7a6f25ae7864a09543b4e8 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/coordinates.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/coords.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/coords.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b9acd8be314a98718ba29bc53ab4b785adf8df7 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/coords.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/creation.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/creation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7b0e2fc83935cdbbe4bbe1a0e2d834a4359cffb Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/creation.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/decorators.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/decorators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbd4f9d5b8a63899cdc9c63af16d831ca53d0b95 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/decorators.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/errors.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..688f57669863b1d47653b93e34ed5fb739b7f72c Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/errors.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/geos.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/geos.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f16402936fa4411e1461836621c9c67afa8a388 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/geos.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/io.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/io.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56b9d5c0b9558a5c6ce88011d85879cc6abd2dd9 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/io.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/linear.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/linear.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfff88ab2b15a530e41dae819c0dfd07b95bbd3e Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/linear.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/measurement.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/measurement.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c59414e72e8f8feab080dcc23d0c96116cbf11e Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/measurement.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/ops.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/ops.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44de905a3cf93922b1d5cd51040abb2c22962359 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/ops.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/plotting.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/plotting.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b01944c1b9c34f7c47c8aa63a7340c2cc0442a6 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/plotting.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/predicates.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/predicates.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b8a84d92dac604c7b20dc076201ba8e570b8e15 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/predicates.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/prepared.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/prepared.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2efc9a35f3c295edd6d48ba604e799c0b3020a93 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/prepared.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/set_operations.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/set_operations.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3b688a1da141b798c1c16595b170edc380e7f3e Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/set_operations.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/speedups.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/speedups.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1848a926f16414c3543c4fb990cf6a14624d868 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/speedups.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/strtree.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/strtree.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe95a843df76e8742031d1f284198d7b59931384 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/strtree.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/testing.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/testing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32f17be6186b3b89d26acf2f412b71ecc183acc9 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/testing.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/validation.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/validation.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70c5ae18de508b8d26d6d804a32581ac2d9986f2 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/validation.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/wkb.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/wkb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..faffd63152847109fd5a594a3893b91cf29829f0 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/wkb.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/wkt.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/wkt.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2a8f7c9643d54acd39c2254557b581810d36f80 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/__pycache__/wkt.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__init__.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c1d805901f3f8ba31a20a94647871d27638ec8a --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__init__.py @@ -0,0 +1 @@ +"""Algorithms implemented in Shapely.""" diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/__init__.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a16e43b49860bd1cba96a743d546263bea776bfd Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/_oriented_envelope.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/_oriented_envelope.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7acc3fdf275cb2a5700f8656c39da5e1df1404d2 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/_oriented_envelope.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/cga.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/cga.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77aa6d0038a3ce42f7abdbeee85398b3bb0946d8 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/cga.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/polylabel.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/polylabel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65a580617921802237fb5b245c46a9c01b990450 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/__pycache__/polylabel.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/_oriented_envelope.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/_oriented_envelope.py new file mode 100644 index 0000000000000000000000000000000000000000..2e7ade75c9cff41d65d1ee5dbd3a8745f29ce0b7 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/_oriented_envelope.py @@ -0,0 +1,56 @@ +import math +from itertools import islice + +import numpy as np + +import shapely +from shapely.affinity import affine_transform + + +def _oriented_envelope_min_area(geometry, **kwargs): + """Compute the oriented envelope (minimum rotated rectangle). + + This is a fallback implementation for GEOS < 3.12 to have the correct + minimum area behaviour. + """ + if geometry is None: + return None + if geometry.is_empty: + return shapely.from_wkt("POLYGON EMPTY") + + # first compute the convex hull + hull = geometry.convex_hull + try: + coords = hull.exterior.coords + except AttributeError: # may be a Point or a LineString + return hull + # generate the edge vectors between the convex hull's coords + edges = ( + (pt2[0] - pt1[0], pt2[1] - pt1[1]) + for pt1, pt2 in zip(coords, islice(coords, 1, None)) + ) + + def _transformed_rects(): + for dx, dy in edges: + # compute the normalized direction vector of the edge + # vector. + length = math.sqrt(dx**2 + dy**2) + ux, uy = dx / length, dy / length + # compute the normalized perpendicular vector + vx, vy = -uy, ux + # transform hull from the original coordinate system to + # the coordinate system defined by the edge and compute + # the axes-parallel bounding rectangle. + transf_rect = affine_transform(hull, (ux, uy, vx, vy, 0, 0)).envelope + # yield the transformed rectangle and a matrix to + # transform it back to the original coordinate system. + yield (transf_rect, (ux, vx, uy, vy, 0, 0)) + + # check for the minimum area rectangle and return it + transf_rect, inv_matrix = min(_transformed_rects(), key=lambda r: r[0].area) + return affine_transform(transf_rect, inv_matrix) + + +_oriented_envelope_min_area_vectorized = np.frompyfunc( + _oriented_envelope_min_area, 1, 1 +) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/cga.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/cga.py new file mode 100644 index 0000000000000000000000000000000000000000..1887c40cf9f845ccf9505e2b1d36e62f7e4d32b6 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/cga.py @@ -0,0 +1,50 @@ +"""Shapely CGA algorithms.""" + +import numpy as np + +import shapely + + +def signed_area(ring): + """Return the signed area enclosed by a ring in linear time. + + Algorithm used: https://web.archive.org/web/20080209143651/http://cgafaq.info:80/wiki/Polygon_Area + """ + coords = np.array(ring.coords)[:, :2] + xs, ys = np.vstack([coords, coords[1]]).T + return np.sum(xs[1:-1] * (ys[2:] - ys[:-2])) / 2.0 + + +def _reverse_conditioned(rings, condition): + """Return a copy of the rings potentially reversed depending on `condition`.""" + condition = np.asarray(condition) + if np.all(condition): + rings = shapely.reverse(rings) + elif np.any(condition): + rings = np.array(rings) + rings[condition] = shapely.reverse(rings[condition]) + return rings + + +def _orient_polygon(geometry, exterior_cw=False): + if geometry is None: + return None + if geometry.geom_type in ["MultiPolygon", "GeometryCollection"]: + return geometry.__class__( + [_orient_polygon(geom, exterior_cw) for geom in geometry.geoms] + ) + # elif geometry.geom_type in ["LinearRing"]: + # return reverse_conditioned(geometry, is_ccw(geometry) != ccw) + elif geometry.geom_type == "Polygon": + rings = np.array([geometry.exterior, *geometry.interiors]) + reverse_condition = shapely.is_ccw(rings) + reverse_condition[0] = not reverse_condition[0] + if exterior_cw: + reverse_condition = np.logical_not(reverse_condition) + if np.any(reverse_condition): + rings = _reverse_conditioned(rings, reverse_condition) + return geometry.__class__(rings[0], rings[1:]) + return geometry + + +_orient_polygons_vectorized = np.frompyfunc(_orient_polygon, nin=2, nout=1) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/polylabel.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/polylabel.py new file mode 100644 index 0000000000000000000000000000000000000000..c21ddd43e600b3851965b7dc7be4d465c59683bb --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/algorithms/polylabel.py @@ -0,0 +1,43 @@ +"""Provides functions for finding the pole of inaccessibility for a given polygon.""" + +from shapely._geometry import get_point +from shapely.constructive import maximum_inscribed_circle + + +def polylabel(polygon, tolerance=1.0): + """Find pole of inaccessibility for a given polygon. + + Based on Vladimir Agafonkin's https://github.com/mapbox/polylabel + + Parameters + ---------- + polygon : shapely.geometry.Polygon + Polygon for which to find the pole of inaccessibility. + tolerance : int or float, optional + `tolerance` represents the highest resolution in units of the + input geometry that will be considered for a solution. (default + value is 1.0). + + Returns + ------- + shapely.geometry.Point + A point representing the pole of inaccessibility for the given input + polygon. + + Raises + ------ + shapely.errors.TopologicalError + If the input polygon is not a valid geometry. + + Examples + -------- + >>> from shapely.ops import polylabel + >>> from shapely import LineString + >>> polygon = LineString([(0, 0), (50, 200), (100, 100), (20, 50), + ... (-100, -20), (-150, -200)]).buffer(100) + >>> polylabel(polygon, tolerance=0.001) + + + """ + line = maximum_inscribed_circle(polygon, tolerance) + return get_point(line, 0) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__init__.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..47d2a8b7f68bf83c2e03ea14fe7da0821f778b60 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__init__.py @@ -0,0 +1,27 @@ +"""Geometry classes and factories.""" + +from shapely.geometry.base import CAP_STYLE, JOIN_STYLE +from shapely.geometry.collection import GeometryCollection +from shapely.geometry.geo import box, mapping, shape +from shapely.geometry.linestring import LineString +from shapely.geometry.multilinestring import MultiLineString +from shapely.geometry.multipoint import MultiPoint +from shapely.geometry.multipolygon import MultiPolygon +from shapely.geometry.point import Point +from shapely.geometry.polygon import LinearRing, Polygon + +__all__ = [ + "CAP_STYLE", + "JOIN_STYLE", + "GeometryCollection", + "LineString", + "LinearRing", + "MultiLineString", + "MultiPoint", + "MultiPolygon", + "Point", + "Polygon", + "box", + "mapping", + "shape", +] diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/__init__.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1947012c4f46aab1096805183ad0d4d3acae4feb Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/base.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c98748777c1aee80b8194f03b508e563cd484ad Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/base.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/collection.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/collection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02c10c7bc820e9bffb0d611f3da75116060ddb6a Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/collection.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/geo.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/geo.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b99123d3fcdf1b4e199be2fdcd190899e827dcb7 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/geo.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/linestring.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/linestring.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75255cda0a56c1454b9eb54750633b859d2cac2b Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/linestring.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/multilinestring.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/multilinestring.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3dd01b33a4b4154e040c58829d1f60fc614c418e Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/multilinestring.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/multipoint.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/multipoint.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89640f5315b935b26b2e0bc9a29a0873304c03d5 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/multipoint.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/multipolygon.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/multipolygon.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a858f2edef94ba3249bdccd6150a53ec2461d2f Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/multipolygon.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/point.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/point.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..279bff82fee9687ad2517b170157c380fa2f9925 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/point.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/polygon.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/polygon.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f29a9907666783b6724aa44c4208edac14c64c8 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/__pycache__/polygon.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/base.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/base.py new file mode 100644 index 0000000000000000000000000000000000000000..9f3ed13d38eeddc476d59932aa117c7c3a80456b --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/base.py @@ -0,0 +1,1138 @@ +"""Base geometry class and utilities. + +Note: a third, z, coordinate value may be used when constructing +geometry objects, but has no effect on geometric analysis. All +operations are performed in the x-y plane. Thus, geometries with +different z values may intersect or be equal. +""" + +import re +from warnings import warn + +import numpy as np + +import shapely +from shapely._geometry_helpers import _geom_factory +from shapely.constructive import BufferCapStyle, BufferJoinStyle +from shapely.coords import CoordinateSequence +from shapely.decorators import deprecate_positional +from shapely.errors import GeometryTypeError, GEOSException, ShapelyDeprecationWarning + +GEOMETRY_TYPES = [ + "Point", + "LineString", + "LinearRing", + "Polygon", + "MultiPoint", + "MultiLineString", + "MultiPolygon", + "GeometryCollection", +] + +_geos_ge_312 = shapely.geos_version >= (3, 12, 0) + + +def geom_factory(g, parent=None): + """Create a Shapely geometry instance from a pointer to a GEOS geometry. + + .. warning:: + The GEOS library used to create the the GEOS geometry pointer + and the GEOS library used by Shapely must be exactly the same, or + unexpected results or segfaults may occur. + + .. deprecated:: 2.0 + Deprecated in Shapely 2.0, and will be removed in a future version. + """ + warn( + "The 'geom_factory' function is deprecated in Shapely 2.0, and will be " + "removed in a future version", + FutureWarning, + stacklevel=2, + ) + return _geom_factory(g) + + +def dump_coords(geom): + """Dump coordinates of a geometry in the same order as data packing.""" + if not isinstance(geom, BaseGeometry): + raise ValueError( + "Must be instance of a geometry class; found " + geom.__class__.__name__ + ) + elif geom.geom_type in ("Point", "LineString", "LinearRing"): + return geom.coords[:] + elif geom.geom_type == "Polygon": + return geom.exterior.coords[:] + [i.coords[:] for i in geom.interiors] + elif geom.geom_type.startswith("Multi") or geom.geom_type == "GeometryCollection": + # Recursive call + return [dump_coords(part) for part in geom.geoms] + else: + raise GeometryTypeError("Unhandled geometry type: " + repr(geom.geom_type)) + + +def _maybe_unpack(result): + if result.ndim == 0: + # convert numpy 0-d array / scalar to python scalar + return result.item() + else: + # >=1 dim array + return result + + +class CAP_STYLE: + """Buffer cap styles.""" + + round = BufferCapStyle.round + flat = BufferCapStyle.flat + square = BufferCapStyle.square + + +class JOIN_STYLE: + """Buffer join styles.""" + + round = BufferJoinStyle.round + mitre = BufferJoinStyle.mitre + bevel = BufferJoinStyle.bevel + + +class BaseGeometry(shapely.Geometry): + """Provides GEOS spatial predicates and topological operations.""" + + __slots__ = [] + + def __new__(self): + """Directly calling the base class 'BaseGeometry()' is deprecated. + + This will raise an error in the future. To create an empty geometry, + use one of the subclasses instead, for example 'GeometryCollection()' + """ + warn( + "Directly calling the base class 'BaseGeometry()' is deprecated, and " + "will raise an error in the future. To create an empty geometry, " + "use one of the subclasses instead, for example 'GeometryCollection()'.", + ShapelyDeprecationWarning, + stacklevel=2, + ) + return shapely.from_wkt("GEOMETRYCOLLECTION EMPTY") + + @property + def _ndim(self): + return shapely.get_coordinate_dimension(self) + + def __bool__(self): + """Return True if the geometry is not empty, else False.""" + return self.is_empty is False + + def __nonzero__(self): + """Return True if the geometry is not empty, else False.""" + return self.__bool__() + + def __format__(self, format_spec): + """Format a geometry using a format specification.""" + # bypass regexp for simple cases + if format_spec == "": + return shapely.to_wkt(self, rounding_precision=-1) + elif format_spec == "x": + return shapely.to_wkb(self, hex=True).lower() + elif format_spec == "X": + return shapely.to_wkb(self, hex=True) + + # fmt: off + format_spec_regexp = ( + "(?:0?\\.(?P[0-9]+))?" + "(?P[fFgGxX]?)" + ) + # fmt: on + match = re.fullmatch(format_spec_regexp, format_spec) + if match is None: + raise ValueError(f"invalid format specifier: {format_spec}") + + prec, fmt_code = match.groups() + + if prec: + prec = int(prec) + else: + # GEOS has a default rounding_precision -1 + prec = -1 + + if not fmt_code: + fmt_code = "g" + + if fmt_code in ("g", "G"): + res = shapely.to_wkt(self, rounding_precision=prec, trim=True) + elif fmt_code in ("f", "F"): + res = shapely.to_wkt(self, rounding_precision=prec, trim=False) + elif fmt_code in ("x", "X"): + raise ValueError("hex representation does not specify precision") + else: + raise NotImplementedError(f"unhandled fmt_code: {fmt_code}") + + if fmt_code.isupper(): + return res.upper() + else: + return res + + def __repr__(self): + """Return a string representation of the geometry.""" + try: + wkt = super().__str__() + except (GEOSException, ValueError): + # we never want a repr() to fail; that can be very confusing + return f"" + + # the total length is limited to 80 characters including brackets + max_length = 78 + if len(wkt) > max_length: + return f"<{wkt[: max_length - 3]}...>" + + return f"<{wkt}>" + + def __str__(self): + """Return a string representation of the geometry.""" + return self.wkt + + def __reduce__(self): + """Pickle support.""" + return (shapely.from_wkb, (shapely.to_wkb(self, include_srid=True),)) + + # Operators + # --------- + + def __and__(self, other): + """Return the intersection of the geometries.""" + return self.intersection(other) + + def __or__(self, other): + """Return the union of the geometries.""" + return self.union(other) + + def __sub__(self, other): + """Return the difference of the geometries.""" + return self.difference(other) + + def __xor__(self, other): + """Return the symmetric difference of the geometries.""" + return self.symmetric_difference(other) + + # Coordinate access + # ----------------- + + @property + def coords(self): + """Access to geometry's coordinates (CoordinateSequence).""" + has_z = self.has_z + has_m = self.has_m if _geos_ge_312 else False + coords_array = shapely.get_coordinates(self, include_z=has_z, include_m=has_m) + return CoordinateSequence(coords_array) + + @property + def xy(self): + """Separate arrays of X and Y coordinate values.""" + raise NotImplementedError + + # Python feature protocol + + @property + def __geo_interface__(self): + """Dictionary representation of the geometry.""" + raise NotImplementedError + + # Type of geometry and its representations + # ---------------------------------------- + + def geometryType(self): + """Get the geometry type (deprecated). + + .. deprecated:: 2.0 + Use the :py:attr:`geom_type` attribute instead. + """ + warn( + "The 'GeometryType()' method is deprecated, and will be removed in " + "the future. You can use the 'geom_type' attribute instead.", + ShapelyDeprecationWarning, + stacklevel=2, + ) + return self.geom_type + + @property + def type(self): + """Get the geometry type (deprecated). + + .. deprecated:: 2.0 + Use the :py:attr:`geom_type` attribute instead. + """ + warn( + "The 'type' attribute is deprecated, and will be removed in " + "the future. You can use the 'geom_type' attribute instead.", + ShapelyDeprecationWarning, + stacklevel=2, + ) + return self.geom_type + + @property + def wkt(self): + """WKT representation of the geometry.""" + # TODO(shapely-2.0) keep default of not trimming? + return shapely.to_wkt(self, rounding_precision=-1) + + @property + def wkb(self): + """WKB representation of the geometry.""" + return shapely.to_wkb(self) + + @property + def wkb_hex(self): + """WKB hex representation of the geometry.""" + return shapely.to_wkb(self, hex=True) + + def svg(self, scale_factor=1.0, **kwargs): + """Raise NotImplementedError.""" + raise NotImplementedError + + def _repr_svg_(self): + """SVG representation for iPython notebook.""" + svg_top = ( + '" + else: + # Establish SVG canvas that will fit all the data + small space + xmin, ymin, xmax, ymax = self.bounds + if xmin == xmax and ymin == ymax: + # This is a point; buffer using an arbitrary size + xmin, ymin, xmax, ymax = self.buffer(1).bounds + else: + # Expand bounds by a fraction of the data ranges + expand = 0.04 # or 4%, same as R plots + widest_part = max([xmax - xmin, ymax - ymin]) + expand_amount = widest_part * expand + xmin -= expand_amount + ymin -= expand_amount + xmax += expand_amount + ymax += expand_amount + dx = xmax - xmin + dy = ymax - ymin + width = min([max([100.0, dx]), 300]) + height = min([max([100.0, dy]), 300]) + try: + scale_factor = max([dx, dy]) / max([width, height]) + except ZeroDivisionError: + scale_factor = 1.0 + view_box = f"{xmin} {ymin} {dx} {dy}" + transform = f"matrix(1,0,0,-1,0,{ymax + ymin})" + return ( + f'{svg_top}width="{width}" height="{height}" viewBox="{view_box}" ' + 'preserveAspectRatio="xMinYMin meet">' + f'{self.svg(scale_factor)}' + ) + + @property + def geom_type(self): + """Name of the geometry's type, such as 'Point'.""" + return GEOMETRY_TYPES[shapely.get_type_id(self)] + + # Real-valued properties and methods + # ---------------------------------- + + @property + def area(self): + """Unitless area of the geometry (float).""" + return float(shapely.area(self)) + + def distance(self, other): + """Unitless distance to other geometry (float).""" + return _maybe_unpack(shapely.distance(self, other)) + + def hausdorff_distance(self, other): + """Unitless hausdorff distance to other geometry (float).""" + return _maybe_unpack(shapely.hausdorff_distance(self, other)) + + @property + def length(self): + """Unitless length of the geometry (float).""" + return float(shapely.length(self)) + + @property + def minimum_clearance(self): + """Unitless distance a node can be moved to produce an invalid geometry (float).""" # noqa: E501 + return float(shapely.minimum_clearance(self)) + + # Topological properties + # ---------------------- + + @property + def boundary(self): + """Return a lower dimension geometry that bounds the object. + + The boundary of a polygon is a line, the boundary of a line is a + collection of points. The boundary of a point is an empty (null) + collection. + """ + return shapely.boundary(self) + + @property + def bounds(self): + """Return minimum bounding region (minx, miny, maxx, maxy).""" + return tuple(shapely.bounds(self).tolist()) + + @property + def centroid(self): + """Return the geometric center of the object.""" + return shapely.centroid(self) + + def point_on_surface(self): + """Return a point guaranteed to be within the object, cheaply. + + Alias of `representative_point`. + """ + return shapely.point_on_surface(self) + + def representative_point(self): + """Return a point guaranteed to be within the object, cheaply. + + Alias of `point_on_surface`. + """ + return shapely.point_on_surface(self) + + @property + def convex_hull(self): + """Return the convex hull of the geometry. + + Imagine an elastic band stretched around the geometry: that's a convex + hull, more or less. + + The convex hull of a three member multipoint, for example, is a + triangular polygon. + """ + return shapely.convex_hull(self) + + @property + def envelope(self): + """A figure that envelopes the geometry.""" + return shapely.envelope(self) + + @property + def oriented_envelope(self): + """Return the oriented envelope (minimum rotated rectangle) of a geometry. + + The oriented envelope encloses an input geometry, such that the resulting + rectangle has minimum area. + + Unlike envelope this rectangle is not constrained to be parallel to the + coordinate axes. If the convex hull of the object is a degenerate (line + or point) this degenerate is returned. + + The starting point of the rectangle is not fixed. You can use + :func:`~shapely.normalize` to reorganize the rectangle to + :ref:`strict canonical form ` so the starting point is + always the lower left point. + + Alias of `minimum_rotated_rectangle`. + """ + return shapely.oriented_envelope(self) + + @property + def minimum_rotated_rectangle(self): + """Return the oriented envelope (minimum rotated rectangle) of the geometry. + + The oriented envelope encloses an input geometry, such that the resulting + rectangle has minimum area. + + Unlike `envelope` this rectangle is not constrained to be parallel to the + coordinate axes. If the convex hull of the object is a degenerate (line + or point) this degenerate is returned. + + The starting point of the rectangle is not fixed. You can use + :func:`~shapely.normalize` to reorganize the rectangle to + :ref:`strict canonical form ` so the starting point is + always the lower left point. + + Alias of `oriented_envelope`. + """ + return shapely.oriented_envelope(self) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # buffer(self, geometry, distance, quad_segs=16, cap_style="round", ...) + # shapely 2.1: shows deprecation warning about positional 'cap_style', etc. + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'quad_segs' + # buffer(self, geometry, distance, quad_segs=16, *, cap_style="round", ...) + @deprecate_positional( + ["cap_style", "join_style", "mitre_limit", "single_sided"], + category=DeprecationWarning, + ) + def buffer( + self, + distance, + quad_segs=16, + cap_style="round", + join_style="round", + mitre_limit=5.0, + single_sided=False, + **kwargs, + ): + """Get a geometry that represents all points within a distance of this geometry. + + A positive distance produces a dilation, a negative distance an + erosion. A very small or zero distance may sometimes be used to + "tidy" a polygon. + + Parameters + ---------- + distance : float + The distance to buffer around the object. + quad_segs : int, optional + Sets the number of line segments used to approximate an + angle fillet. + cap_style : shapely.BufferCapStyle or {'round', 'square', 'flat'}, default 'round' + Specifies the shape of buffered line endings. BufferCapStyle.round + ('round') results in circular line endings (see ``quad_segs``). Both + BufferCapStyle.square ('square') and BufferCapStyle.flat ('flat') + result in rectangular line endings, only BufferCapStyle.flat + ('flat') will end at the original vertex, while + BufferCapStyle.square ('square') involves adding the buffer width. + join_style : shapely.BufferJoinStyle or {'round', 'mitre', 'bevel'}, default 'round' + Specifies the shape of buffered line midpoints. + BufferJoinStyle.ROUND ('round') results in rounded shapes. + BufferJoinStyle.bevel ('bevel') results in a beveled edge that + touches the original vertex. BufferJoinStyle.mitre ('mitre') results + in a single vertex that is beveled depending on the ``mitre_limit`` + parameter. + mitre_limit : float, optional + The mitre limit ratio is used for very sharp corners. The + mitre ratio is the ratio of the distance from the corner to + the end of the mitred offset corner. When two line segments + meet at a sharp angle, a miter join will extend the original + geometry. To prevent unreasonable geometry, the mitre limit + allows controlling the maximum length of the join corner. + Corners with a ratio which exceed the limit will be beveled. + single_sided : bool, optional + The side used is determined by the sign of the buffer + distance: + + a positive distance indicates the left-hand side + a negative distance indicates the right-hand side + + The single-sided buffer of point geometries is the same as + the regular buffer. The End Cap Style for single-sided + buffers is always ignored, and forced to the equivalent of + CAP_FLAT. + quadsegs, resolution : int, optional + Deprecated aliases for `quad_segs`. + **kwargs : dict, optional + For backwards compatibility of renamed parameters. If an unsupported + kwarg is passed, a `ValueError` will be raised. + + Returns + ------- + Geometry + + Notes + ----- + The return value is a strictly two-dimensional geometry. All + Z coordinates of the original geometry will be ignored. + + .. deprecated:: 2.1.0 + A deprecation warning is shown if ``quad_segs``, ``cap_style``, + ``join_style``, ``mitre_limit`` or ``single_sided`` are + specified as positional arguments. In a future release, these will + need to be specified as keyword arguments. + + Examples + -------- + >>> from shapely import BufferCapStyle + >>> from shapely.wkt import loads + >>> g = loads('POINT (0.0 0.0)') + + 16-gon approx of a unit radius circle: + + >>> g.buffer(1.0).area + 3.1365484905459398 + + 128-gon approximation: + + >>> g.buffer(1.0, 128).area + 3.1415138011443013 + + triangle approximation: + + >>> g.buffer(1.0, 3).area + 3.0 + >>> list(g.buffer(1.0, cap_style=BufferCapStyle.square).exterior.coords) + [(1.0, 1.0), (1.0, -1.0), (-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)] + >>> g.buffer(1.0, cap_style=BufferCapStyle.square).area + 4.0 + + """ # noqa: E501 + quadsegs = kwargs.pop("quadsegs", None) + if quadsegs is not None: + warn( + "The `quadsegs` argument is deprecated. Use `quad_segs` instead.", + FutureWarning, + stacklevel=2, + ) + quad_segs = quadsegs + + resolution = kwargs.pop("resolution", None) + if resolution is not None: + warn( + "The 'resolution' argument is deprecated. Use 'quad_segs' instead", + DeprecationWarning, + stacklevel=2, + ) + quad_segs = resolution + if kwargs: + kwarg = list(kwargs.keys())[0] # noqa + raise TypeError(f"buffer() got an unexpected keyword argument '{kwarg}'") + + if mitre_limit == 0.0: + raise ValueError("Cannot compute offset from zero-length line segment") + elif not np.isfinite(distance).all(): + raise ValueError("buffer distance must be finite") + + return shapely.buffer( + self, + distance, + quad_segs=quad_segs, + cap_style=cap_style, + join_style=join_style, + mitre_limit=mitre_limit, + single_sided=single_sided, + ) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # simplify(self, tolerance, preserve_topology=True) + # shapely 2.1: shows deprecation warning about positional 'preserve_topology' + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'tolerance' + # simplify(self, tolerance, *, preserve_topology=True) + + @deprecate_positional(["preserve_topology"], category=DeprecationWarning) + def simplify(self, tolerance, preserve_topology=True): + """Return a simplified geometry produced by the Douglas-Peucker algorithm. + + Coordinates of the simplified geometry will be no more than the + tolerance distance from the original. Unless the topology preserving + option is used, the algorithm may produce self-intersecting or + otherwise invalid geometries. + """ + return shapely.simplify(self, tolerance, preserve_topology=preserve_topology) + + def normalize(self): + """Convert geometry to normal form (or canonical form). + + This method orders the coordinates, rings of a polygon and parts of + multi geometries consistently. Typically useful for testing purposes + (for example in combination with `equals_exact`). + + Examples + -------- + >>> from shapely import MultiLineString + >>> line = MultiLineString([[(0, 0), (1, 1)], [(3, 3), (2, 2)]]) + >>> line.normalize() + + + """ + return shapely.normalize(self) + + # Overlay operations + # --------------------------- + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # difference(self, other, grid_size=None) + # shapely 2.1: shows deprecation warning about positional 'grid_size' arg + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # difference(self, other, *, grid_size=None) + + @deprecate_positional(["grid_size"], category=DeprecationWarning) + def difference(self, other, grid_size=None): + """Return the difference of the geometries. + + Refer to `shapely.difference` for full documentation. + """ + return shapely.difference(self, other, grid_size=grid_size) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # intersection(self, other, grid_size=None) + # shapely 2.1: shows deprecation warning about positional 'grid_size' arg + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # intersection(self, other, *, grid_size=None) + + @deprecate_positional(["grid_size"], category=DeprecationWarning) + def intersection(self, other, grid_size=None): + """Return the intersection of the geometries. + + Refer to `shapely.intersection` for full documentation. + """ + return shapely.intersection(self, other, grid_size=grid_size) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # symmetric_difference(self, other, grid_size=None) + # shapely 2.1: shows deprecation warning about positional 'grid_size' arg + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # symmetric_difference(self, other, *, grid_size=None) + + @deprecate_positional(["grid_size"], category=DeprecationWarning) + def symmetric_difference(self, other, grid_size=None): + """Return the symmetric difference of the geometries. + + Refer to `shapely.symmetric_difference` for full documentation. + """ + return shapely.symmetric_difference(self, other, grid_size=grid_size) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # union(self, other, grid_size=None) + # shapely 2.1: shows deprecation warning about positional 'grid_size' arg + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # union(self, other, *, grid_size=None) + + @deprecate_positional(["grid_size"], category=DeprecationWarning) + def union(self, other, grid_size=None): + """Return the union of the geometries. + + Refer to `shapely.union` for full documentation. + """ + return shapely.union(self, other, grid_size=grid_size) + + # Unary predicates + # ---------------- + + @property + def has_z(self): + """True if the geometry's coordinate sequence(s) have z values.""" + return bool(shapely.has_z(self)) + + @property + def has_m(self): + """True if the geometry's coordinate sequence(s) have m values.""" + return bool(shapely.has_m(self)) + + @property + def is_empty(self): + """True if the set of points in this geometry is empty, else False.""" + return bool(shapely.is_empty(self)) + + @property + def is_ring(self): + """True if the geometry is a closed ring, else False.""" + return bool(shapely.is_ring(self)) + + @property + def is_closed(self): + """True if the geometry is closed, else False. + + Applicable only to linear geometries. + """ + if self.geom_type == "LinearRing": + return True + return bool(shapely.is_closed(self)) + + @property + def is_simple(self): + """True if the geometry is simple. + + Simple means that any self-intersections are only at boundary points. + """ + return bool(shapely.is_simple(self)) + + @property + def is_valid(self): + """True if the geometry is valid. + + The definition depends on sub-class. + """ + return bool(shapely.is_valid(self)) + + # Binary predicates + # ----------------- + + def relate(self, other): + """Return the DE-9IM intersection matrix for the two geometries (string).""" + return shapely.relate(self, other) + + def covers(self, other): + """Return True if the geometry covers the other, else False.""" + return _maybe_unpack(shapely.covers(self, other)) + + def covered_by(self, other): + """Return True if the geometry is covered by the other, else False.""" + return _maybe_unpack(shapely.covered_by(self, other)) + + def contains(self, other): + """Return True if the geometry contains the other, else False.""" + return _maybe_unpack(shapely.contains(self, other)) + + def contains_properly(self, other): + """Return True if the geometry completely contains the other. + + There should be no common boundary points. + + Refer to `shapely.contains_properly` for full documentation. + """ + return _maybe_unpack(shapely.contains_properly(self, other)) + + def crosses(self, other): + """Return True if the geometries cross, else False.""" + return _maybe_unpack(shapely.crosses(self, other)) + + def disjoint(self, other): + """Return True if geometries are disjoint, else False.""" + return _maybe_unpack(shapely.disjoint(self, other)) + + def equals(self, other): + """Return True if geometries are equal, else False. + + This method considers point-set equality (or topological + equality), and is equivalent to (self.within(other) & + self.contains(other)). + + Examples + -------- + >>> from shapely import LineString + >>> LineString( + ... [(0, 0), (2, 2)] + ... ).equals( + ... LineString([(0, 0), (1, 1), (2, 2)]) + ... ) + True + + Returns + ------- + bool + + """ + return _maybe_unpack(shapely.equals(self, other)) + + def intersects(self, other): + """Return True if geometries intersect, else False.""" + return _maybe_unpack(shapely.intersects(self, other)) + + def overlaps(self, other): + """Return True if geometries overlap, else False.""" + return _maybe_unpack(shapely.overlaps(self, other)) + + def touches(self, other): + """Return True if geometries touch, else False.""" + return _maybe_unpack(shapely.touches(self, other)) + + def within(self, other): + """Return True if geometry is within the other, else False.""" + return _maybe_unpack(shapely.within(self, other)) + + def dwithin(self, other, distance): + """Return True if geometry is within a given distance from the other. + + Refer to `shapely.dwithin` for full documentation. + """ + return _maybe_unpack(shapely.dwithin(self, other, distance)) + + def equals_exact(self, other, tolerance=0.0, *, normalize=False): + """Return True if the geometries are equivalent within the tolerance. + + Refer to :func:`~shapely.equals_exact` for full documentation. + + Parameters + ---------- + other : BaseGeometry + The other geometry object in this comparison. + tolerance : float, optional (default: 0.) + Absolute tolerance in the same units as coordinates. + normalize : bool, optional (default: False) + If True, normalize the two geometries so that the coordinates are + in the same order. + + .. versionadded:: 2.1.0 + + Examples + -------- + >>> from shapely import LineString + >>> LineString( + ... [(0, 0), (2, 2)] + ... ).equals_exact( + ... LineString([(0, 0), (1, 1), (2, 2)]), + ... 1e-6 + ... ) + False + + Returns + ------- + bool + + """ + return _maybe_unpack( + shapely.equals_exact(self, other, tolerance, normalize=normalize) + ) + + def relate_pattern(self, other, pattern): + """Return True if the DE-9IM relationship code satisfies the pattern.""" + return _maybe_unpack(shapely.relate_pattern(self, other, pattern)) + + # Linear referencing + # ------------------ + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # line_locate_point(self, other, normalized=False) + # shapely 2.1: shows deprecation warning about positional 'normalized' + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # line_locate_point(self, other, *, normalized=False) + + @deprecate_positional(["normalized"], category=DeprecationWarning) + def line_locate_point(self, other, normalized=False): + """Return the distance of this geometry to a point nearest the specified point. + + If the normalized arg is True, return the distance normalized to the + length of the linear geometry. + + Alias of `project`. + """ + return _maybe_unpack( + shapely.line_locate_point(self, other, normalized=normalized) + ) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # project(self, other, normalized=False) + # shapely 2.1: shows deprecation warning about positional 'normalized' + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'other' + # project(self, other, *, normalized=False) + + @deprecate_positional(["normalized"], category=DeprecationWarning) + def project(self, other, normalized=False): + """Return the distance of geometry to a point nearest the specified point. + + If the normalized arg is True, return the distance normalized to the + length of the linear geometry. + + Alias of `line_locate_point`. + """ + return _maybe_unpack( + shapely.line_locate_point(self, other, normalized=normalized) + ) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # line_interpolate_point(self, distance, normalized=False) + # shapely 2.1: shows deprecation warning about positional 'normalized' + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'distance' + # line_interpolate_point(self, distance, *, normalized=False) + + @deprecate_positional(["normalized"], category=DeprecationWarning) + def line_interpolate_point(self, distance, normalized=False): + """Return a point at the specified distance along a linear geometry. + + Negative length values are taken as measured in the reverse + direction from the end of the geometry. Out-of-range index + values are handled by clamping them to the valid range of values. + If the normalized arg is True, the distance will be interpreted as a + fraction of the geometry's length. + + Alias of `interpolate`. + """ + return shapely.line_interpolate_point(self, distance, normalized=normalized) + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # interpolate(self, distance, normalized=False) + # shapely 2.1: shows deprecation warning about positional 'normalized' + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'distance' + # interpolate(self, distance, *, normalized=False) + + @deprecate_positional(["normalized"], category=DeprecationWarning) + def interpolate(self, distance, normalized=False): + """Return a point at the specified distance along a linear geometry. + + Negative length values are taken as measured in the reverse + direction from the end of the geometry. Out-of-range index + values are handled by clamping them to the valid range of values. + If the normalized arg is True, the distance will be interpreted as a + fraction of the geometry's length. + + Alias of `line_interpolate_point`. + """ + return shapely.line_interpolate_point(self, distance, normalized=normalized) + + def segmentize(self, max_segment_length): + """Add vertices to line segments based on maximum segment length. + + Additional vertices will be added to every line segment in an input geometry + so that segments are no longer than the provided maximum segment length. New + vertices will evenly subdivide each segment. + + Only linear components of input geometries are densified; other geometries + are returned unmodified. + + Parameters + ---------- + max_segment_length : float or array_like + Additional vertices will be added so that all line segments are no + longer this value. Must be greater than 0. + + Examples + -------- + >>> from shapely import LineString, Polygon + >>> LineString([(0, 0), (0, 10)]).segmentize(max_segment_length=5) + + >>> Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]).segmentize(max_segment_length=5) + + + """ # noqa: E501 + return shapely.segmentize(self, max_segment_length) + + def reverse(self): + """Return a copy of this geometry with the order of coordinates reversed. + + If the geometry is a polygon with interior rings, the interior rings are also + reversed. + + Points are unchanged. + + See Also + -------- + is_ccw : Checks if a geometry is clockwise. + + Examples + -------- + >>> from shapely import LineString, Polygon + >>> LineString([(0, 0), (1, 2)]).reverse() + + >>> Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]).reverse() + + + """ + return shapely.reverse(self) + + +class BaseMultipartGeometry(BaseGeometry): + """Base class for collections of multiple geometries.""" + + __slots__ = [] + + @property + def coords(self): + """Not implemented. + + Sub-geometries may have coordinate sequences, but multi-part geometries + do not. + """ + raise NotImplementedError( + "Sub-geometries may have coordinate sequences, " + "but multi-part geometries do not" + ) + + @property + def geoms(self): + """Access to the contained geometries.""" + return GeometrySequence(self) + + def __bool__(self): + """Return True if the geometry is not empty, else False.""" + return self.is_empty is False + + def __eq__(self, other): + """Return True if geometries are equal, else False.""" + if not isinstance(other, BaseGeometry): + return NotImplemented + return ( + type(other) is type(self) + and len(self.geoms) == len(other.geoms) + and all(a == b for a, b in zip(self.geoms, other.geoms)) + ) + + def __hash__(self): + """Return the hash value of the geometry.""" + return super().__hash__() + + def svg(self, scale_factor=1.0, color=None): + """Return a group of SVG elements for the multipart geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG stroke-width. Default is 1. + color : str, optional + Hex string for stroke or fill color. Default is to use "#66cc99" + if geometry is valid, and "#ff3333" if invalid. + + """ + if self.is_empty: + return "" + if color is None: + color = "#66cc99" if self.is_valid else "#ff3333" + return "" + "".join(p.svg(scale_factor, color) for p in self.geoms) + "" + + +class GeometrySequence: + """Iterative access to members of a homogeneous multipart geometry.""" + + # Attributes + # ---------- + # _parent : object + # Parent (Shapely) geometry + _parent = None + + def __init__(self, parent): + """Initialize the sequence with a parent geometry.""" + self._parent = parent + + def _get_geom_item(self, i): + return shapely.get_geometry(self._parent, i) + + def __iter__(self): + """Iterate over the geometries in the sequence.""" + for i in range(self.__len__()): + yield self._get_geom_item(i) + + def __len__(self): + """Return the number of geometries in the sequence.""" + return shapely.get_num_geometries(self._parent) + + def __getitem__(self, key): + """Access a geometry in the sequence by index or slice.""" + m = self.__len__() + if isinstance(key, (int, np.integer)): + if key + m < 0 or key >= m: + raise IndexError("index out of range") + if key < 0: + i = m + key + else: + i = key + return self._get_geom_item(i) + elif isinstance(key, slice): + res = [] + start, stop, stride = key.indices(m) + for i in range(start, stop, stride): + res.append(self._get_geom_item(i)) + return type(self._parent)(res or None) + else: + raise TypeError("key must be an index or slice") + + +class EmptyGeometry(BaseGeometry): + """An empty geometry.""" + + def __new__(self): + """Create an empty geometry.""" + warn( + "The 'EmptyGeometry()' constructor to create an empty geometry is " + "deprecated, and will raise an error in the future. Use one of the " + "geometry subclasses instead, for example 'GeometryCollection()'.", + ShapelyDeprecationWarning, + stacklevel=2, + ) + return shapely.from_wkt("GEOMETRYCOLLECTION EMPTY") diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/collection.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/collection.py new file mode 100644 index 0000000000000000000000000000000000000000..51879a07bb37abad03c89d82cd4dc14b600a3242 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/collection.py @@ -0,0 +1,58 @@ +"""Multi-part collections of geometries.""" + +import shapely +from shapely.geometry.base import BaseGeometry, BaseMultipartGeometry + + +class GeometryCollection(BaseMultipartGeometry): + """Collection of one or more geometries that can be of different types. + + Parameters + ---------- + geoms : list + A list of shapely geometry instances, which may be of varying geometry + types. + + Attributes + ---------- + geoms : sequence + A sequence of Shapely geometry instances + + Examples + -------- + Create a GeometryCollection with a Point and a LineString + + >>> from shapely import GeometryCollection, LineString, Point + >>> p = Point(51, -1) + >>> l = LineString([(52, -1), (49, 2)]) + >>> gc = GeometryCollection([p, l]) + + """ + + __slots__ = [] + + def __new__(self, geoms=None): + """Create a new GeometryCollection.""" + if isinstance(geoms, BaseGeometry): + # TODO(shapely-2.0) do we actually want to split Multi-part geometries? + # this is needed for the split() tests + if hasattr(geoms, "geoms"): + geoms = geoms.geoms + else: + geoms = [geoms] + elif geoms is None or len(geoms) == 0: + # TODO better empty constructor + return shapely.from_wkt("GEOMETRYCOLLECTION EMPTY") + + return shapely.geometrycollections(geoms) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the geometry collection.""" + geometries = [] + for geom in self.geoms: + geometries.append(geom.__geo_interface__) + return dict(type="GeometryCollection", geometries=geometries) + + +shapely.lib.registry[7] = GeometryCollection diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/geo.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/geo.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1de81ae5a7265704cf24d27e1bf23eddb39c8e --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/geo.py @@ -0,0 +1,143 @@ +"""Geometry factories based on the geo interface.""" + +import numpy as np + +from shapely.errors import GeometryTypeError +from shapely.geometry.collection import GeometryCollection +from shapely.geometry.linestring import LineString +from shapely.geometry.multilinestring import MultiLineString +from shapely.geometry.multipoint import MultiPoint +from shapely.geometry.multipolygon import MultiPolygon +from shapely.geometry.point import Point +from shapely.geometry.polygon import LinearRing, Polygon + + +def _is_coordinates_empty(coordinates): + """Identify if coordinates or subset of coordinates are empty.""" + if coordinates is None: + return True + + if isinstance(coordinates, (list, tuple, np.ndarray)): + if len(coordinates) == 0: + return True + return all(map(_is_coordinates_empty, coordinates)) + else: + return False + + +def _empty_shape_for_no_coordinates(geom_type): + """Return empty counterpart for geom_type.""" + if geom_type == "point": + return Point() + elif geom_type == "multipoint": + return MultiPoint() + elif geom_type == "linestring": + return LineString() + elif geom_type == "multilinestring": + return MultiLineString() + elif geom_type == "polygon": + return Polygon() + elif geom_type == "multipolygon": + return MultiPolygon() + else: + raise GeometryTypeError(f"Unknown geometry type: {geom_type!r}") + + +def box(minx, miny, maxx, maxy, ccw=True): + """Return a rectangular polygon with configurable normal vector.""" + coords = [(maxx, miny), (maxx, maxy), (minx, maxy), (minx, miny)] + if not ccw: + coords = coords[::-1] + return Polygon(coords) + + +def shape(context): + """Return a new, independent geometry with coordinates copied from the context. + + Changes to the original context will not be reflected in the geometry + object. + + Parameters + ---------- + context : + a GeoJSON-like dict, which provides a "type" member describing the type + of the geometry and "coordinates" member providing a list of coordinates, + or an object which implements __geo_interface__. + + Returns + ------- + Geometry object + + Examples + -------- + Create a Point from GeoJSON, and then create a copy using __geo_interface__. + + >>> from shapely.geometry import shape + >>> context = {'type': 'Point', 'coordinates': [0, 1]} + >>> geom = shape(context) + >>> geom.geom_type == 'Point' + True + >>> geom.wkt + 'POINT (0 1)' + >>> geom2 = shape(geom) + >>> geom == geom2 + True + + """ + if hasattr(context, "__geo_interface__"): + ob = context.__geo_interface__ + else: + ob = context + geom_type = ob.get("type").lower() + + if geom_type == "feature": + # GeoJSON features must have a 'geometry' field. + ob = ob["geometry"] + geom_type = ob.get("type").lower() + + if "coordinates" in ob and _is_coordinates_empty(ob["coordinates"]): + return _empty_shape_for_no_coordinates(geom_type) + elif geom_type == "point": + return Point(ob["coordinates"]) + elif geom_type == "linestring": + return LineString(ob["coordinates"]) + elif geom_type == "linearring": + return LinearRing(ob["coordinates"]) + elif geom_type == "polygon": + return Polygon(ob["coordinates"][0], ob["coordinates"][1:]) + elif geom_type == "multipoint": + return MultiPoint(ob["coordinates"]) + elif geom_type == "multilinestring": + return MultiLineString(ob["coordinates"]) + elif geom_type == "multipolygon": + return MultiPolygon([[c[0], c[1:]] for c in ob["coordinates"]]) + elif geom_type == "geometrycollection": + geoms = [shape(g) for g in ob.get("geometries", [])] + return GeometryCollection(geoms) + else: + raise GeometryTypeError(f"Unknown geometry type: {geom_type!r}") + + +def mapping(ob): + """Return a GeoJSON-like mapping. + + Input should be a Geometry or an object which implements __geo_interface__. + + Parameters + ---------- + ob : geometry or object + An object which implements __geo_interface__. + + Returns + ------- + dict + + Examples + -------- + >>> from shapely.geometry import mapping, Point + >>> pt = Point(0, 0) + >>> mapping(pt) + {'type': 'Point', 'coordinates': (0.0, 0.0)} + + """ + return ob.__geo_interface__ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/linestring.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/linestring.py new file mode 100644 index 0000000000000000000000000000000000000000..7019be2d87dea2c9f0e39846652a06197a7213f3 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/linestring.py @@ -0,0 +1,211 @@ +"""Line strings and related utilities.""" + +import numpy as np + +import shapely +from shapely.decorators import deprecate_positional +from shapely.geometry.base import JOIN_STYLE, BaseGeometry +from shapely.geometry.point import Point + +__all__ = ["LineString"] + + +class LineString(BaseGeometry): + """A geometry type composed of one or more line segments. + + A LineString is a one-dimensional feature and has a non-zero length but + zero area. It may approximate a curve and need not be straight. A LineString may + be closed. + + Parameters + ---------- + coordinates : sequence + A sequence of (x, y, [,z]) numeric coordinate pairs or triples, or + an array-like with shape (N, 2) or (N, 3). + Also can be a sequence of Point objects, or combination of both. + + Examples + -------- + Create a LineString with two segments + + >>> from shapely import LineString + >>> a = LineString([[0, 0], [1, 0], [1, 1]]) + >>> a.length + 2.0 + + """ + + __slots__ = [] + + def __new__(self, coordinates=None): + """Create a new LineString geometry.""" + if coordinates is None: + # empty geometry + # TODO better constructor + return shapely.from_wkt("LINESTRING EMPTY") + elif isinstance(coordinates, LineString): + if type(coordinates) is LineString: + # return original objects since geometries are immutable + return coordinates + else: + # LinearRing + # TODO convert LinearRing to LineString more directly + coordinates = coordinates.coords + else: + if hasattr(coordinates, "__array__"): + coordinates = np.asarray(coordinates) + if isinstance(coordinates, np.ndarray) and np.issubdtype( + coordinates.dtype, np.number + ): + pass + else: + # check coordinates on points + def _coords(o): + if isinstance(o, Point): + return o.coords[0] + else: + return [float(c) for c in o] + + coordinates = [_coords(o) for o in coordinates] + + if len(coordinates) == 0: + # empty geometry + # TODO better constructor + should shapely.linestrings handle this? + return shapely.from_wkt("LINESTRING EMPTY") + + geom = shapely.linestrings(coordinates) + if not isinstance(geom, LineString): + raise ValueError("Invalid values passed to LineString constructor") + return geom + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the LineString geometry.""" + return {"type": "LineString", "coordinates": tuple(self.coords)} + + def svg(self, scale_factor=1.0, stroke_color=None, opacity=None): + """Return SVG polyline element for the LineString geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG stroke-width. Default is 1. + stroke_color : str, optional + Hex string for stroke color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.8 + + """ + if self.is_empty: + return "" + if stroke_color is None: + stroke_color = "#66cc99" if self.is_valid else "#ff3333" + if opacity is None: + opacity = 0.8 + pnt_format = " ".join(["{},{}".format(*c) for c in self.coords]) + return ( + f'' + ) + + @property + def xy(self): + """Separate arrays of X and Y coordinate values. + + Examples + -------- + >>> from shapely import LineString + >>> x, y = LineString([(0, 0), (1, 1)]).xy + >>> list(x) + [0.0, 1.0] + >>> list(y) + [0.0, 1.0] + + """ + return self.coords.xy + + # Note: future plan is to change this signature over a few releases: + # shapely 2.0: + # offset_curve(self, distance, quad_segs=16, ...) + # shapely 2.1: shows deprecation warning about positional 'quad_segs', etc. + # same signature as 2.0 + # shapely 2.2(?): enforce keyword-only arguments after 'distance' + # offset_curve(self, distance, *, quad_segs=16, ...) + + @deprecate_positional( + ["quad_segs", "join_style", "mitre_limit"], category=DeprecationWarning + ) + def offset_curve( + self, + distance, + quad_segs=16, + join_style=JOIN_STYLE.round, + mitre_limit=5.0, + ): + """Return a (Multi)LineString at a distance from the object. + + The side, left or right, is determined by the sign of the `distance` + parameter (negative for right side offset, positive for left side + offset). The resolution of the buffer around each vertex of the object + increases by increasing the `quad_segs` keyword parameter. + + The join style is for outside corners between line segments. Accepted + values are JOIN_STYLE.round (1), JOIN_STYLE.mitre (2), and + JOIN_STYLE.bevel (3). + + The mitre ratio limit is used for very sharp corners. It is the ratio + of the distance from the corner to the end of the mitred offset corner. + When two line segments meet at a sharp angle, a miter join will extend + far beyond the original geometry. To prevent unreasonable geometry, the + mitre limit allows controlling the maximum length of the join corner. + Corners with a ratio which exceed the limit will be beveled. + + Note: the behaviour regarding orientation of the resulting line + depends on the GEOS version. With GEOS < 3.11, the line retains the + same direction for a left offset (positive distance) or has reverse + direction for a right offset (negative distance), and this behaviour + was documented as such in previous Shapely versions. Starting with + GEOS 3.11, the function tries to preserve the orientation of the + original line. + """ + if mitre_limit == 0.0: + raise ValueError("Cannot compute offset from zero-length line segment") + elif not np.isfinite(distance): + raise ValueError("offset_curve distance must be finite") + return shapely.offset_curve( + self, + distance, + quad_segs=quad_segs, + join_style=join_style, + mitre_limit=mitre_limit, + ) + + def parallel_offset( + self, + distance, + side="right", + resolution=16, + join_style=JOIN_STYLE.round, + mitre_limit=5.0, + ): + """Alternative method to :meth:`offset_curve` method. + + Older alternative method to the :meth:`offset_curve` method, but uses + ``resolution`` instead of ``quad_segs`` and a ``side`` keyword + ('left' or 'right') instead of sign of the distance. This method is + kept for backwards compatibility for now, but is is recommended to + use :meth:`offset_curve` instead. + """ + if side == "right": + distance *= -1 + return self.offset_curve( + distance, + quad_segs=resolution, + join_style=join_style, + mitre_limit=mitre_limit, + ) + + +shapely.lib.registry[1] = LineString diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/multilinestring.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/multilinestring.py new file mode 100644 index 0000000000000000000000000000000000000000..551e77a2b9455b578e85f931c10a39d9f88f9fca --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/multilinestring.py @@ -0,0 +1,95 @@ +"""Collections of linestrings and related utilities.""" + +import shapely +from shapely.errors import EmptyPartError +from shapely.geometry import linestring +from shapely.geometry.base import BaseMultipartGeometry + +__all__ = ["MultiLineString"] + + +class MultiLineString(BaseMultipartGeometry): + """A collection of one or more LineStrings. + + A MultiLineString has non-zero length and zero area. + + Parameters + ---------- + lines : sequence + A sequence LineStrings, or a sequence of line-like coordinate + sequences or array-likes (see accepted input for LineString). + + Attributes + ---------- + geoms : sequence + A sequence of LineStrings + + Examples + -------- + Construct a MultiLineString containing two LineStrings. + + >>> from shapely import MultiLineString + >>> lines = MultiLineString([[[0, 0], [1, 2]], [[4, 4], [5, 6]]]) + + """ + + __slots__ = [] + + def __new__(self, lines=None): + """Create a new MultiLineString geometry.""" + if not lines: + # allow creation of empty multilinestrings, to support unpickling + # TODO better empty constructor + return shapely.from_wkt("MULTILINESTRING EMPTY") + elif isinstance(lines, MultiLineString): + return lines + + lines = getattr(lines, "geoms", lines) + subs = [] + for item in lines: + line = linestring.LineString(item) + if line.is_empty: + raise EmptyPartError( + "Can't create MultiLineString with empty component" + ) + subs.append(line) + + if len(lines) == 0: + return shapely.from_wkt("MULTILINESTRING EMPTY") + + return shapely.multilinestrings(subs) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping interface for this MultiLineString.""" + return { + "type": "MultiLineString", + "coordinates": tuple(tuple(c for c in g.coords) for g in self.geoms), + } + + def svg(self, scale_factor=1.0, stroke_color=None, opacity=None): + """Return a group of SVG polyline elements for the LineString geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG stroke-width. Default is 1. + stroke_color : str, optional + Hex string for stroke color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.8 + + """ + if self.is_empty: + return "" + if stroke_color is None: + stroke_color = "#66cc99" if self.is_valid else "#ff3333" + return ( + "" + + "".join(p.svg(scale_factor, stroke_color, opacity) for p in self.geoms) + + "" + ) + + +shapely.lib.registry[5] = MultiLineString diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/multipoint.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/multipoint.py new file mode 100644 index 0000000000000000000000000000000000000000..235046a3328dcdb1315c18e11b377426efeb754f --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/multipoint.py @@ -0,0 +1,104 @@ +"""Collections of points and related utilities.""" + +import numpy as np + +import shapely +from shapely.errors import EmptyPartError +from shapely.geometry import point +from shapely.geometry.base import BaseMultipartGeometry + +__all__ = ["MultiPoint"] + + +class MultiPoint(BaseMultipartGeometry): + """A collection of one or more Points. + + A MultiPoint has zero area and zero length. + + Parameters + ---------- + points : sequence + A sequence of Points, or a sequence of (x, y [,z]) numeric coordinate + pairs or triples, or an array-like of shape (N, 2) or (N, 3). + + Attributes + ---------- + geoms : sequence + A sequence of Points + + Examples + -------- + Construct a MultiPoint containing two Points + + >>> from shapely import MultiPoint, Point + >>> ob = MultiPoint([[0.0, 0.0], [1.0, 2.0]]) + >>> len(ob.geoms) + 2 + >>> type(ob.geoms[0]) == Point + True + + """ + + __slots__ = [] + + def __new__(self, points=None): + """Create a new MultiPoint geometry.""" + if points is None: + # allow creation of empty multipoints, to support unpickling + # TODO better empty constructor + return shapely.from_wkt("MULTIPOINT EMPTY") + elif isinstance(points, MultiPoint): + return points + elif len(points) == 0: + return shapely.from_wkt("MULTIPOINT EMPTY") + + if isinstance(points, np.ndarray) and np.issubdtype(points.dtype, np.number): + subs = shapely.points(points) + if not subs.ndim == 1: + raise ValueError("Invalid values passed to MultiPoint constructor") + if shapely.is_empty(subs).any(): + raise EmptyPartError("Can't create MultiPoint with empty component") + else: + subs = [] + for item in points: + p = point.Point(item) + if p.is_empty: + raise EmptyPartError("Can't create MultiPoint with empty component") + subs.append(p) + + return shapely.multipoints(subs) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping interface for this MultiPoint.""" + return { + "type": "MultiPoint", + "coordinates": tuple(g.coords[0] for g in self.geoms), + } + + def svg(self, scale_factor=1.0, fill_color=None, opacity=None): + """Return a group of SVG circle elements for the MultiPoint geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG circle diameters. Default is 1. + fill_color : str, optional + Hex string for fill color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.6 + + """ + if self.is_empty: + return "" + if fill_color is None: + fill_color = "#66cc99" if self.is_valid else "#ff3333" + return ( + "" + + "".join(p.svg(scale_factor, fill_color, opacity) for p in self.geoms) + + "" + ) + + +shapely.lib.registry[4] = MultiPoint diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/multipolygon.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/multipolygon.py new file mode 100644 index 0000000000000000000000000000000000000000..073fd86665208978989456fb825c2e1be4afed12 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/multipolygon.py @@ -0,0 +1,125 @@ +"""Collections of polygons and related utilities.""" + +import shapely +from shapely.geometry import polygon +from shapely.geometry.base import BaseMultipartGeometry + +__all__ = ["MultiPolygon"] + + +class MultiPolygon(BaseMultipartGeometry): + """A collection of one or more Polygons. + + If component polygons overlap the collection is invalid and some + operations on it may fail. + + Parameters + ---------- + polygons : sequence + A sequence of Polygons, or a sequence of (shell, holes) tuples + where shell is the sequence representation of a linear ring + (see LinearRing) and holes is a sequence of such linear rings. + + Attributes + ---------- + geoms : sequence + A sequence of `Polygon` instances + + Examples + -------- + Construct a MultiPolygon from a sequence of coordinate tuples + + >>> from shapely import MultiPolygon, Polygon + >>> ob = MultiPolygon([ + ... ( + ... ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), + ... [((0.1,0.1), (0.1,0.2), (0.2,0.2), (0.2,0.1))] + ... ) + ... ]) + >>> len(ob.geoms) + 1 + >>> type(ob.geoms[0]) == Polygon + True + + """ + + __slots__ = [] + + def __new__(self, polygons=None): + """Create a new MultiPolygon geometry.""" + if polygons is None: + # allow creation of empty multipolygons, to support unpickling + # TODO better empty constructor + return shapely.from_wkt("MULTIPOLYGON EMPTY") + elif isinstance(polygons, MultiPolygon): + return polygons + + polygons = getattr(polygons, "geoms", polygons) + # remove None and empty polygons from list of Polygons + polygons = [p for p in polygons if p] + + L = len(polygons) + + # Bail immediately if we have no input points. + if L == 0: + return shapely.from_wkt("MULTIPOLYGON EMPTY") + + # This function does not accept sequences of MultiPolygons: there is + # no implicit flattening. + if any(isinstance(p, MultiPolygon) for p in polygons): + raise ValueError("Sequences of multi-polygons are not valid arguments") + + subs = [] + for i in range(L): + ob = polygons[i] + if not isinstance(ob, polygon.Polygon): + shell = ob[0] + if len(ob) > 1: + holes = ob[1] + else: + holes = None + p = polygon.Polygon(shell, holes) + else: + p = polygon.Polygon(ob) + subs.append(p) + + return shapely.multipolygons(subs) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the MultiPolygon geometry.""" + allcoords = [] + for geom in self.geoms: + coords = [] + coords.append(tuple(geom.exterior.coords)) + for hole in geom.interiors: + coords.append(tuple(hole.coords)) + allcoords.append(tuple(coords)) + return {"type": "MultiPolygon", "coordinates": allcoords} + + def svg(self, scale_factor=1.0, fill_color=None, opacity=None): + """Return group of SVG path elements for the MultiPolygon geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG stroke-width. Default is 1. + fill_color : str, optional + Hex string for fill color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.6 + + """ + if self.is_empty: + return "" + if fill_color is None: + fill_color = "#66cc99" if self.is_valid else "#ff3333" + return ( + "" + + "".join(p.svg(scale_factor, fill_color, opacity) for p in self.geoms) + + "" + ) + + +shapely.lib.registry[6] = MultiPolygon diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/point.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/point.py new file mode 100644 index 0000000000000000000000000000000000000000..217410709695080fbb0f76031595df72f6083934 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/point.py @@ -0,0 +1,166 @@ +"""Points and related utilities.""" + +import numpy as np + +import shapely +from shapely.errors import DimensionError +from shapely.geometry.base import BaseGeometry + +__all__ = ["Point"] + + +class Point(BaseGeometry): + """A geometry type that represents a single coordinate. + + Each coordinate has x, y and possibly z and/or m values. + + A point is a zero-dimensional feature and has zero length and zero area. + + Parameters + ---------- + args : float, or sequence of floats + The coordinates can either be passed as a single parameter, or as + individual float values using multiple parameters: + + 1) 1 parameter: a sequence or array-like of with 2 or 3 values. + 2) 2 or 3 parameters (float): x, y, and possibly z. + + Attributes + ---------- + x, y, z, m : float + Coordinate values + + Examples + -------- + Constructing the Point using separate parameters for x and y: + + >>> from shapely import Point + >>> p = Point(1.0, -1.0) + + Constructing the Point using a list of x, y coordinates: + + >>> p = Point([1.0, -1.0]) + >>> print(p) + POINT (1 -1) + >>> p.y + -1.0 + >>> p.x + 1.0 + + """ + + __slots__ = [] + + def __new__(self, *args): + """Create a new Point geometry.""" + if len(args) == 0: + # empty geometry + # TODO better constructor + return shapely.from_wkt("POINT EMPTY") + elif len(args) > 3: + raise TypeError(f"Point() takes at most 3 arguments ({len(args)} given)") + elif len(args) == 1: + coords = args[0] + if isinstance(coords, Point): + return coords + + # Accept either (x, y) or [(x, y)] + if not hasattr(coords, "__getitem__"): # generators + coords = list(coords) + coords = np.asarray(coords).squeeze() + else: + # 2 or 3 args + coords = np.array(args).squeeze() + + if coords.ndim > 1: + raise ValueError( + f"Point() takes only scalar or 1-size vector arguments, got {args}" + ) + if not np.issubdtype(coords.dtype, np.number): + coords = [float(c) for c in coords] + geom = shapely.points(coords) + if not isinstance(geom, Point): + raise ValueError("Invalid values passed to Point constructor") + return geom + + # Coordinate getters and setters + + @property + def x(self): + """Return x coordinate.""" + return float(shapely.get_x(self)) + + @property + def y(self): + """Return y coordinate.""" + return float(shapely.get_y(self)) + + @property + def z(self): + """Return z coordinate.""" + z = shapely.get_z(self) + if np.isnan(z) and not shapely.has_z(self): + raise DimensionError("This point has no z coordinate.") + return float(z) + + @property + def m(self): + """Return m coordinate. + + .. versionadded:: 2.1.0 + Also requires GEOS 3.12.0 or later. + """ + if not shapely.has_m(self): + raise DimensionError("This point has no m coordinate.") + return float(shapely.get_m(self)) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the Point geometry.""" + coords = self.coords + return {"type": "Point", "coordinates": coords[0] if len(coords) > 0 else ()} + + def svg(self, scale_factor=1.0, fill_color=None, opacity=None): + """Return SVG circle element for the Point geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG circle diameter. Default is 1. + fill_color : str, optional + Hex string for fill color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.6 + + """ + if self.is_empty: + return "" + if fill_color is None: + fill_color = "#66cc99" if self.is_valid else "#ff3333" + if opacity is None: + opacity = 0.6 + return ( + f'' + ) + + @property + def xy(self): + """Separate arrays of X and Y coordinate values. + + Examples + -------- + >>> from shapely import Point + >>> x, y = Point(0, 0).xy + >>> list(x) + [0.0] + >>> list(y) + [0.0] + + """ + return self.coords.xy + + +shapely.lib.registry[0] = Point diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/polygon.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/polygon.py new file mode 100644 index 0000000000000000000000000000000000000000..c7793e785f73e7c6b7d23a6d66206f9af02d0fa0 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/geometry/polygon.py @@ -0,0 +1,345 @@ +"""Polygons and their linear ring components.""" + +import numpy as np + +import shapely +from shapely import _geometry_helpers +from shapely.algorithms.cga import signed_area # noqa +from shapely.errors import TopologicalError +from shapely.geometry.base import BaseGeometry +from shapely.geometry.linestring import LineString +from shapely.geometry.point import Point + +__all__ = ["LinearRing", "Polygon", "orient"] + + +def _unpickle_linearring(wkb): + linestring = shapely.from_wkb(wkb) + srid = shapely.get_srid(linestring) + linearring = _geometry_helpers.linestring_to_linearring(linestring) + if srid: + linearring = shapely.set_srid(linearring, srid) + return linearring + + +class LinearRing(LineString): + """Geometry type composed of one or more line segments that forms a closed loop. + + A LinearRing is a closed, one-dimensional feature. + A LinearRing that crosses itself or touches itself at a single point is + invalid and operations on it may fail. + + Parameters + ---------- + coordinates : sequence + A sequence of (x, y [,z]) numeric coordinate pairs or triples, or + an array-like with shape (N, 2) or (N, 3). + Also can be a sequence of Point objects. + + Notes + ----- + Rings are automatically closed. There is no need to specify a final + coordinate pair identical to the first. + + Examples + -------- + Construct a square ring. + + >>> from shapely import LinearRing + >>> ring = LinearRing( ((0, 0), (0, 1), (1 ,1 ), (1 , 0)) ) + >>> ring.is_closed + True + >>> list(ring.coords) + [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)] + >>> ring.length + 4.0 + + """ + + __slots__ = [] + + def __new__(self, coordinates=None): + """Create a new LinearRing geometry.""" + if coordinates is None: + # empty geometry + # TODO better way? + return shapely.from_wkt("LINEARRING EMPTY") + elif isinstance(coordinates, LineString): + if type(coordinates) is LinearRing: + # return original objects since geometries are immutable + return coordinates + elif not coordinates.is_valid: + raise TopologicalError("An input LineString must be valid.") + else: + # LineString + # TODO convert LineString to LinearRing more directly? + coordinates = coordinates.coords + + else: + if hasattr(coordinates, "__array__"): + coordinates = np.asarray(coordinates) + if isinstance(coordinates, np.ndarray) and np.issubdtype( + coordinates.dtype, np.number + ): + pass + else: + # check coordinates on points + def _coords(o): + if isinstance(o, Point): + return o.coords[0] + else: + return [float(c) for c in o] + + coordinates = np.array([_coords(o) for o in coordinates]) + if not np.issubdtype(coordinates.dtype, np.number): + # conversion of coords to 2D array failed, this might be due + # to inconsistent coordinate dimensionality + raise ValueError("Inconsistent coordinate dimensionality") + + if len(coordinates) == 0: + # empty geometry + # TODO better constructor + should shapely.linearrings handle this? + return shapely.from_wkt("LINEARRING EMPTY") + + geom = shapely.linearrings(coordinates) + if not isinstance(geom, LinearRing): + raise ValueError("Invalid values passed to LinearRing constructor") + return geom + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the LinearRing geometry.""" + return {"type": "LinearRing", "coordinates": tuple(self.coords)} + + def __reduce__(self): + """Pickle support. + + WKB doesn't differentiate between LineString and LinearRing so we + need to move the coordinate sequence into the correct geometry type + """ + return (_unpickle_linearring, (shapely.to_wkb(self, include_srid=True),)) + + @property + def is_ccw(self): + """True if the ring is oriented counter clock-wise.""" + return bool(shapely.is_ccw(self)) + + @property + def is_simple(self): + """True if the geometry is simple. + + Simple means that any self-intersections are only at boundary points. + """ + return bool(shapely.is_simple(self)) + + +shapely.lib.registry[2] = LinearRing + + +class InteriorRingSequence: + _parent = None + _ndim = None + _index = 0 + _length = 0 + + def __init__(self, parent): + self._parent = parent + self._ndim = parent._ndim + + def __iter__(self): + self._index = 0 + self._length = self.__len__() + return self + + def __next__(self): + if self._index < self._length: + ring = self._get_ring(self._index) + self._index += 1 + return ring + else: + raise StopIteration + + def __len__(self): + return shapely.get_num_interior_rings(self._parent) + + def __getitem__(self, key): + m = self.__len__() + if isinstance(key, int): + if key + m < 0 or key >= m: + raise IndexError("index out of range") + if key < 0: + i = m + key + else: + i = key + return self._get_ring(i) + elif isinstance(key, slice): + res = [] + start, stop, stride = key.indices(m) + for i in range(start, stop, stride): + res.append(self._get_ring(i)) + return res + else: + raise TypeError("key must be an index or slice") + + def _get_ring(self, i): + return shapely.get_interior_ring(self._parent, i) + + +class Polygon(BaseGeometry): + """A geometry type representing an area that is enclosed by a linear ring. + + A polygon is a two-dimensional feature and has a non-zero area. It may + have one or more negative-space "holes" which are also bounded by linear + rings. If any rings cross each other, the feature is invalid and + operations on it may fail. + + Parameters + ---------- + shell : sequence + A sequence of (x, y [,z]) numeric coordinate pairs or triples, or + an array-like with shape (N, 2) or (N, 3). + Also can be a sequence of Point objects. + holes : sequence + A sequence of objects which satisfy the same requirements as the + shell parameters above + + Attributes + ---------- + exterior : LinearRing + The ring which bounds the positive space of the polygon. + interiors : sequence + A sequence of rings which bound all existing holes. + + Examples + -------- + Create a square polygon with no holes + + >>> from shapely import Polygon + >>> coords = ((0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.)) + >>> polygon = Polygon(coords) + >>> polygon.area + 1.0 + + """ + + __slots__ = [] + + def __new__(self, shell=None, holes=None): + """Create a new Polygon geometry.""" + if shell is None: + # empty geometry + # TODO better way? + return shapely.from_wkt("POLYGON EMPTY") + elif isinstance(shell, Polygon): + # return original objects since geometries are immutable + return shell + else: + shell = LinearRing(shell) + + if holes is not None: + if len(holes) == 0: + # shapely constructor cannot handle holes=[] + holes = None + else: + holes = [LinearRing(ring) for ring in holes] + + geom = shapely.polygons(shell, holes=holes) + if not isinstance(geom, Polygon): + raise ValueError("Invalid values passed to Polygon constructor") + return geom + + @property + def exterior(self): + """Return the exterior ring of the polygon.""" + return shapely.get_exterior_ring(self) + + @property + def interiors(self): + """Return the sequence of interior rings of the polygon.""" + if self.is_empty: + return [] + return InteriorRingSequence(self) + + @property + def coords(self): + """Not implemented for polygons.""" + raise NotImplementedError( + "Component rings have coordinate sequences, but the polygon does not" + ) + + @property + def __geo_interface__(self): + """Return a GeoJSON-like mapping of the Polygon geometry.""" + if self.exterior == LinearRing(): + coords = [] + else: + coords = [tuple(self.exterior.coords)] + for hole in self.interiors: + coords.append(tuple(hole.coords)) + return {"type": "Polygon", "coordinates": tuple(coords)} + + def svg(self, scale_factor=1.0, fill_color=None, opacity=None): + """Return SVG path element for the Polygon geometry. + + Parameters + ---------- + scale_factor : float + Multiplication factor for the SVG stroke-width. Default is 1. + fill_color : str, optional + Hex string for fill color. Default is to use "#66cc99" if + geometry is valid, and "#ff3333" if invalid. + opacity : float + Float number between 0 and 1 for color opacity. Default value is 0.6 + + """ + if self.is_empty: + return "" + if fill_color is None: + fill_color = "#66cc99" if self.is_valid else "#ff3333" + if opacity is None: + opacity = 0.6 + exterior_coords = [["{},{}".format(*c) for c in self.exterior.coords]] + interior_coords = [ + ["{},{}".format(*c) for c in interior.coords] for interior in self.interiors + ] + path = " ".join( + [ + "M {} L {} z".format(coords[0], " L ".join(coords[1:])) + for coords in exterior_coords + interior_coords + ] + ) + return ( + f'' + ) + + @classmethod + def from_bounds(cls, xmin, ymin, xmax, ymax): + """Construct a `Polygon()` from spatial bounds.""" + return cls([(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]) + + +shapely.lib.registry[3] = Polygon + + +def orient(polygon, sign=1.0): + """Return an oriented polygon. + + It is recommended to use :func:`shapely.orient_polygons` instead. + + Parameters + ---------- + polygon : shapely.Polygon + sign : float, default 1. + The sign of the result's signed area. + A non-negative sign means that the coordinates of the geometry's exterior + rings will be oriented counter-clockwise. + + Returns + ------- + Geometry or array_like + + Refer to :func:`shapely.orient_polygons` for full documentation. + + """ + return shapely.orient_polygons(polygon, exterior_cw=sign < 0.0) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__init__.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/common.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3543fda6c1eefea5b0ceda05a1f8c2f854c0d036 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/common.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/test_constructive.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/test_constructive.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10bca20481a07bb6154dcd3b80d0e88ce46e6abb Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/test_constructive.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/test_decorators.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/test_decorators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0acb2362e43caacab4a8f3fddb11cbbbc2dd3827 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/test_decorators.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/test_testing.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/test_testing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98a962c0b11cbc30222d093aba5da12347badef2 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/__pycache__/test_testing.cpython-311.pyc differ diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/common.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/common.py new file mode 100644 index 0000000000000000000000000000000000000000..ca24b5562e9993294db577705e17675cbd6b207b --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/common.py @@ -0,0 +1,285 @@ +import warnings +from contextlib import contextmanager + +import numpy as np + +import shapely + +point_polygon_testdata = ( + shapely.points(np.arange(6), np.arange(6)), + shapely.box(2, 2, 4, 4), +) +# XY +point = shapely.Point(2, 3) +line_string = shapely.LineString([(0, 0), (1, 0), (1, 1)]) +linear_ring = shapely.LinearRing([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) +polygon = shapely.Polygon([(0, 0), (2, 0), (2, 2), (0, 2), (0, 0)]) +polygon_with_hole = shapely.Polygon( + [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], +) +multi_point = shapely.MultiPoint([(0, 0), (1, 2)]) +multi_line_string = shapely.MultiLineString([[(0, 0), (1, 2)]]) +multi_polygon = shapely.multipolygons( + [ + [(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)], + [(2.1, 2.1), (2.2, 2.1), (2.2, 2.2), (2.1, 2.2), (2.1, 2.1)], + ] +) +geometry_collection = shapely.GeometryCollection( + [shapely.Point(51, -1), shapely.LineString([(52, -1), (49, 2)])] +) +empty = shapely.from_wkt("GEOMETRYCOLLECTION EMPTY") +empty_point = shapely.from_wkt("POINT EMPTY") +empty_line_string = shapely.from_wkt("LINESTRING EMPTY") +empty_polygon = shapely.from_wkt("POLYGON EMPTY") +empty_multi_point = shapely.from_wkt("MULTIPOINT EMPTY") +empty_multi_line_string = shapely.from_wkt("MULTILINESTRING EMPTY") +empty_multi_polygon = shapely.from_wkt("MULTIPOLYGON EMPTY") +multi_point_empty = shapely.multipoints([empty_point]) +multi_line_string_empty = shapely.multilinestrings([empty_line_string]) +multi_polygon_empty = shapely.multipolygons([empty_polygon]) +geometry_collection_empty = shapely.geometrycollections([empty_line_string]) +# XYZ +point_z = shapely.Point(2, 3, 4) +line_string_z = shapely.LineString([(0, 0, 4), (1, 0, 4), (1, 1, 4)]) +linear_ring_z = shapely.LinearRing( + [(0, 0, 8), (1, 0, 7), (1, 1, 6), (0, 1, 9), (0, 0, 8)] +) +polygon_z = shapely.Polygon([(0, 0, 4), (2, 0, 4), (2, 2, 4), (0, 2, 4), (0, 0, 4)]) +polygon_with_hole_z = shapely.Polygon( + [(0, 0, 4), (0, 10, 4), (10, 10, 4), (10, 0, 4), (0, 0, 4)], + holes=[[(2, 2, 4), (2, 4, 4), (4, 4, 4), (4, 2, 4), (2, 2, 4)]], +) +multi_point_z = shapely.MultiPoint([(0, 0, 4), (1, 2, 4)]) +multi_line_string_z = shapely.MultiLineString([[(0, 0, 4), (1, 2, 4)]]) +multi_polygon_z = shapely.multipolygons( + [ + [(0, 0, 4), (1, 0, 4), (1, 1, 4), (0, 1, 4), (0, 0, 4)], + [(2.1, 2.1, 4), (2.2, 2.1, 4), (2.2, 2.2, 4), (2.1, 2.2, 4), (2.1, 2.1, 4)], + ] +) +geometry_collection_z = shapely.GeometryCollection([point_z, line_string_z]) +empty_geometry_collection_z = shapely.from_wkt("GEOMETRYCOLLECTION Z EMPTY") +empty_point_z = shapely.from_wkt("POINT Z EMPTY") +empty_line_string_z = shapely.from_wkt("LINESTRING Z EMPTY") +empty_polygon_z = shapely.from_wkt("POLYGON Z EMPTY") +empty_multi_point_z = shapely.from_wkt("MULTIPOINT Z EMPTY") +empty_multi_line_string_z = shapely.from_wkt("MULTILINESTRING Z EMPTY") +empty_multi_polygon_z = shapely.from_wkt("MULTIPOLYGON Z EMPTY") +multi_point_empty_z = shapely.multipoints([empty_point_z]) +multi_line_string_empty_z = shapely.multilinestrings([empty_line_string_z]) +multi_polygon_empty_z = shapely.multipolygons([empty_polygon_z]) +geometry_collection_empty_z = shapely.geometrycollections([empty_line_string_z]) +# XYM +point_m = shapely.from_wkt("POINT M (2 3 5)") +line_string_m = shapely.from_wkt("LINESTRING M (0 0 1, 1 0 2, 1 1 3)") +linear_ring_m = shapely.from_wkt("LINEARRING M (0 0 1, 1 0 2, 1 1 3, 0 1 2, 0 0 1)") +polygon_m = shapely.from_wkt("POLYGON M ((0 0 1, 2 0 2, 2 2 3, 0 2 2, 0 0 1))") +polygon_with_hole_m = shapely.from_wkt( + """POLYGON M ((0 0 1, 0 10 2, 10 10 3, 10 0 2, 0 0 1), + (2 2 6, 2 4 5, 4 4 4, 4 2 5, 2 2 6))""" +) +multi_point_m = shapely.from_wkt("MULTIPOINT M ((0 0 3), (1 2 5))") +multi_line_string_m = shapely.from_wkt("MULTILINESTRING M ((0 0 3, 1 2 5))") +multi_polygon_m = shapely.from_wkt( + """MULTIPOLYGON M (((0 0 1, 2 0 2, 2 2 3, 0 2 2, 0 0 1)), + ((2.1 2.1 1.1, 2.2 2.1 1.2, 2.2 2.2 1.3, 2.1 2.2 1.4, 2.1 2.1 1.1)))""" +) +geometry_collection_m = shapely.GeometryCollection([point_m, line_string_m]) +empty_geometry_collection_m = shapely.from_wkt("GEOMETRYCOLLECTION M EMPTY") +empty_point_m = shapely.from_wkt("POINT M EMPTY") +empty_line_string_m = shapely.from_wkt("LINESTRING M EMPTY") +empty_polygon_m = shapely.from_wkt("POLYGON M EMPTY") +empty_multi_point_m = shapely.from_wkt("MULTIPOINT M EMPTY") +empty_multi_line_string_m = shapely.from_wkt("MULTILINESTRING M EMPTY") +empty_multi_polygon_m = shapely.from_wkt("MULTIPOLYGON M EMPTY") +multi_point_empty_m = shapely.multipoints([empty_point_m]) +multi_line_string_empty_m = shapely.multilinestrings([empty_line_string_m]) +multi_polygon_empty_m = shapely.multipolygons([empty_polygon_m]) +geometry_collection_empty_m = shapely.geometrycollections([empty_line_string_m]) +# XYZM +point_zm = shapely.from_wkt("POINT ZM (2 3 4 5)") +line_string_zm = shapely.from_wkt("LINESTRING ZM (0 0 4 1, 1 0 4 2, 1 1 4 3)") +linear_ring_zm = shapely.from_wkt( + "LINEARRING ZM (0 0 1 8, 1 0 2 7, 1 1 3 6, 0 1 2 9, 0 0 1 8)" +) +polygon_zm = shapely.from_wkt( + "POLYGON ZM ((0 0 4 1, 2 0 4 2, 2 2 4 3, 0 2 4 2, 0 0 4 1))" +) +polygon_with_hole_zm = shapely.from_wkt( + """POLYGON ZM ((0 0 4 1, 0 10 4 2, 10 10 4 3, 10 0 4 2, 0 0 4 1), + (2 2 4 6, 2 4 4 5, 4 4 4 4, 4 2 4 5, 2 2 4 6))""" +) +multi_point_zm = shapely.from_wkt("MULTIPOINT ZM ((0 0 4 3), (1 2 4 5))") +multi_line_string_zm = shapely.from_wkt("MULTILINESTRING ZM ((0 0 4 3, 1 2 4 5))") +multi_polygon_zm = shapely.from_wkt( + """MULTIPOLYGON ZM (((0 0 4 1, 2 0 4 2, 2 2 4 3, 0 2 4 2, 0 0 4 1)), + ((2.1 2.1 4 1.1, 2.2 2.1 4 1.2, 2.2 2.2 4 1.3, 2.1 2.2 4 1.4, 2.1 2.1 4 1.1)))""" +) +geometry_collection_zm = shapely.GeometryCollection([point_zm, line_string_zm]) +empty_geometry_collection_zm = shapely.from_wkt("GEOMETRYCOLLECTION ZM EMPTY") +empty_point_zm = shapely.from_wkt("POINT ZM EMPTY") +empty_line_string_zm = shapely.from_wkt("LINESTRING ZM EMPTY") +empty_polygon_zm = shapely.from_wkt("POLYGON ZM EMPTY") +empty_multi_point_zm = shapely.from_wkt("MULTIPOINT ZM EMPTY") +empty_multi_line_string_zm = shapely.from_wkt("MULTILINESTRING ZM EMPTY") +empty_multi_polygon_zm = shapely.from_wkt("MULTIPOLYGON ZM EMPTY") +multi_point_empty_zm = shapely.multipoints([empty_point_zm]) +multi_line_string_empty_zm = shapely.multilinestrings([empty_line_string_zm]) +multi_polygon_empty_zm = shapely.multipolygons([empty_polygon_zm]) +geometry_collection_empty_zm = shapely.geometrycollections([empty_line_string_zm]) + +all_types = ( + point, + line_string, + linear_ring, + polygon, + polygon_with_hole, + multi_point, + multi_line_string, + multi_polygon, + geometry_collection, + empty, + empty_point, + empty_line_string, + empty_polygon, + empty_multi_point, + empty_multi_line_string, + empty_multi_polygon, + multi_point_empty, + multi_line_string_empty, + multi_polygon_empty, + geometry_collection_empty, +) + +all_types_z = ( + point_z, + line_string_z, + linear_ring_z, + polygon_z, + polygon_with_hole_z, + multi_point_z, + multi_line_string_z, + multi_polygon_z, + geometry_collection_z, + empty_geometry_collection_z, + empty_point_z, + empty_line_string_z, + empty_polygon_z, + empty_multi_point_z, + empty_multi_line_string_z, + empty_multi_polygon_z, + multi_point_empty_z, + multi_line_string_empty_z, + multi_polygon_empty_z, + geometry_collection_empty_z, +) +all_types_m = ( + point_m, + line_string_m, + linear_ring_m, + polygon_m, + polygon_with_hole_m, + multi_point_m, + multi_line_string_m, + multi_polygon_m, + geometry_collection_m, + empty_geometry_collection_m, + empty_point_m, + empty_line_string_m, + empty_polygon_m, + empty_multi_point_m, + empty_multi_line_string_m, + empty_multi_polygon_m, + multi_point_empty_m, + multi_line_string_empty_m, + multi_polygon_empty_m, + geometry_collection_empty_m, +) +all_types_zm = ( + point_zm, + line_string_zm, + linear_ring_zm, + polygon_zm, + polygon_with_hole_zm, + multi_point_zm, + multi_line_string_zm, + multi_polygon_zm, + geometry_collection_zm, + empty_geometry_collection_zm, + empty_point_zm, + empty_line_string_zm, + empty_polygon_zm, + empty_multi_point_zm, + empty_multi_line_string_zm, + empty_multi_polygon_zm, + multi_point_empty_zm, + multi_line_string_empty_zm, + multi_polygon_empty_zm, + geometry_collection_empty_zm, +) + + +@contextmanager +def ignore_invalid(condition=True): + if condition: + with np.errstate(invalid="ignore"): + yield + else: + yield + + +with ignore_invalid(): + line_string_nan = shapely.LineString([(np.nan, np.nan), (np.nan, np.nan)]) + + +@contextmanager +def ignore_warnings(geos_version, category): + if shapely.geos_version < geos_version: + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=category) + yield + else: + yield + + +def equal_geometries_abnormally_yield_unequal(geom): + """Older GEOS versions have various issues with "equals".""" + if geom.is_empty and shapely.get_num_geometries(geom) > 0: + if shapely.geos_version < (3, 10, 0) and geom.geom_type == "GeometryCollection": + return True + if shapely.geos_version < (3, 13, 0) and geom.geom_type.startswith("Multi"): + return True + return False + + +class ArrayLike: + """ + Simple numpy Array like class that implements the + ufunc protocol. + """ + + def __init__(self, array): + self._array = np.asarray(array) + + def __len__(self): + return len(self._array) + + def __getitem(self, key): + return self._array[key] + + def __iter__(self): + return self._array.__iter__() + + def __array__(self): + return np.asarray(self._array) + + def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): + if method == "__call__": + inputs = [ + arg._array if isinstance(arg, self.__class__) else arg for arg in inputs + ] + return self.__class__(ufunc(*inputs, **kwargs)) + else: + return NotImplemented diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/__init__.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_collection.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..68dc3408602e5724911b9bb58d732b395db0d036 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_collection.py @@ -0,0 +1,95 @@ +import numpy as np +import pytest + +import shapely +from shapely import GeometryCollection, LineString, Point, wkt +from shapely.geometry import shape + + +@pytest.fixture() +def geometrycollection_geojson(): + return { + "type": "GeometryCollection", + "geometries": [ + {"type": "Point", "coordinates": (0, 3, 0)}, + {"type": "LineString", "coordinates": ((2, 0), (1, 0))}, + ], + } + + +@pytest.mark.parametrize( + "geom", + [ + GeometryCollection(), + GeometryCollection([]), + shape({"type": "GeometryCollection", "geometries": []}), + wkt.loads("GEOMETRYCOLLECTION EMPTY"), + ], +) +def test_empty(geom): + assert geom.geom_type == "GeometryCollection" + assert geom.is_empty + assert len(geom.geoms) == 0 + assert list(geom.geoms) == [] + + +def test_empty_subgeoms(): + geom = GeometryCollection([Point(), LineString()]) + assert geom.geom_type == "GeometryCollection" + assert geom.is_empty + assert len(geom.geoms) == 2 + parts = list(geom.geoms) + if shapely.geos_version < (3, 9, 0): + # the accessed empty 2D point has a 3D coordseq on GEOS 3.8 + parts[0] = shapely.force_2d(parts[0]) + assert parts == [Point(), LineString()] + + +def test_child_with_deleted_parent(): + # test that we can remove a collection while keeping + # children around + a = LineString([(0, 0), (1, 1), (1, 2), (2, 2)]) + b = LineString([(0, 0), (1, 1), (2, 1), (2, 2)]) + collection = a.intersection(b) + + child = collection.geoms[0] + # delete parent of child + del collection + + # access geometry, this should not seg fault as 1.2.15 did + assert child.wkt is not None + + +def test_from_numpy_array(): + geoms = np.array([Point(0, 0), LineString([(1, 1), (2, 2)])]) + geom = GeometryCollection(geoms) + assert len(geom.geoms) == 2 + np.testing.assert_array_equal(geoms, geom.geoms) + + +def test_from_geojson(geometrycollection_geojson): + geom = shape(geometrycollection_geojson) + assert geom.geom_type == "GeometryCollection" + assert len(geom.geoms) == 2 + + geom_types = [g.geom_type for g in geom.geoms] + assert "Point" in geom_types + assert "LineString" in geom_types + + +def test_geointerface(geometrycollection_geojson): + geom = shape(geometrycollection_geojson) + assert geom.__geo_interface__ == geometrycollection_geojson + + +def test_len_raises(geometrycollection_geojson): + geom = shape(geometrycollection_geojson) + with pytest.raises(TypeError): + len(geom) + + +def test_numpy_object_array(): + geom = GeometryCollection([LineString([(0, 0), (1, 1)])]) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_coords.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_coords.py new file mode 100644 index 0000000000000000000000000000000000000000..113200570de0c9a16e1479810170406129f1e5a8 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_coords.py @@ -0,0 +1,127 @@ +import numpy as np +import pytest + +from shapely import LineString, geos_version +from shapely.tests.common import ( + line_string, + line_string_m, + line_string_z, + line_string_zm, + point, + point_m, + point_z, + point_zm, +) + + +class TestCoords: + """ + Shapely assumes contiguous C-order float64 data for internal ops. + Data should be converted to contiguous float64 if numpy exists. + c9a0707 broke this a little bit. + """ + + def test_data_promotion(self): + coords = np.array([[12, 34], [56, 78]], dtype=np.float32) + processed_coords = np.array(LineString(coords).coords) + + assert coords.tolist() == processed_coords.tolist() + + def test_data_destriding(self): + coords = np.array([[12, 34], [56, 78]], dtype=np.float32) + + # Easy way to introduce striding: reverse list order + processed_coords = np.array(LineString(coords[::-1]).coords) + + assert coords[::-1].tolist() == processed_coords.tolist() + + +class TestCoordsGetItem: + def test_index_coords(self): + c = [(float(x), float(-x)) for x in range(4)] + g = LineString(c) + for i in range(-4, 4): + assert g.coords[i] == c[i] + with pytest.raises(IndexError): + g.coords[4] + with pytest.raises(IndexError): + g.coords[-5] + + def test_index_coords_z(self): + c = [(float(x), float(-x), float(x * 2)) for x in range(4)] + g = LineString(c) + for i in range(-4, 4): + assert g.coords[i] == c[i] + with pytest.raises(IndexError): + g.coords[4] + with pytest.raises(IndexError): + g.coords[-5] + + def test_index_coords_misc(self): + g = LineString() # empty + with pytest.raises(IndexError): + g.coords[0] + with pytest.raises(TypeError): + g.coords[0.0] + + def test_slice_coords(self): + c = [(float(x), float(-x)) for x in range(4)] + g = LineString(c) + assert g.coords[1:] == c[1:] + assert g.coords[:-1] == c[:-1] + assert g.coords[::-1] == c[::-1] + assert g.coords[::2] == c[::2] + assert g.coords[:4] == c[:4] + assert g.coords[4:] == c[4:] == [] + + def test_slice_coords_z(self): + c = [(float(x), float(-x), float(x * 2)) for x in range(4)] + g = LineString(c) + assert g.coords[1:] == c[1:] + assert g.coords[:-1] == c[:-1] + assert g.coords[::-1] == c[::-1] + assert g.coords[::2] == c[::2] + assert g.coords[:4] == c[:4] + assert g.coords[4:] == c[4:] == [] + + +class TestXY: + """New geometry/coordseq method 'xy' makes numpy interop easier""" + + def test_arrays(self): + x, y = LineString([(0, 0), (1, 1)]).xy + assert len(x) == 2 + assert list(x) == [0.0, 1.0] + assert len(y) == 2 + assert list(y) == [0.0, 1.0] + + +@pytest.mark.parametrize("geom", [point, point_z, line_string, line_string_z]) +def test_coords_array_copy(geom): + """Test CoordinateSequence.__array__ method.""" + coord_seq = geom.coords + assert np.array(coord_seq) is not np.array(coord_seq) + assert np.array(coord_seq, copy=True) is not np.array(coord_seq, copy=True) + + # Behaviour of copy=False is different between NumPy 1.x and 2.x + if int(np.version.short_version.split(".", 1)[0]) >= 2: + with pytest.raises(ValueError, match="A copy is always created"): + np.array(coord_seq, copy=False) + else: + assert np.array(coord_seq, copy=False) is np.array(coord_seq, copy=False) + + +@pytest.mark.skipif(geos_version < (3, 12, 0), reason="GEOS < 3.12") +def test_coords_with_m(): + assert point_m.coords[:] == [(2.0, 3.0, 5.0)] + assert point_zm.coords[:] == [(2.0, 3.0, 4.0, 5.0)] + assert line_string_m.coords[:] == [ + (0.0, 0.0, 1.0), + (1.0, 0.0, 2.0), + (1.0, 1.0, 3.0), + ] + assert line_string_zm.coords[:] == [ + (0.0, 0.0, 4.0, 1.0), + (1.0, 0.0, 4.0, 2.0), + (1.0, 1.0, 4.0, 3.0), + ] diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_decimal.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_decimal.py new file mode 100644 index 0000000000000000000000000000000000000000..3ae805ae0d759baf3897907b22fad0f0dd6aea29 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_decimal.py @@ -0,0 +1,117 @@ +from decimal import Decimal + +import pytest + +from shapely import ( + GeometryCollection, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) + +items2d = [ + [(0.0, 0.0), (70.0, 120.0), (140.0, 0.0), (0.0, 0.0)], + [(60.0, 80.0), (80.0, 80.0), (70.0, 60.0), (60.0, 80.0)], +] + +items2d_mixed = [ + [ + (Decimal("0.0"), Decimal("0.0")), + (Decimal("70.0"), 120.0), + (140.0, Decimal("0.0")), + (0.0, 0.0), + ], + [ + (Decimal("60.0"), Decimal("80.0")), + (Decimal("80.0"), 80.0), + (70.0, Decimal("60.0")), + (60.0, 80.0), + ], +] + +items2d_decimal = [ + [ + (Decimal("0.0"), Decimal("0.0")), + (Decimal("70.0"), Decimal("120.0")), + (Decimal("140.0"), Decimal("0.0")), + (Decimal("0.0"), Decimal("0.0")), + ], + [ + (Decimal("60.0"), Decimal("80.0")), + (Decimal("80.0"), Decimal("80.0")), + (Decimal("70.0"), Decimal("60.0")), + (Decimal("60.0"), Decimal("80.0")), + ], +] + +items3d = [ + [(0.0, 0.0, 1), (70.0, 120.0, 2), (140.0, 0.0, 3), (0.0, 0.0, 1)], + [(60.0, 80.0, 1), (80.0, 80.0, 2), (70.0, 60.0, 3), (60.0, 80.0, 1)], +] + +items3d_mixed = [ + [ + (Decimal("0.0"), Decimal("0.0"), Decimal(1)), + (Decimal("70.0"), 120.0, Decimal(2)), + (140.0, Decimal("0.0"), 3), + (0.0, 0.0, 1), + ], + [ + (Decimal("60.0"), Decimal("80.0"), Decimal(1)), + (Decimal("80.0"), 80.0, 2), + (70.0, Decimal("60.0"), Decimal(3)), + (60.0, 80.0, 1), + ], +] + +items3d_decimal = [ + [ + (Decimal("0.0"), Decimal("0.0"), Decimal(1)), + (Decimal("70.0"), Decimal("120.0"), Decimal(2)), + (Decimal("140.0"), Decimal("0.0"), Decimal(3)), + (Decimal("0.0"), Decimal("0.0"), Decimal(1)), + ], + [ + (Decimal("60.0"), Decimal("80.0"), Decimal(1)), + (Decimal("80.0"), Decimal("80.0"), Decimal(2)), + (Decimal("70.0"), Decimal("60.0"), Decimal(3)), + (Decimal("60.0"), Decimal("80.0"), Decimal(1)), + ], +] + +all_geoms = [ + [ + Point(items[0][0]), + Point(*items[0][0]), + MultiPoint(items[0]), + LinearRing(items[0]), + LineString(items[0]), + MultiLineString(items), + Polygon(items[0]), + MultiPolygon( + [ + Polygon(items[1]), + Polygon(items[0], holes=items[1:]), + ] + ), + GeometryCollection([Point(items[0][0]), Polygon(items[0])]), + ] + for items in [ + items2d, + items2d_mixed, + items2d_decimal, + items3d, + items3d_mixed, + items3d_decimal, + ] +] + + +@pytest.mark.parametrize("geoms", list(zip(*all_geoms))) +def test_decimal(geoms): + assert geoms[0] == geoms[1] == geoms[2] + assert geoms[3] == geoms[4] == geoms[5] diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_emptiness.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_emptiness.py new file mode 100644 index 0000000000000000000000000000000000000000..005b2b8ecb88f5be4c72f63ce5737bc8a9bd9a68 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_emptiness.py @@ -0,0 +1,98 @@ +import math + +import numpy as np +import pytest + +from shapely import ( + GeometryCollection, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) +from shapely.geometry import mapping, shape +from shapely.geometry.base import BaseGeometry, EmptyGeometry + + +def empty_generator(): + return iter([]) + + +class TestEmptiness: + def test_empty_class(self): + with pytest.warns(FutureWarning): + g = EmptyGeometry() + assert g.is_empty + + def test_empty_base(self): + with pytest.warns(FutureWarning): + g = BaseGeometry() + assert g.is_empty + + def test_empty_point(self): + assert Point().is_empty + + def test_empty_multipoint(self): + assert MultiPoint().is_empty + + def test_empty_geometry_collection(self): + assert GeometryCollection().is_empty + + def test_empty_linestring(self): + assert LineString().is_empty + assert LineString(None).is_empty + assert LineString([]).is_empty + assert LineString(empty_generator()).is_empty + + def test_empty_multilinestring(self): + assert MultiLineString([]).is_empty + + def test_empty_polygon(self): + assert Polygon().is_empty + assert Polygon(None).is_empty + assert Polygon([]).is_empty + assert Polygon(empty_generator()).is_empty + + def test_empty_multipolygon(self): + assert MultiPolygon([]).is_empty + + def test_empty_linear_ring(self): + assert LinearRing().is_empty + assert LinearRing(None).is_empty + assert LinearRing([]).is_empty + assert LinearRing(empty_generator()).is_empty + + +def test_numpy_object_array(): + geoms = [Point(), GeometryCollection()] + arr = np.empty(2, object) + arr[:] = geoms + + +def test_shape_empty(): + empty_mp = MultiPolygon() + empty_json = mapping(empty_mp) + empty_shape = shape(empty_json) + assert empty_shape.is_empty + + +@pytest.mark.parametrize( + "geom", + [ + Point(), + LineString(), + Polygon(), + MultiPoint(), + MultiLineString(), + MultiPolygon(), + GeometryCollection(), + LinearRing(), + ], +) +def test_empty_geometry_bounds(geom): + """The bounds of an empty geometry is a tuple of NaNs""" + assert len(geom.bounds) == 4 + assert all(math.isnan(v) for v in geom.bounds) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_equality.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_equality.py new file mode 100644 index 0000000000000000000000000000000000000000..26704a1b9299030d743c8e493b133cd1320e9e86 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_equality.py @@ -0,0 +1,284 @@ +import numpy as np +import pytest + +import shapely +from shapely import LinearRing, LineString, MultiLineString, Point, Polygon +from shapely.tests.common import all_types, all_types_z, empty_point, ignore_invalid + +all_non_empty_types = np.array(all_types + all_types_z)[ + ~shapely.is_empty(all_types + all_types_z) +] + + +# TODO add all_types_m and all_types_zm once tranform supports M coordinates +@pytest.mark.parametrize("geom", all_types + all_types_z) +def test_equality(geom): + assert geom == geom # noqa: PLR0124 + transformed = shapely.transform(geom, lambda x: x, include_z=True) + if ( + shapely.geos_version < (3, 9, 0) + and isinstance(geom, Point) + and geom.is_empty + and not geom.has_z + ): + # the transformed empty 2D point has become 3D on GEOS 3.8 + transformed = shapely.force_2d(geom) + assert geom == transformed + assert not (geom != transformed) + + +@pytest.mark.parametrize( + "left, right", + # automated test cases with transformed coordinate values + [(geom, shapely.transform(geom, lambda x: x + 1)) for geom in all_non_empty_types] + + [ + # (slightly) different coordinate values + (LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 2)])), + (LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1 + 1e-12)])), + # different coordinate order + (LineString([(0, 0), (1, 1)]), LineString([(1, 1), (0, 0)])), + # different number of coordinates (but spatially equal) + (LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1), (1, 1)])), + (LineString([(0, 0), (1, 1)]), LineString([(0, 0), (0.5, 0.5), (1, 1)])), + # different order of sub-geometries + ( + MultiLineString([[(1, 1), (2, 2)], [(2, 2), (3, 3)]]), + MultiLineString([[(2, 2), (3, 3)], [(1, 1), (2, 2)]]), + ), + # M coordinates (don't work yet with automated cases) + pytest.param( + shapely.from_wkt("POINT M (0 0 0)"), + shapely.from_wkt("POINT M (0 0 1)"), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + pytest.param( + shapely.from_wkt("POINT ZM (0 0 0 0)"), + shapely.from_wkt("POINT ZM (0 0 0 1)"), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + ], +) +def test_equality_false(left, right): + assert left != right + assert not (left == right) + + +with ignore_invalid(): + cases1 = [ + (LineString([(0, 1), (2, np.nan)]), LineString([(0, 1), (2, np.nan)])), + ( + LineString([(0, 1), (np.nan, np.nan)]), + LineString([(0, 1), (np.nan, np.nan)]), + ), + (LineString([(np.nan, 1), (2, 3)]), LineString([(np.nan, 1), (2, 3)])), + (LineString([(0, np.nan), (2, 3)]), LineString([(0, np.nan), (2, 3)])), + ( + LineString([(np.nan, np.nan), (np.nan, np.nan)]), + LineString([(np.nan, np.nan), (np.nan, np.nan)]), + ), + # NaN as explicit Z coordinate + # TODO: if first z is NaN -> considered as 2D -> tested below explicitly + # ( + # LineString([(0, 1, np.nan), (2, 3, np.nan)]), + # LineString([(0, 1, np.nan), (2, 3, np.nan)]), + # ), + ( + LineString([(0, 1, 2), (2, 3, np.nan)]), + LineString([(0, 1, 2), (2, 3, np.nan)]), + ), + # ( + # LineString([(0, 1, np.nan), (2, 3, 4)]), + # LineString([(0, 1, np.nan), (2, 3, 4)]), + # ), + ] + + +@pytest.mark.parametrize("left, right", cases1) +def test_equality_with_nan(left, right): + assert left == right + assert not (left != right) + + +with ignore_invalid(): + cases2 = [ + ( + LineString([(0, 1, np.nan), (2, 3, np.nan)]), + LineString([(0, 1, np.nan), (2, 3, np.nan)]), + ), + ( + LineString([(0, 1, np.nan), (2, 3, 4)]), + LineString([(0, 1, np.nan), (2, 3, 4)]), + ), + ] + + +@pytest.mark.parametrize("left, right", cases2) +def test_equality_with_nan_z(left, right): + assert left == right + assert not (left != right) + + +with ignore_invalid(): + cases3 = [ + (LineString([(0, np.nan), (2, 3)]), LineString([(0, 1), (2, 3)])), + (LineString([(0, 1), (2, np.nan)]), LineString([(0, 1), (2, 3)])), + (LineString([(0, 1, np.nan), (2, 3, 4)]), LineString([(0, 1, 2), (2, 3, 4)])), + (LineString([(0, 1, 2), (2, 3, np.nan)]), LineString([(0, 1, 2), (2, 3, 4)])), + pytest.param( + shapely.from_wkt("POINT M (0 0 0)"), + shapely.from_wkt("POINT M (0 0 NaN)"), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + pytest.param( + shapely.from_wkt("POINT ZM (0 0 0 0)"), + shapely.from_wkt("POINT ZM (0 0 0 NaN)"), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + ] + + +@pytest.mark.parametrize("left, right", cases3) +def test_equality_with_nan_false(left, right): + assert left != right + + +def test_equality_with_nan_z_false(): + with ignore_invalid(): + left = LineString([(0, 1, np.nan), (2, 3, np.nan)]) + right = LineString([(0, 1, np.nan), (2, 3, 4)]) + + if shapely.geos_version < (3, 10, 0): + # GEOS <= 3.9 fill the NaN with 0, so the z dimension is different + assert left != right + elif shapely.geos_version < (3, 12, 0): + # GEOS 3.10-3.11 ignore NaN for Z also when explicitly created with 3D + # and so the geometries are considered as 2D (and thus z dimension is ignored) + assert left == right + else: + assert left != right + + +def test_equality_z(): + # different dimensionality + geom1 = Point(0, 1) + geom2 = Point(0, 1, 0) + assert geom1 != geom2 + + # different dimensionality with NaN z + geom2 = Point(0, 1, np.nan) + if shapely.geos_version < (3, 12, 0): + # GEOS 3.10-3.11 ignore NaN for Z also when explicitly created with 3D + # and so the geometries are considered as 2D (and thus z dimension is ignored) + assert geom1 == geom2 + else: + assert geom1 != geom2 + + +def test_equality_exact_type(): + # geometries with different type but same coord seq are not equal + geom1 = LineString([(0, 0), (1, 1), (0, 1), (0, 0)]) + geom2 = LinearRing([(0, 0), (1, 1), (0, 1), (0, 0)]) + geom3 = Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]) + assert geom1 != geom2 + assert geom1 != geom3 + assert geom2 != geom3 + + # empty with different type + geom1 = shapely.from_wkt("POINT EMPTY") + geom2 = shapely.from_wkt("LINESTRING EMPTY") + assert geom1 != geom2 + + +def test_equality_polygon(): + # different exterior rings + geom1 = shapely.from_wkt("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))") + geom2 = shapely.from_wkt("POLYGON ((0 0, 10 0, 10 10, 0 15, 0 0))") + assert geom1 != geom2 + + # different number of holes + geom1 = shapely.from_wkt( + "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 2 1, 2 2, 1 1))" + ) + geom2 = shapely.from_wkt( + "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 2 1, 2 2, 1 1), " + "(3 3, 4 3, 4 4, 3 3))" + ) + assert geom1 != geom2 + + # different order of holes + geom1 = shapely.from_wkt( + "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (3 3, 4 3, 4 4, 3 3), " + "(1 1, 2 1, 2 2, 1 1))" + ) + geom2 = shapely.from_wkt( + "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0), (1 1, 2 1, 2 2, 1 1), " + "(3 3, 4 3, 4 4, 3 3))" + ) + assert geom1 != geom2 + + +@pytest.mark.parametrize("geom", all_types) +def test_comparison_notimplemented(geom): + # comparing to a non-geometry class should return NotImplemented in __eq__ + # to ensure proper delegation to other (eg to ensure comparison of scalar + # with array works) + # https://github.com/shapely/shapely/issues/1056 + assert geom.__eq__(1) is NotImplemented + + # with array + arr = np.array([geom, geom], dtype=object) + + result = arr == geom + assert isinstance(result, np.ndarray) + assert result.all() + + result = geom == arr + assert isinstance(result, np.ndarray) + assert result.all() + + result = arr != geom + assert isinstance(result, np.ndarray) + assert not result.any() + + result = geom != arr + assert isinstance(result, np.ndarray) + assert not result.any() + + +def test_comparison_not_supported(): + geom1 = Point(1, 1) + geom2 = Point(2, 2) + + with pytest.raises(TypeError, match="not supported between instances"): + assert geom1 > geom2 + + with pytest.raises(TypeError, match="not supported between instances"): + assert geom1 < geom2 + + with pytest.raises(TypeError, match="not supported between instances"): + assert geom1 >= geom2 + + with pytest.raises(TypeError, match="not supported between instances"): + assert geom1 <= geom2 + + +@pytest.mark.parametrize( + "geom", all_types + (shapely.points(np.nan, np.nan), empty_point) +) +def test_hash_same_equal(geom): + hash1 = hash(geom) + hash2 = hash(shapely.transform(geom, lambda x: x)) + assert hash1 == hash2, geom + + +@pytest.mark.parametrize("geom", all_non_empty_types) +def test_hash_same_not_equal(geom): + assert hash(geom) != hash(shapely.transform(geom, lambda x: x + 1)) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_format.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..36c0fa38654407ef96884e0fd8ef17fb8997e06c --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_format.py @@ -0,0 +1,118 @@ +import pytest + +from shapely import Point, Polygon, geos_version + + +def test_format_invalid(): + # check invalid spec formats + pt = Point(1, 2) + test_list = [ + ("5G", ValueError, "invalid format specifier"), + (".f", ValueError, "invalid format specifier"), + ("0.2e", ValueError, "invalid format specifier"), + (".1x", ValueError, "hex representation does not specify precision"), + ] + for format_spec, err, match in test_list: + with pytest.raises(err, match=match): + format(pt, format_spec) + + +def get_tst_format_point_params(): + xy1 = (0.12345678901234567, 1.2345678901234567e10) + xy2 = (-169.910918, -18.997564) + xyz3 = (630084, 4833438, 76) + test_list = [ + (".0f", xy1, "POINT (0 12345678901)", True), + (".1f", xy1, "POINT (0.1 12345678901.2)", True), + ("0.2f", xy2, "POINT (-169.91 -19.00)", True), + (".3F", (float("inf"), -float("inf")), "POINT (INF -INF)", True), + ] + if geos_version < (3, 10, 0): + # 'g' format varies depending on GEOS version + test_list += [ + (".1g", xy1, "POINT (0.1 1e+10)", True), + (".6G", xy1, "POINT (0.123457 1.23457E+10)", True), + ("0.12g", xy1, "POINT (0.123456789012 12345678901.2)", True), + ("0.4g", xy2, "POINT (-169.9 -19)", True), + ] + else: + test_list += [ + (".1g", xy1, "POINT (0.1 12345678901.2)", False), + (".6G", xy1, "POINT (0.123457 12345678901.234568)", False), + ("0.12g", xy1, "POINT (0.123456789012 12345678901.234568)", False), + ("g", xy2, "POINT (-169.910918 -18.997564)", False), + ("0.2g", xy2, "POINT (-169.91 -19)", False), + ] + # without precisions test GEOS rounding_precision=-1; different than Python + test_list += [ + ("f", (1, 2), f"POINT ({1:.16f} {2:.16f})", False), + ("F", xyz3, "POINT Z ({:.16f} {:.16f} {:.16f})".format(*xyz3), False), + ("g", xyz3, "POINT Z (630084 4833438 76)", False), + ] + return test_list + + +@pytest.mark.parametrize( + "format_spec, coords, expt_wkt, same_python_float", get_tst_format_point_params() +) +def test_format_point(format_spec, coords, expt_wkt, same_python_float): + pt = Point(*coords) + # basic checks + assert f"{pt}" == pt.wkt + assert format(pt, "") == pt.wkt + assert format(pt, "x") == pt.wkb_hex.lower() + assert format(pt, "X") == pt.wkb_hex + # check formatted WKT to expected + assert format(pt, format_spec) == expt_wkt, format_spec + # check Python's format consistency + text_coords = expt_wkt[expt_wkt.index("(") + 1 : expt_wkt.index(")")] + is_same = [] + for coord, expt_coord in zip(coords, text_coords.split()): + py_fmt_float = format(float(coord), format_spec) + if same_python_float: + assert py_fmt_float == expt_coord, format_spec + else: + is_same.append(py_fmt_float == expt_coord) + if not same_python_float: + assert not all(is_same), f"{format_spec!r} with {expt_wkt}" + + +def test_format_polygon(): + # check basic cases + poly = Point(0, 0).buffer(10, quad_segs=2) + assert f"{poly}" == poly.wkt + assert format(poly, "") == poly.wkt + assert format(poly, "x") == poly.wkb_hex.lower() + assert format(poly, "X") == poly.wkb_hex + + # Use f-strings with extra characters and rounding precision + if geos_version < (3, 13, 0): + assert f"<{poly:.2f}>" == ( + "" + ) + else: + assert f"<{poly:.2f}>" == ( + "" + ) + + # 'g' format varies depending on GEOS version + if geos_version < (3, 10, 0): + assert f"{poly:.2G}" == ( + "POLYGON ((10 0, 7.1 -7.1, 1.6E-14 -10, -7.1 -7.1, " + "-10 -3.2E-14, -7.1 7.1, -4.6E-14 10, 7.1 7.1, 10 0))" + ) + else: + assert f"{poly:.2G}" == ( + "POLYGON ((10 0, 7.07 -7.07, 0 -10, -7.07 -7.07, " + "-10 0, -7.07 7.07, 0 10, 7.07 7.07, 10 0))" + ) + + # check empty + empty = Polygon() + assert f"{empty}" == "POLYGON EMPTY" + assert format(empty, "") == empty.wkt + assert format(empty, ".2G") == empty.wkt + assert format(empty, "x") == empty.wkb_hex.lower() + assert format(empty, "X") == empty.wkb_hex diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_geometry_base.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_geometry_base.py new file mode 100644 index 0000000000000000000000000000000000000000..0314ccb43dd3b4c8cfff74ad4e6987a8fd9241b2 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_geometry_base.py @@ -0,0 +1,369 @@ +import platform +import weakref + +import numpy as np +import pytest + +import shapely +from shapely import ( + GeometryCollection, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) +from shapely.errors import ShapelyDeprecationWarning +from shapely.testing import assert_geometries_equal + + +def test_polygon(): + assert bool(Polygon()) is False + + +def test_linestring(): + assert bool(LineString()) is False + + +def test_point(): + assert bool(Point()) is False + + +def test_geometry_collection(): + assert bool(GeometryCollection()) is False + + +geometries_all_types = [ + Point(1, 1), + LinearRing([(0, 0), (1, 1), (0, 1), (0, 0)]), + LineString([(0, 0), (1, 1), (0, 1), (0, 0)]), + Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]), + MultiPoint([(1, 1)]), + MultiLineString([[(0, 0), (1, 1), (0, 1), (0, 0)]]), + MultiPolygon([Polygon([(0, 0), (1, 1), (0, 1), (0, 0)])]), + GeometryCollection([Point(1, 1)]), +] + + +@pytest.mark.skipif( + platform.python_implementation() == "PyPy", + reason="Setting custom attributes doesn't fail on PyPy", +) +@pytest.mark.parametrize("geom", geometries_all_types) +def test_setattr_disallowed(geom): + with pytest.raises(AttributeError): + geom.name = "test" + + +@pytest.mark.parametrize("geom", geometries_all_types) +def test_weakrefable(geom): + _ = weakref.ref(geom) + + +def test_base_class_not_callable(): + with pytest.raises(TypeError): + shapely.Geometry("POINT (1 1)") + + +def test_GeometryType_deprecated(): + geom = Point(1, 1) + + with pytest.warns(ShapelyDeprecationWarning): + geom_type = geom.geometryType() + + assert geom_type == geom.geom_type + + +def test_type_deprecated(): + geom = Point(1, 1) + + with pytest.warns(ShapelyDeprecationWarning): + geom_type = geom.type + + assert geom_type == geom.geom_type + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +def test_segmentize(): + line = LineString([(0, 0), (0, 10)]) + result = line.segmentize(max_segment_length=5) + assert result.equals(LineString([(0, 0), (0, 5), (0, 10)])) + + +def test_reverse(): + coords = [(0, 0), (1, 2)] + line = LineString(coords) + result = line.reverse() + assert result.coords[:] == coords[::-1] + + +@pytest.mark.parametrize( + "op", ["union", "intersection", "difference", "symmetric_difference"] +) +@pytest.mark.parametrize("grid_size", [0, 1, 2]) +def test_binary_op_grid_size(op, grid_size): + geom1 = shapely.box(0, 0, 2.5, 2.5) + geom2 = shapely.box(2, 2, 3, 3) + + result = getattr(geom1, op)(geom2, grid_size=grid_size) + expected = getattr(shapely, op)(geom1, geom2, grid_size=grid_size) + assert result == expected + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +def test_dwithin(): + point = Point(1, 1) + line = LineString([(0, 0), (0, 10)]) + assert point.dwithin(line, 0.5) is False + assert point.dwithin(line, 1.5) is True + + +def test_contains_properly(): + polygon = Polygon([(0, 0), (10, 10), (10, -10)]) + line = LineString([(0, 0), (10, 0)]) + assert polygon.contains_properly(line) is False + assert polygon.contains(line) is True + + +@pytest.mark.parametrize( + "op", ["convex_hull", "envelope", "oriented_envelope", "minimum_rotated_rectangle"] +) +def test_constructive_properties(op): + geom = LineString([(0, 0), (0, 10), (10, 10)]) + result = getattr(geom, op) + expected = getattr(shapely, op)(geom) + assert result == expected + + +@pytest.mark.parametrize( + "op", + [ + "crosses", + "contains", + "contains_properly", + "covered_by", + "covers", + "disjoint", + "equals", + "intersects", + "overlaps", + "touches", + "within", + ], +) +def test_array_argument_binary_predicates(op): + polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + points = shapely.points([(0, 0), (0.5, 0.5), (1, 1)]) + + result = getattr(polygon, op)(points) + assert isinstance(result, np.ndarray) + expected = np.array([getattr(polygon, op)(p) for p in points], dtype=bool) + np.testing.assert_array_equal(result, expected) + + # check scalar + result = getattr(polygon, op)(points[0]) + assert type(result) is bool + + +@pytest.mark.parametrize( + "op, kwargs", + [ + pytest.param( + "dwithin", + dict(distance=0.5), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10" + ), + ), + ("equals_exact", dict(tolerance=0.01)), + ("relate_pattern", dict(pattern="T*F**F***")), + ], +) +def test_array_argument_binary_predicates2(op, kwargs): + polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + points = shapely.points([(0, 0), (0.5, 0.5), (1, 1)]) + + result = getattr(polygon, op)(points, **kwargs) + assert isinstance(result, np.ndarray) + expected = np.array([getattr(polygon, op)(p, **kwargs) for p in points], dtype=bool) + np.testing.assert_array_equal(result, expected) + + # check scalar + result = getattr(polygon, op)(points[0], **kwargs) + assert type(result) is bool + + +@pytest.mark.parametrize( + "op", + [ + "difference", + "intersection", + "symmetric_difference", + "union", + ], +) +def test_array_argument_binary_geo(op): + box = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + polygons = shapely.buffer(shapely.points([(0, 0), (0.5, 0.5), (1, 1)]), 0.5) + + result = getattr(box, op)(polygons) + assert isinstance(result, np.ndarray) + expected = np.array([getattr(box, op)(g) for g in polygons], dtype=object) + assert_geometries_equal(result, expected) + + # check scalar + result = getattr(box, op)(polygons[0]) + assert isinstance(result, (Polygon, MultiPolygon)) + + +@pytest.mark.parametrize("op", ["distance", "hausdorff_distance"]) +def test_array_argument_float(op): + polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + points = shapely.points([(0, 0), (0.5, 0.5), (1, 1)]) + + result = getattr(polygon, op)(points) + assert isinstance(result, np.ndarray) + expected = np.array([getattr(polygon, op)(p) for p in points], dtype="float64") + np.testing.assert_array_equal(result, expected) + + # check scalar + result = getattr(polygon, op)(points[0]) + assert type(result) is float + + +@pytest.mark.parametrize("op", ["line_interpolate_point", "interpolate"]) +def test_array_argument_linear_point(op): + line = LineString([(0, 0), (0, 1), (1, 1)]) + distances = np.array([0, 0.5, 1]) + + result = getattr(line, op)(distances) + assert isinstance(result, np.ndarray) + expected = np.array( + [line.line_interpolate_point(d) for d in distances], dtype=object + ) + assert_geometries_equal(result, expected) + + # check scalar + result = getattr(line, op)(distances[0]) + assert isinstance(result, Point) + + +@pytest.mark.parametrize("op", ["line_locate_point", "project"]) +def test_array_argument_linear_float(op): + line = LineString([(0, 0), (0, 1), (1, 1)]) + points = shapely.points([(0, 0), (0.5, 0.5), (1, 1)]) + + result = getattr(line, op)(points) + assert isinstance(result, np.ndarray) + expected = np.array([line.line_locate_point(p) for p in points], dtype="float64") + np.testing.assert_array_equal(result, expected) + + # check scalar + result = getattr(line, op)(points[0]) + assert type(result) is float + + +def test_array_argument_buffer(): + point = Point(1, 1) + distances = np.array([0, 0.5, 1]) + + result = point.buffer(distances) + assert isinstance(result, np.ndarray) + expected = np.array([point.buffer(d) for d in distances], dtype=object) + assert_geometries_equal(result, expected) + + # check scalar + result = point.buffer(distances[0]) + assert isinstance(result, Polygon) + + +def test_buffer_deprecate_positional(): + point = Point(1, 1) + with pytest.deprecated_call( + match="positional argument `cap_style` for `buffer` is deprecated" + ): + point.buffer(1.0, 8, "round") + with pytest.deprecated_call( + match="positional arguments `cap_style` and `join_style` " + "for `buffer` are deprecated" + ): + point.buffer(1.0, 8, "round", "round") + with pytest.deprecated_call(): + point.buffer(1.0, 8, "round", "round", 5.0) + with pytest.deprecated_call(): + point.buffer(1.0, 8, "round", "round", 5.0, False) + + +def test_simplify_deprecate_positional(): + linestring = LineString([(0, 0), (1, 1)]) + with pytest.deprecated_call( + match="positional argument `preserve_topology` for `simplify` is deprecated" + ): + linestring.simplify(1.0, True) + + +def test_difference_deprecate_positional(): + point = Point(1, 1) + with pytest.deprecated_call( + match="positional argument `grid_size` for `difference` is deprecated" + ): + point.difference(point, None) + + +def test_intersection_deprecate_positional(): + point = Point(1, 1) + with pytest.deprecated_call( + match="positional argument `grid_size` for `intersection` is deprecated" + ): + point.intersection(point, None) + + +def test_symmetric_difference_deprecate_positional(): + point = Point(1, 1) + with pytest.deprecated_call( + match="positional argument `grid_size` for `symmetric_difference` is deprecated" + ): + point.symmetric_difference(point, None) + + +def test_union_deprecate_positional(): + point = Point(1, 1) + with pytest.deprecated_call( + match="positional argument `grid_size` for `union` is deprecated" + ): + point.union(point, None) + + +def test_line_locate_point_deprecate_positional(): + line_string = LineString([(1.0, 2.0), (3.0, 4.0)]) + with pytest.deprecated_call( + match="positional argument `normalized` for `line_locate_point` is deprecated" + ): + line_string.line_locate_point(Point(1, 1), False) + + +def test_project_deprecate_positional(): + line_string = LineString([(1.0, 2.0), (3.0, 4.0)]) + with pytest.deprecated_call( + match="positional argument `normalized` for `project` is deprecated" + ): + line_string.project(Point(1, 1), False) + + +def test_line_interpolate_point_deprecate_positional(): + line_string = LineString([(1.0, 2.0), (3.0, 4.0)]) + with pytest.deprecated_call( + match="positional argument `normalized` for `line_interpolate_point` " + "is deprecated" + ): + line_string.line_interpolate_point(0, False) + + +def test_interpolate_deprecate_positional(): + line_string = LineString([(1.0, 2.0), (3.0, 4.0)]) + with pytest.deprecated_call( + match="positional argument `normalized` for `interpolate` is deprecated" + ): + line_string.interpolate(0, False) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_hash.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_hash.py new file mode 100644 index 0000000000000000000000000000000000000000..f54f88548c2f4422d86a74900fcd5f7197e6b3ce --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_hash.py @@ -0,0 +1,28 @@ +import pytest + +import shapely +from shapely.affinity import translate +from shapely.geometry import GeometryCollection, LineString, MultiPoint, Point + + +@pytest.mark.parametrize( + "geom", + [ + Point(1, 2), + MultiPoint([(1, 2), (3, 4)]), + LineString([(1, 2), (3, 4)]), + Point(0, 0).buffer(1.0), + GeometryCollection([Point(1, 2), LineString([(1, 2), (3, 4)])]), + ], + ids=[ + "Point", + "MultiPoint", + "LineString", + "Polygon", + "GeometryCollection", + ], +) +def test_hash(geom): + h1 = hash(geom) + assert h1 == hash(shapely.from_wkb(geom.wkb)) + assert h1 != hash(translate(geom, 1.0, 2.0)) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_linestring.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_linestring.py new file mode 100644 index 0000000000000000000000000000000000000000..231c75aa4fb15d442fe1a09bfa5452ae66b61f75 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_linestring.py @@ -0,0 +1,232 @@ +import numpy as np +import pytest + +import shapely +from shapely import LinearRing, LineString, Point +from shapely.coords import CoordinateSequence + + +def test_from_coordinate_sequence(): + # From coordinate tuples + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + assert len(line.coords) == 2 + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + +def test_from_coordinate_sequence_z(): + line = LineString([(1.0, 2.0, 3.0), (3.0, 4.0, 5.0)]) + assert line.has_z + assert line.coords[:] == [(1.0, 2.0, 3.0), (3.0, 4.0, 5.0)] + + +def test_from_points(): + # From Points + line = LineString([Point(1.0, 2.0), Point(3.0, 4.0)]) + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + line = LineString([Point(1.0, 2.0), Point(3.0, 4.0)]) + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + +def test_from_mix(): + # From mix of tuples and Points + line = LineString([Point(1.0, 2.0), (2.0, 3.0), Point(3.0, 4.0)]) + assert line.coords[:] == [(1.0, 2.0), (2.0, 3.0), (3.0, 4.0)] + + +def test_from_linestring(): + # From another linestring + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + copy = LineString(line) + assert copy.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + assert copy.geom_type == "LineString" + + +def test_from_linearring(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + ring = LinearRing(coords) + copy = LineString(ring) + assert copy.coords[:] == coords + assert copy.geom_type == "LineString" + + +def test_from_linestring_z(): + coords = [(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)] + line = LineString(coords) + copy = LineString(line) + assert copy.coords[:] == coords + assert copy.geom_type == "LineString" + + +def test_from_generator(): + gen = (coord for coord in [(1.0, 2.0), (3.0, 4.0)]) + line = LineString(gen) + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + +def test_from_empty(): + line = LineString() + assert line.is_empty + assert isinstance(line.coords, CoordinateSequence) + assert line.coords[:] == [] + + line = LineString([]) + assert line.is_empty + assert isinstance(line.coords, CoordinateSequence) + assert line.coords[:] == [] + + +def test_from_numpy(): + # Construct from a numpy array + line = LineString(np.array([[1.0, 2.0], [3.0, 4.0]])) + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + +def test_numpy_empty_linestring_coords(): + # Check empty + line = LineString([]) + la = np.asarray(line.coords) + + assert la.shape == (0, 2) + + +def test_numpy_object_array(): + geom = LineString([(0.0, 0.0), (0.0, 1.0)]) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom + + +@pytest.mark.filterwarnings("ignore:Creating an ndarray from ragged nested sequences:") +def test_from_invalid_dim(): + # TODO(shapely-2.0) better error message? + # pytest.raises( + # ValueError, match="at least 2 coordinate tuples|at least 2 coordinates" + # ): + with pytest.raises(shapely.GEOSException): + LineString([(1, 2)]) + + # exact error depends on numpy version + with pytest.raises((ValueError, TypeError)): + LineString([(1, 2, 3), (4, 5)]) + + with pytest.raises((ValueError, TypeError)): + LineString([(1, 2), (3, 4, 5)]) + + msg = r"The ordinate \(last\) dimension should be 2 or 3, got {}" + with pytest.raises(ValueError, match=msg.format(4)): + LineString([(1, 2, 3, 4), (4, 5, 6, 7)]) + + with pytest.raises(ValueError, match=msg.format(1)): + LineString([(1,), (4,)]) + + +def test_from_single_coordinate(): + """Test for issue #486""" + coords = [[-122.185933073564, 37.3629353839073]] + with pytest.raises(shapely.GEOSException): + ls = LineString(coords) + ls.geom_type # caused segfault before fix + + +class TestLineString: + def test_linestring(self): + # From coordinate tuples + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + assert len(line.coords) == 2 + assert line.coords[:] == [(1.0, 2.0), (3.0, 4.0)] + + # Bounds + assert line.bounds == (1.0, 2.0, 3.0, 4.0) + + # Coordinate access + assert tuple(line.coords) == ((1.0, 2.0), (3.0, 4.0)) + assert line.coords[0] == (1.0, 2.0) + assert line.coords[1] == (3.0, 4.0) + with pytest.raises(IndexError): + line.coords[2] # index out of range + + # Geo interface + assert line.__geo_interface__ == { + "type": "LineString", + "coordinates": ((1.0, 2.0), (3.0, 4.0)), + } + + def test_linestring_empty(self): + # Test Non-operability of Null geometry + l_null = LineString() + assert l_null.wkt == "LINESTRING EMPTY" + assert l_null.length == 0.0 + + def test_equals_argument_order(self): + """ + Test equals predicate functions correctly regardless of the order + of the inputs. See issue #317. + """ + coords = ((0, 0), (1, 0), (1, 1), (0, 0)) + ls = LineString(coords) + lr = LinearRing(coords) + + assert ls.__eq__(lr) is False # previously incorrectly returned True + assert lr.__eq__(ls) is False + assert (ls == lr) is False + assert (lr == ls) is False + + ls_clone = LineString(coords) + lr_clone = LinearRing(coords) + + assert ls.__eq__(ls_clone) is True + assert lr.__eq__(lr_clone) is True + assert (ls == ls_clone) is True + assert (lr == lr_clone) is True + + def test_numpy_linestring_coords(self): + from numpy.testing import assert_array_equal + + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + expected = np.array([[1.0, 2.0], [3.0, 4.0]]) + + # Coordinate sequences can be adapted as well + la = np.asarray(line.coords) + assert_array_equal(la, expected) + + +def test_linestring_immutable(): + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + + with pytest.raises(AttributeError): + line.coords = [(-1.0, -1.0), (1.0, 1.0)] + + with pytest.raises(TypeError): + line.coords[0] = (-1.0, -1.0) + + +def test_linestring_array_coercion(): + # don't convert to array of coordinates, keep objects + line = LineString([(1.0, 2.0), (3.0, 4.0)]) + arr = np.array(line) + assert arr.ndim == 0 + assert arr.size == 1 + assert arr.dtype == np.dtype("object") + assert arr.item() == line + + +def test_offset_curve_deprecate_positional(): + line_string = LineString([(1.0, 2.0), (3.0, 4.0)]) + with pytest.deprecated_call( + match="positional argument `quad_segs` for `offset_curve` is deprecated" + ): + line_string.offset_curve(1.0, 8) + with pytest.deprecated_call( + match="positional arguments `quad_segs` and `join_style` " + "for `offset_curve` are deprecated" + ): + line_string.offset_curve(1.0, 8, "round") + with pytest.deprecated_call( + match="positional arguments `quad_segs`, `join_style`, and `mitre_limit` " + "for `offset_curve` are deprecated" + ): + line_string.offset_curve(1.0, 8, "round", 5.0) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multi.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multi.py new file mode 100644 index 0000000000000000000000000000000000000000..59dc043540f6808e878af7ebedd9b03aa126e751 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multi.py @@ -0,0 +1,11 @@ +import numpy as np + +test_int_types = [int, np.int16, np.int32, np.int64] + + +class MultiGeometryTestCase: + def subgeom_access_test(self, cls, geoms): + geom = cls(geoms) + for t in test_int_types: + for i, g in enumerate(geoms): + assert geom.geoms[t(i)] == g diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multilinestring.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multilinestring.py new file mode 100644 index 0000000000000000000000000000000000000000..637e66ab930230ec398596d87ba2e46073f69ea8 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multilinestring.py @@ -0,0 +1,77 @@ +import numpy as np +import pytest + +from shapely import LineString, MultiLineString +from shapely.errors import EmptyPartError +from shapely.geometry.base import dump_coords +from shapely.tests.geometry.test_multi import MultiGeometryTestCase + + +class TestMultiLineString(MultiGeometryTestCase): + def test_multilinestring(self): + # From coordinate tuples + geom = MultiLineString([[(1.0, 2.0), (3.0, 4.0)]]) + assert isinstance(geom, MultiLineString) + assert len(geom.geoms) == 1 + assert dump_coords(geom) == [[(1.0, 2.0), (3.0, 4.0)]] + + # From lines + a = LineString([(1.0, 2.0), (3.0, 4.0)]) + ml = MultiLineString([a]) + assert len(ml.geoms) == 1 + assert dump_coords(ml) == [[(1.0, 2.0), (3.0, 4.0)]] + + # From another multi-line + ml2 = MultiLineString(ml) + assert len(ml2.geoms) == 1 + assert dump_coords(ml2) == [[(1.0, 2.0), (3.0, 4.0)]] + + # Sub-geometry Access + geom = MultiLineString([(((0.0, 0.0), (1.0, 2.0)))]) + assert isinstance(geom.geoms[0], LineString) + assert dump_coords(geom.geoms[0]) == [(0.0, 0.0), (1.0, 2.0)] + with pytest.raises(IndexError): # index out of range + geom.geoms[1] + + # Geo interface + assert geom.__geo_interface__ == { + "type": "MultiLineString", + "coordinates": (((0.0, 0.0), (1.0, 2.0)),), + } + + def test_from_multilinestring_z(self): + coords1 = [(0.0, 1.0, 2.0), (3.0, 4.0, 5.0)] + coords2 = [(6.0, 7.0, 8.0), (9.0, 10.0, 11.0)] + + # From coordinate tuples + ml = MultiLineString([coords1, coords2]) + copy = MultiLineString(ml) + assert isinstance(copy, MultiLineString) + assert copy.geom_type == "MultiLineString" + assert len(copy.geoms) == 2 + assert dump_coords(copy.geoms[0]) == coords1 + assert dump_coords(copy.geoms[1]) == coords2 + + def test_numpy(self): + # Construct from a numpy array + geom = MultiLineString([np.array(((0.0, 0.0), (1.0, 2.0)))]) + assert isinstance(geom, MultiLineString) + assert len(geom.geoms) == 1 + assert dump_coords(geom) == [[(0.0, 0.0), (1.0, 2.0)]] + + def test_subgeom_access(self): + line0 = LineString([(0.0, 1.0), (2.0, 3.0)]) + line1 = LineString([(4.0, 5.0), (6.0, 7.0)]) + self.subgeom_access_test(MultiLineString, [line0, line1]) + + def test_create_multi_with_empty_component(self): + msg = "Can't create MultiLineString with empty component" + with pytest.raises(EmptyPartError, match=msg): + MultiLineString([LineString([(0, 0), (1, 1), (2, 2)]), LineString()]).wkt + + +def test_numpy_object_array(): + geom = MultiLineString([[[5.0, 6.0], [7.0, 8.0]]]) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multipoint.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multipoint.py new file mode 100644 index 0000000000000000000000000000000000000000..aedfce5499cd642ce16d0eeebe9f31a4162c9c99 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multipoint.py @@ -0,0 +1,93 @@ +import numpy as np +import pytest + +import shapely +from shapely import MultiPoint, Point +from shapely.errors import EmptyPartError +from shapely.geometry.base import dump_coords +from shapely.tests.geometry.test_multi import MultiGeometryTestCase + + +class TestMultiPoint(MultiGeometryTestCase): + def test_multipoint(self): + # From coordinate tuples + geom = MultiPoint([(1.0, 2.0), (3.0, 4.0)]) + assert len(geom.geoms) == 2 + assert dump_coords(geom) == [[(1.0, 2.0)], [(3.0, 4.0)]] + + # From points + geom = MultiPoint([Point(1.0, 2.0), Point(3.0, 4.0)]) + assert len(geom.geoms) == 2 + assert dump_coords(geom) == [[(1.0, 2.0)], [(3.0, 4.0)]] + + # From another multi-point + geom2 = MultiPoint(geom) + assert len(geom2.geoms) == 2 + assert dump_coords(geom2) == [[(1.0, 2.0)], [(3.0, 4.0)]] + + # Sub-geometry Access + assert isinstance(geom.geoms[0], Point) + assert geom.geoms[0].x == 1.0 + assert geom.geoms[0].y == 2.0 + with pytest.raises(IndexError): # index out of range + geom.geoms[2] + + # Geo interface + assert geom.__geo_interface__ == { + "type": "MultiPoint", + "coordinates": ((1.0, 2.0), (3.0, 4.0)), + } + + def test_multipoint_from_numpy(self): + # Construct from a numpy array + geom = MultiPoint(np.array([[0.0, 0.0], [1.0, 2.0]])) + assert isinstance(geom, MultiPoint) + assert len(geom.geoms) == 2 + assert dump_coords(geom) == [[(0.0, 0.0)], [(1.0, 2.0)]] + + def test_subgeom_access(self): + p0 = Point(1.0, 2.0) + p1 = Point(3.0, 4.0) + self.subgeom_access_test(MultiPoint, [p0, p1]) + + def test_create_multi_with_empty_component(self): + msg = "Can't create MultiPoint with empty component" + with pytest.raises(EmptyPartError, match=msg): + MultiPoint([Point(0, 0), Point()]) + + if shapely.geos_version < (3, 13, 0): + # for older GEOS, Point(NaN, NaN) is considered empty + with pytest.raises(EmptyPartError, match=msg): + MultiPoint([(0, 0), (np.nan, np.nan)]) + + with pytest.raises(EmptyPartError, match=msg): + MultiPoint(np.array([(0, 0), (np.nan, np.nan)])) + + else: + result = MultiPoint([(0, 0), (np.nan, np.nan)]) + expected = shapely.multipoints( + shapely.points([(0, 0), (np.nan, np.nan)], handle_nan="allow") + ) + assert result == expected + + +def test_multipoint_array_coercion(): + geom = MultiPoint([(1.0, 2.0), (3.0, 4.0)]) + arr = np.array(geom) + assert arr.ndim == 0 + assert arr.size == 1 + assert arr.dtype == np.dtype("object") + assert arr.item() == geom + + +def test_numpy_object_array(): + geom = MultiPoint([(1.0, 2.0), (3.0, 4.0)]) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom + + +def test_len_raises(): + geom = MultiPoint([[5.0, 6.0], [7.0, 8.0]]) + with pytest.raises(TypeError): + len(geom) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multipolygon.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multipolygon.py new file mode 100644 index 0000000000000000000000000000000000000000..0494951ff4984d7b1a992fe5b1f5d4998dd9dd3e --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_multipolygon.py @@ -0,0 +1,156 @@ +import numpy as np +import pytest + +from shapely import MultiPolygon, Polygon +from shapely.geometry.base import dump_coords +from shapely.tests.geometry.test_multi import MultiGeometryTestCase + + +class TestMultiPolygon(MultiGeometryTestCase): + def test_multipolygon(self): + # Empty + geom = MultiPolygon([]) + assert geom.is_empty + assert len(geom.geoms) == 0 + + # From coordinate tuples + coords = [ + ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), + [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))], + ) + ] + geom = MultiPolygon(coords) + assert isinstance(geom, MultiPolygon) + assert len(geom.geoms) == 1 + assert dump_coords(geom) == [ + [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + [(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)], + ] + ] + + # Or without holes + coords2 = [(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)),)] + geom = MultiPolygon(coords2) + assert isinstance(geom, MultiPolygon) + assert len(geom.geoms) == 1 + assert dump_coords(geom) == [ + [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + ] + ] + + # Or from polygons + p = Polygon( + ((0, 0), (0, 1), (1, 1), (1, 0)), + [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))], + ) + geom = MultiPolygon([p]) + assert len(geom.geoms) == 1 + assert dump_coords(geom) == [ + [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + [(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)], + ] + ] + + # None and empty polygons are dropped + geom_from_list_with_empty = MultiPolygon([p, None, Polygon()]) + assert geom_from_list_with_empty == geom + + # Or from a list of multiple polygons + geom_multiple_from_list = MultiPolygon([p, p]) + assert len(geom_multiple_from_list.geoms) == 2 + assert all(p == geom.geoms[0] for p in geom_multiple_from_list.geoms) + + # Or from a np.array of polygons + geom_multiple_from_array = MultiPolygon(np.array([p, p])) + assert geom_multiple_from_array == geom_multiple_from_list + + # Or from another multi-polygon + geom2 = MultiPolygon(geom) + assert len(geom2.geoms) == 1 + assert dump_coords(geom2) == [ + [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + [(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)], + ] + ] + + # Sub-geometry Access + assert isinstance(geom.geoms[0], Polygon) + assert dump_coords(geom.geoms[0]) == [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + [(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)], + ] + with pytest.raises(IndexError): # index out of range + geom.geoms[1] + + # Geo interface + assert geom.__geo_interface__ == { + "type": "MultiPolygon", + "coordinates": [ + ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)), + ((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)), + ) + ], + } + + def test_subgeom_access(self): + poly0 = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)]) + poly1 = Polygon([(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25)]) + self.subgeom_access_test(MultiPolygon, [poly0, poly1]) + + +def test_fail_list_of_multipolygons(): + """A list of multipolygons is not a valid multipolygon ctor argument""" + poly = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)]) + multi = MultiPolygon( + [ + ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), + [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))], + ) + ] + ) + with pytest.raises(ValueError): + MultiPolygon([multi]) + + with pytest.raises(ValueError): + MultiPolygon([poly, multi]) + + +def test_numpy_object_array(): + geom = MultiPolygon( + [ + ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), + [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))], + ) + ] + ) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_point.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_point.py new file mode 100644 index 0000000000000000000000000000000000000000..9995c89adb5946f95382b1cd1ee55defca43b87f --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_point.py @@ -0,0 +1,201 @@ +import numpy as np +import pytest + +from shapely import Point, geos_version +from shapely.coords import CoordinateSequence +from shapely.errors import DimensionError, UnsupportedGEOSVersionError + + +def test_from_coordinates(): + # Point + p = Point(1.0, 2.0) + assert p.coords[:] == [(1.0, 2.0)] + assert p.has_z is False + + # PointZ + p = Point(1.0, 2.0, 3.0) + assert p.coords[:] == [(1.0, 2.0, 3.0)] + assert p.has_z + + # empty + p = Point() + assert p.is_empty + assert isinstance(p.coords, CoordinateSequence) + assert p.coords[:] == [] + + +def test_from_sequence(): + # From single coordinate pair + p = Point((3.0, 4.0)) + assert p.coords[:] == [(3.0, 4.0)] + p = Point([3.0, 4.0]) + assert p.coords[:] == [(3.0, 4.0)] + + # From coordinate sequence + p = Point([(3.0, 4.0)]) + assert p.coords[:] == [(3.0, 4.0)] + p = Point([[3.0, 4.0]]) + assert p.coords[:] == [(3.0, 4.0)] + + # PointZ + p = Point((3.0, 4.0, 5.0)) + assert p.coords[:] == [(3.0, 4.0, 5.0)] + p = Point([3.0, 4.0, 5.0]) + assert p.coords[:] == [(3.0, 4.0, 5.0)] + p = Point([(3.0, 4.0, 5.0)]) + assert p.coords[:] == [(3.0, 4.0, 5.0)] + + +def test_from_numpy(): + # Construct from a numpy array + p = Point(np.array([1.0, 2.0])) + assert p.coords[:] == [(1.0, 2.0)] + + p = Point(np.array([1.0, 2.0, 3.0])) + assert p.coords[:] == [(1.0, 2.0, 3.0)] + + +def test_from_numpy_xy(): + # Construct from separate x, y numpy arrays - if those are length 1, + # this is allowed for compat with shapely 1.8 + # (https://github.com/shapely/shapely/issues/1587) + p = Point(np.array([1.0]), np.array([2.0])) + assert p.coords[:] == [(1.0, 2.0)] + + p = Point(np.array([1.0]), np.array([2.0]), np.array([3.0])) + assert p.coords[:] == [(1.0, 2.0, 3.0)] + + +def test_from_point(): + # From another point + p = Point(3.0, 4.0) + q = Point(p) + assert q.coords[:] == [(3.0, 4.0)] + + p = Point(3.0, 4.0, 5.0) + q = Point(p) + assert q.coords[:] == [(3.0, 4.0, 5.0)] + + +def test_from_generator(): + gen = (coord for coord in [(1.0, 2.0)]) + p = Point(gen) + assert p.coords[:] == [(1.0, 2.0)] + + +def test_from_invalid(): + with pytest.raises(TypeError, match="takes at most 3 arguments"): + Point(1, 2, 3, 4) + + # this worked in shapely 1.x, just ignoring the other coords + with pytest.raises( + ValueError, match="takes only scalar or 1-size vector arguments" + ): + Point([(2, 3), (11, 4)]) + + +class TestPoint: + def test_point(self): + # Test XY point + p = Point(1.0, 2.0) + assert p.x == 1.0 + assert type(p.x) is float + assert p.y == 2.0 + assert type(p.y) is float + assert p.coords[:] == [(1.0, 2.0)] + assert str(p) == p.wkt + assert p.has_z is False + with pytest.raises(DimensionError): + p.z + if geos_version >= (3, 12, 0): + assert p.has_m is False + with pytest.raises(DimensionError): + p.m + else: + with pytest.raises(UnsupportedGEOSVersionError): + p.m + + # Check XYZ point + p = Point(1.0, 2.0, 3.0) + assert p.coords[:] == [(1.0, 2.0, 3.0)] + assert str(p) == p.wkt + assert p.has_z is True + assert p.z == 3.0 + assert type(p.z) is float + if geos_version >= (3, 12, 0): + assert p.has_m is False + with pytest.raises(DimensionError): + p.m + + # TODO: Check XYM and XYZM points + + # Coordinate access + p = Point((3.0, 4.0)) + assert p.x == 3.0 + assert p.y == 4.0 + assert tuple(p.coords) == ((3.0, 4.0),) + assert p.coords[0] == (3.0, 4.0) + with pytest.raises(IndexError): # index out of range + p.coords[1] + + # Bounds + assert p.bounds == (3.0, 4.0, 3.0, 4.0) + + # Geo interface + assert p.__geo_interface__ == {"type": "Point", "coordinates": (3.0, 4.0)} + + def test_point_empty(self): + # Test Non-operability of Null geometry + p_null = Point() + assert p_null.wkt == "POINT EMPTY" + assert p_null.coords[:] == [] + assert p_null.area == 0.0 + + assert p_null.__geo_interface__ == {"type": "Point", "coordinates": ()} + + def test_coords(self): + # From Array.txt + p = Point(0.0, 0.0, 1.0) + coords = p.coords[0] + assert coords == (0.0, 0.0, 1.0) + + # Convert to Numpy array, passing through Python sequence + a = np.asarray(coords) + assert a.ndim == 1 + assert a.size == 3 + assert a.shape == (3,) + + +def test_point_immutable(): + p = Point(3.0, 4.0) + + with pytest.raises(AttributeError): + p.coords = (2.0, 1.0) + + with pytest.raises(TypeError): + p.coords[0] = (2.0, 1.0) + + +def test_point_array_coercion(): + # don't convert to array of coordinates, keep objects + p = Point(3.0, 4.0) + arr = np.array(p) + assert arr.ndim == 0 + assert arr.size == 1 + assert arr.dtype == np.dtype("object") + assert arr.item() == p + + +def test_numpy_empty_point_coords(): + pe = Point() + + # Access the coords + a = np.asarray(pe.coords) + assert a.shape == (0, 2) + + +def test_numpy_object_array(): + geom = Point(3.0, 4.0) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_polygon.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_polygon.py new file mode 100644 index 0000000000000000000000000000000000000000..21a67a461c28f7f18fc3f66a1e008335ebb30b2c --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/geometry/test_polygon.py @@ -0,0 +1,460 @@ +"""Polygons and Linear Rings""" + +import numpy as np +import pytest + +from shapely import LinearRing, LineString, Point, Polygon +from shapely.coords import CoordinateSequence +from shapely.errors import TopologicalError +from shapely.wkb import loads as load_wkb + + +def test_empty_linearring_coords(): + assert LinearRing().coords[:] == [] + + +def test_linearring_from_coordinate_sequence(): + expected_coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + + ring = LinearRing([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + assert ring.coords[:] == expected_coords + + ring = LinearRing([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + assert ring.coords[:] == expected_coords + + +def test_linearring_from_points(): + # From Points + expected_coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + + ring = LinearRing([Point(0.0, 0.0), Point(0.0, 1.0), Point(1.0, 1.0)]) + assert ring.coords[:] == expected_coords + + +def test_linearring_from_closed_linestring(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + line = LineString(coords) + ring = LinearRing(line) + assert len(ring.coords) == 4 + assert ring.coords[:] == coords + assert ring.geom_type == "LinearRing" + + +def test_linearring_from_unclosed_linestring(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + line = LineString(coords[:-1]) # Pass in unclosed line + ring = LinearRing(line) + assert len(ring.coords) == 4 + assert ring.coords[:] == coords + assert ring.geom_type == "LinearRing" + + +def test_linearring_from_invalid(): + coords = [(0.0, 0.0), (0.0, 0.0), (0.0, 0.0)] + line = LineString(coords) + assert not line.is_valid + with pytest.raises(TopologicalError): + LinearRing(line) + + +def test_linearring_from_too_short_linestring(): + # Creation of LinearRing request at least 3 coordinates (unclosed) or + # 4 coordinates (closed) + coords = [(0.0, 0.0), (1.0, 1.0)] + line = LineString(coords) + with pytest.raises(ValueError, match="requires at least 4 coordinates"): + LinearRing(line) + + +def test_linearring_from_linearring(): + coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + ring = LinearRing(coords) + assert ring.coords[:] == coords + + +def test_linearring_from_generator(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + gen = (coord for coord in coords) + ring = LinearRing(gen) + assert ring.coords[:] == coords + + +def test_linearring_from_empty(): + ring = LinearRing() + assert ring.is_empty + assert isinstance(ring.coords, CoordinateSequence) + assert ring.coords[:] == [] + + ring = LinearRing([]) + assert ring.is_empty + assert isinstance(ring.coords, CoordinateSequence) + assert ring.coords[:] == [] + + +def test_linearring_from_numpy(): + # Construct from a numpy array + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + + ring = LinearRing(np.array(coords)) + assert ring.coords[:] == [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + + +def test_numpy_linearring_coords(): + from numpy.testing import assert_array_equal + + ring = LinearRing([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + ra = np.asarray(ring.coords) + expected = np.asarray([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]) + assert_array_equal(ra, expected) + + +def test_numpy_empty_linearring_coords(): + ring = LinearRing() + assert np.asarray(ring.coords).shape == (0, 2) + + +def test_numpy_object_array(): + geom = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + ar = np.empty(1, object) + ar[:] = [geom] + assert ar[0] == geom + + +def test_polygon_from_coordinate_sequence(): + coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + + # Construct a polygon, exterior ring only + polygon = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + assert polygon.exterior.coords[:] == coords + assert len(polygon.interiors) == 0 + + polygon = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) + assert polygon.exterior.coords[:] == coords + assert len(polygon.interiors) == 0 + + +def test_polygon_from_coordinate_sequence_with_holes(): + coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + + # Interior rings (holes) + polygon = Polygon(coords, [[(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25)]]) + assert polygon.exterior.coords[:] == coords + assert len(polygon.interiors) == 1 + assert len(polygon.interiors[0].coords) == 5 + + # Multiple interior rings with different length + coords = [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)] + holes = [ + [(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)], + [(3, 3), (3, 4), (4, 5), (5, 4), (5, 3), (3, 3)], + ] + polygon = Polygon(coords, holes) + assert polygon.exterior.coords[:] == coords + assert len(polygon.interiors) == 2 + assert len(polygon.interiors[0].coords) == 5 + assert len(polygon.interiors[1].coords) == 6 + + +def test_polygon_from_linearring(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + ring = LinearRing(coords) + + polygon = Polygon(ring) + assert polygon.exterior.coords[:] == coords + assert len(polygon.interiors) == 0 + + # from shell and holes linearrings + shell = LinearRing([(0.0, 0.0), (70.0, 120.0), (140.0, 0.0), (0.0, 0.0)]) + holes = [ + LinearRing([(60.0, 80.0), (80.0, 80.0), (70.0, 60.0), (60.0, 80.0)]), + LinearRing([(30.0, 10.0), (50.0, 10.0), (40.0, 30.0), (30.0, 10.0)]), + LinearRing([(90.0, 10), (110.0, 10.0), (100.0, 30.0), (90.0, 10.0)]), + ] + polygon = Polygon(shell, holes) + assert polygon.exterior.coords[:] == shell.coords[:] + assert len(polygon.interiors) == 3 + for i in range(3): + assert polygon.interiors[i].coords[:] == holes[i].coords[:] + + +def test_polygon_from_linestring(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + line = LineString(coords) + polygon = Polygon(line) + assert polygon.exterior.coords[:] == coords + + # from unclosed linestring + line = LineString(coords[:-1]) + polygon = Polygon(line) + assert polygon.exterior.coords[:] == coords + + +def test_polygon_from_points(): + polygon = Polygon([Point(0.0, 0.0), Point(0.0, 1.0), Point(1.0, 1.0)]) + expected_coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)] + assert polygon.exterior.coords[:] == expected_coords + + +def test_polygon_from_polygon(): + coords = [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)] + polygon = Polygon(coords, [[(0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25)]]) + + # Test from another Polygon + copy = Polygon(polygon) + assert len(copy.exterior.coords) == 5 + assert len(copy.interiors) == 1 + assert len(copy.interiors[0].coords) == 5 + + +def test_polygon_from_invalid(): + # Error handling + with pytest.raises(ValueError): + # A LinearRing must have at least 3 coordinate tuples + Polygon([[1, 2], [2, 3]]) + + +def test_polygon_from_empty(): + polygon = Polygon() + assert polygon.is_empty + assert polygon.exterior.coords[:] == [] + + polygon = Polygon([]) + assert polygon.is_empty + assert polygon.exterior.coords[:] == [] + + +def test_polygon_from_numpy(): + a = np.array(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0))) + polygon = Polygon(a) + assert len(polygon.exterior.coords) == 5 + assert polygon.exterior.coords[:] == [ + (0.0, 0.0), + (0.0, 1.0), + (1.0, 1.0), + (1.0, 0.0), + (0.0, 0.0), + ] + assert len(polygon.interiors) == 0 + + +def test_polygon_from_generator(): + coords = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)] + gen = (coord for coord in coords) + polygon = Polygon(gen) + assert polygon.exterior.coords[:] == coords + + +class TestPolygon: + def test_linearring(self): + # Initialization + # Linear rings won't usually be created by users, but by polygons + coords = ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)) + ring = LinearRing(coords) + assert len(ring.coords) == 5 + assert ring.coords[0] == ring.coords[4] + assert ring.coords[0] == ring.coords[-1] + assert ring.is_ring is True + + def test_polygon(self): + coords = ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)) + + # Construct a polygon, exterior ring only + polygon = Polygon(coords) + assert len(polygon.exterior.coords) == 5 + + # Ring Access + assert isinstance(polygon.exterior, LinearRing) + ring = polygon.exterior + assert len(ring.coords) == 5 + assert ring.coords[0] == ring.coords[4] + assert ring.coords[0] == (0.0, 0.0) + assert ring.is_ring is True + assert len(polygon.interiors) == 0 + + # Create a new polygon from WKB + data = polygon.wkb + polygon = None + ring = None + polygon = load_wkb(data) + ring = polygon.exterior + assert len(ring.coords) == 5 + assert ring.coords[0] == ring.coords[4] + assert ring.coords[0] == (0.0, 0.0) + assert ring.is_ring is True + polygon = None + + # Interior rings (holes) + polygon = Polygon( + coords, [((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25))] + ) + assert len(polygon.exterior.coords) == 5 + assert len(polygon.interiors[0].coords) == 5 + with pytest.raises(IndexError): # index out of range + polygon.interiors[1] + + # Coordinate getter raises exceptions + with pytest.raises(NotImplementedError): + polygon.coords + + # Geo interface + assert polygon.__geo_interface__ == { + "type": "Polygon", + "coordinates": ( + ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)), + ((0.25, 0.25), (0.25, 0.5), (0.5, 0.5), (0.5, 0.25), (0.25, 0.25)), + ), + } + + def test_linearring_empty(self): + # Test Non-operability of Null rings + r_null = LinearRing() + assert r_null.wkt == "LINEARRING EMPTY" + assert r_null.length == 0.0 + + def test_dimensions(self): + # Background: see http://trac.gispython.org/lab/ticket/168 + # http://lists.gispython.org/pipermail/community/2008-August/001859.html + + coords = ((0.0, 0.0, 0.0), (0.0, 1.0, 0.0), (1.0, 1.0, 0.0), (1.0, 0.0, 0.0)) + polygon = Polygon(coords) + assert polygon._ndim == 3 + gi = polygon.__geo_interface__ + assert gi["coordinates"] == ( + ( + (0.0, 0.0, 0.0), + (0.0, 1.0, 0.0), + (1.0, 1.0, 0.0), + (1.0, 0.0, 0.0), + (0.0, 0.0, 0.0), + ), + ) + + e = polygon.exterior + assert e._ndim == 3 + gi = e.__geo_interface__ + assert gi["coordinates"] == ( + (0.0, 0.0, 0.0), + (0.0, 1.0, 0.0), + (1.0, 1.0, 0.0), + (1.0, 0.0, 0.0), + (0.0, 0.0, 0.0), + ) + + def test_attribute_chains(self): + # Attribute Chaining + # See also ticket #151. + p = Polygon([(0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)]) + assert list(p.boundary.coords) == [ + (0.0, 0.0), + (0.0, 1.0), + (-1.0, 1.0), + (-1.0, 0.0), + (0.0, 0.0), + ] + + ec = list(Point(0.0, 0.0).buffer(1.0, quad_segs=1).exterior.coords) + assert isinstance(ec, list) # TODO: this is a poor test + + # Test chained access to interiors + p = Polygon( + [(0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)], + [[(-0.25, 0.25), (-0.25, 0.75), (-0.75, 0.75), (-0.75, 0.25)]], + ) + assert p.area == 0.75 + + """Not so much testing the exact values here, which are the + responsibility of the geometry engine (GEOS), but that we can get + chain functions and properties using anonymous references. + """ + assert list(p.interiors[0].coords) == [ + (-0.25, 0.25), + (-0.25, 0.75), + (-0.75, 0.75), + (-0.75, 0.25), + (-0.25, 0.25), + ] + xy = next(iter(p.interiors[0].buffer(1).exterior.coords)) + assert len(xy) == 2 + + # Test multiple operators, boundary of a buffer + ec = list(p.buffer(1).boundary.coords) + assert isinstance(ec, list) # TODO: this is a poor test + + def test_empty_equality(self): + # Test equals operator, including empty geometries + # see issue #338 + + point1 = Point(0, 0) + polygon1 = Polygon([(0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)]) + polygon2 = Polygon([(0.0, 0.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)]) + polygon_empty1 = Polygon() + polygon_empty2 = Polygon() + + assert point1 != polygon1 + assert polygon_empty1 == polygon_empty2 + assert polygon1 != polygon_empty1 + assert polygon1 == polygon2 + assert polygon_empty1 is not None + + def test_from_bounds(self): + xmin, ymin, xmax, ymax = -180, -90, 180, 90 + coords = [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)] + assert Polygon(coords) == Polygon.from_bounds(xmin, ymin, xmax, ymax) + + def test_empty_polygon_exterior(self): + p = Polygon() + assert p.exterior == LinearRing() + + +def test_linearring_immutable(): + ring = LinearRing([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)]) + + with pytest.raises(AttributeError): + ring.coords = [(1.0, 1.0), (2.0, 2.0), (1.0, 2.0)] + + with pytest.raises(TypeError): + ring.coords[0] = (1.0, 1.0) + + +class TestLinearRingGetItem: + def test_index_linearring(self): + shell = LinearRing([(0.0, 0.0), (70.0, 120.0), (140.0, 0.0), (0.0, 0.0)]) + holes = [ + LinearRing([(60.0, 80.0), (80.0, 80.0), (70.0, 60.0), (60.0, 80.0)]), + LinearRing([(30.0, 10.0), (50.0, 10.0), (40.0, 30.0), (30.0, 10.0)]), + LinearRing([(90.0, 10), (110.0, 10.0), (100.0, 30.0), (90.0, 10.0)]), + ] + g = Polygon(shell, holes) + for i in range(-3, 3): + assert g.interiors[i].equals(holes[i]) + with pytest.raises(IndexError): + g.interiors[3] + with pytest.raises(IndexError): + g.interiors[-4] + + def test_index_linearring_misc(self): + g = Polygon() # empty + with pytest.raises(IndexError): + g.interiors[0] + with pytest.raises(TypeError): + g.interiors[0.0] + + def test_slice_linearring(self): + shell = LinearRing([(0.0, 0.0), (70.0, 120.0), (140.0, 0.0), (0.0, 0.0)]) + holes = [ + LinearRing([(60.0, 80.0), (80.0, 80.0), (70.0, 60.0), (60.0, 80.0)]), + LinearRing([(30.0, 10.0), (50.0, 10.0), (40.0, 30.0), (30.0, 10.0)]), + LinearRing([(90.0, 10), (110.0, 10.0), (100.0, 30.0), (90.0, 10.0)]), + ] + g = Polygon(shell, holes) + t = [a.equals(b) for (a, b) in zip(g.interiors[1:], holes[1:])] + assert all(t) + t = [a.equals(b) for (a, b) in zip(g.interiors[:-1], holes[:-1])] + assert all(t) + t = [a.equals(b) for (a, b) in zip(g.interiors[::-1], holes[::-1])] + assert all(t) + t = [a.equals(b) for (a, b) in zip(g.interiors[::2], holes[::2])] + assert all(t) + t = [a.equals(b) for (a, b) in zip(g.interiors[:3], holes[:3])] + assert all(t) + assert g.interiors[3:] == holes[3:] == [] diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_constructive.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_constructive.py new file mode 100644 index 0000000000000000000000000000000000000000..6f2c1380f0cd5475a40a562b5e796aa970158f51 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_constructive.py @@ -0,0 +1,1390 @@ +import numpy as np +import pytest + +import shapely +from shapely import ( + Geometry, + GeometryCollection, + GEOSException, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, + geos_version, +) +from shapely.errors import UnsupportedGEOSVersionError +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + ArrayLike, + all_types, + empty, + empty_line_string, + empty_point, + empty_polygon, + ignore_invalid, + line_string, + multi_point, + point, + point_z, +) + +geos39 = geos_version[0:2] == (3, 9) +geos310 = geos_version[0:2] == (3, 10) +geos311 = geos_version[0:2] == (3, 11) + +CONSTRUCTIVE_NO_ARGS = ( + shapely.boundary, + shapely.centroid, + shapely.convex_hull, + pytest.param( + shapely.concave_hull, + marks=pytest.mark.skipif( + shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11" + ), + ), + shapely.envelope, + shapely.extract_unique_points, + shapely.minimum_clearance_line, + shapely.node, + shapely.normalize, + shapely.point_on_surface, + pytest.param( + shapely.constrained_delaunay_triangles, + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10" + ), + ), +) + +CONSTRUCTIVE_FLOAT_ARG = ( + shapely.buffer, + shapely.offset_curve, + shapely.delaunay_triangles, + shapely.simplify, + shapely.voronoi_polygons, +) + + +@pytest.mark.parametrize("geometry", all_types) +@pytest.mark.parametrize("func", CONSTRUCTIVE_NO_ARGS) +def test_no_args_array(geometry, func): + if ( + geometry.is_empty + and shapely.get_num_geometries(geometry) > 0 + and func is shapely.node + and ( + (geos39 and geos_version < (3, 9, 3)) + or (geos310 and geos_version < (3, 10, 3)) + ) + ): # GEOS GH-601 + pytest.xfail("GEOS < 3.9.3 or GEOS < 3.10.3 crashes with empty geometries") + actual = func([geometry, geometry]) + assert actual.shape == (2,) + assert actual[0] is None or isinstance(actual[0], Geometry) + + +@pytest.mark.parametrize("geometry", all_types) +@pytest.mark.parametrize("func", CONSTRUCTIVE_FLOAT_ARG) +def test_float_arg_array(geometry, func): + if ( + func is shapely.offset_curve + and shapely.get_type_id(geometry) not in [1, 2] + and shapely.geos_version < (3, 11, 0) + ): + with pytest.raises(GEOSException, match="only accept linestrings"): + func([geometry, geometry], 0.0) + return + # voronoi_polygons emits an "invalid" warning when supplied with an empty + # point (see https://github.com/libgeos/geos/issues/515) + with ignore_invalid( + func is shapely.voronoi_polygons + and shapely.get_type_id(geometry) == 0 + and shapely.geos_version < (3, 12, 0) + ): + actual = func([geometry, geometry], 0.0) + assert actual.shape == (2,) + assert isinstance(actual[0], Geometry) + + +@pytest.mark.parametrize("geometry", all_types) +@pytest.mark.parametrize("reference", all_types) +def test_snap_array(geometry, reference): + actual = shapely.snap([geometry, geometry], [reference, reference], tolerance=1.0) + assert actual.shape == (2,) + assert isinstance(actual[0], Geometry) + + +@pytest.mark.parametrize("func", CONSTRUCTIVE_NO_ARGS) +def test_no_args_missing(func): + actual = func(None) + assert actual is None + + +@pytest.mark.parametrize("func", CONSTRUCTIVE_FLOAT_ARG) +def test_float_arg_missing(func): + actual = func(None, 1.0) + assert actual is None + + +@pytest.mark.parametrize("geometry", all_types) +@pytest.mark.parametrize("func", CONSTRUCTIVE_FLOAT_ARG) +def test_float_arg_nan(geometry, func): + actual = func(geometry, float("nan")) + assert actual is None + + +def test_buffer_cap_style_invalid(): + with pytest.raises(ValueError, match="'invalid' is not a valid option"): + shapely.buffer(point, 1, cap_style="invalid") + + +def test_buffer_join_style_invalid(): + with pytest.raises(ValueError, match="'invalid' is not a valid option"): + shapely.buffer(point, 1, join_style="invalid") + + +def test_snap_none(): + actual = shapely.snap(None, point, tolerance=1.0) + assert actual is None + + +@pytest.mark.parametrize("geometry", all_types) +def test_snap_nan_float(geometry): + actual = shapely.snap(geometry, point, tolerance=np.nan) + assert actual is None + + +def test_build_area_none(): + actual = shapely.build_area(None) + assert actual is None + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, empty), # a point has no area + (line_string, empty), # a line string has no area + # geometry collection of two polygons are combined into one + ( + GeometryCollection( + [ + Polygon([(0, 0), (0, 3), (3, 3), (3, 0), (0, 0)]), + Polygon([(1, 1), (2, 2), (1, 2), (1, 1)]), + ] + ), + Polygon( + [(0, 0), (0, 3), (3, 3), (3, 0), (0, 0)], + holes=[[(1, 1), (2, 2), (1, 2), (1, 1)]], + ), + ), + (empty, empty), + ([empty], [empty]), + ], +) +def test_build_area(geom, expected): + actual = shapely.build_area(geom) + assert actual is not expected + assert actual == expected + + +def test_make_valid_none(): + actual = shapely.make_valid(None) + assert actual is None + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point), # a valid geometry stays the same (but is copied) + # an L shaped polygon without area is converted to a multilinestring + ( + Polygon([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)]), + MultiLineString([((1, 1), (1, 2)), ((0, 0), (1, 1))]), + ), + # a polygon with self-intersection (bowtie) is converted into polygons + ( + Polygon([(0, 0), (2, 2), (2, 0), (0, 2), (0, 0)]), + MultiPolygon( + [ + Polygon([(1, 1), (2, 2), (2, 0), (1, 1)]), + Polygon([(0, 0), (0, 2), (1, 1), (0, 0)]), + ] + ), + ), + (empty, empty), + ([empty], [empty]), + ], +) +def test_make_valid(geom, expected): + actual = shapely.make_valid(geom) + assert actual is not expected + # normalize needed to handle variation in output across GEOS versions + assert shapely.normalize(actual) == expected + + +@pytest.mark.parametrize( + "geom,expected", + [ + (all_types, all_types), + # first polygon is valid, second polygon has self-intersection + ( + [ + Polygon([(0, 0), (2, 2), (0, 2), (0, 0)]), + Polygon([(0, 0), (2, 2), (2, 0), (0, 2), (0, 0)]), + ], + [ + Polygon([(0, 0), (2, 2), (0, 2), (0, 0)]), + MultiPolygon( + [ + Polygon([(1, 1), (0, 0), (0, 2), (1, 1)]), + Polygon([(1, 1), (2, 2), (2, 0), (1, 1)]), + ] + ), + ], + ), + ([point, None, empty], [point, None, empty]), + ], +) +def test_make_valid_1d(geom, expected): + actual = shapely.make_valid(geom) + # normalize needed to handle variation in output across GEOS versions + assert np.all(shapely.normalize(actual) == shapely.normalize(expected)) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point), # a valid geometry stays the same (but is copied) + # an L shaped polygon without area is converted to a linestring + ( + Polygon([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)]), + LineString([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)]), + ), + # a polygon with self-intersection (bowtie) is converted into polygons + ( + Polygon([(0, 0), (2, 2), (2, 0), (0, 2), (0, 0)]), + MultiPolygon( + [ + Polygon([(1, 1), (2, 2), (2, 0), (1, 1)]), + Polygon([(0, 0), (0, 2), (1, 1), (0, 0)]), + ] + ), + ), + (empty, empty), + ([empty], [empty]), + ], +) +def test_make_valid_structure(geom, expected): + actual = shapely.make_valid(geom, method="structure") + assert actual is not expected + # normalize needed to handle variation in output across GEOS versions + assert shapely.normalize(actual) == expected + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point), # a valid geometry stays the same (but is copied) + # an L shaped polygon without area is converted to Empty Polygon + ( + Polygon([(0, 0), (1, 1), (1, 2), (1, 1), (0, 0)]), + Polygon(), + ), + # a polygon with self-intersection (bowtie) is converted into polygons + ( + Polygon([(0, 0), (2, 2), (2, 0), (0, 2), (0, 0)]), + MultiPolygon( + [ + Polygon([(1, 1), (2, 2), (2, 0), (1, 1)]), + Polygon([(0, 0), (0, 2), (1, 1), (0, 0)]), + ] + ), + ), + (empty, empty), + ([empty], [empty]), + ], +) +def test_make_valid_structure_keep_collapsed_false(geom, expected): + actual = shapely.make_valid(geom, method="structure", keep_collapsed=False) + assert actual is not expected + # normalize needed to handle variation in output across GEOS versions + assert shapely.normalize(actual) == expected + + +@pytest.mark.skipif(shapely.geos_version >= (3, 10, 0), reason="GEOS >= 3.10") +def test_make_valid_structure_unsupported_geos(): + with pytest.raises( + ValueError, match="The 'structure' method is only available in GEOS >= 3.10.0" + ): + _ = shapely.make_valid(Point(), method="structure") + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "method, keep_collapsed, error_type, error", + [ + ( + np.array(["linework", "structure"]), + True, + TypeError, + "method only accepts scalar values", + ), + ( + "linework", + [True, False], + TypeError, + "keep_collapsed only accepts scalar values", + ), + ("unknown", True, ValueError, "Unknown method: unknown"), + ( + "linework", + False, + ValueError, + "The 'linework' method does not support 'keep_collapsed=False'", + ), + ], +) +def test_make_valid_invalid_params(method, keep_collapsed, error_type, error): + with pytest.raises(error_type, match=error): + _ = shapely.make_valid(Point(), method=method, keep_collapsed=keep_collapsed) + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point), # a point is always in normalized form + # order coordinates of linestrings and parts of multi-linestring + ( + MultiLineString([((1, 1), (0, 0)), ((1, 1), (1, 2))]), + MultiLineString([((1, 1), (1, 2)), ((0, 0), (1, 1))]), + ), + ], +) +def test_normalize(geom, expected): + actual = shapely.normalize(geom) + assert actual == expected + + +def test_offset_curve_empty(): + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # Empty geometries emit an "invalid" warning + # (see https://github.com/libgeos/geos/issues/515) + actual = shapely.offset_curve(empty_line_string, 2.0) + assert shapely.is_empty(actual) + + +def test_offset_curve_distance_array(): + # check that kwargs are passed through + result = shapely.offset_curve([line_string, line_string], [-2.0, -3.0]) + assert result[0] == shapely.offset_curve(line_string, -2.0) + assert result[1] == shapely.offset_curve(line_string, -3.0) + + +def test_offset_curve_kwargs(): + # check that kwargs are passed through + result1 = shapely.offset_curve( + line_string, -2.0, quad_segs=2, join_style="mitre", mitre_limit=2.0 + ) + result2 = shapely.offset_curve(line_string, -2.0) + assert result1 != result2 + + +def test_offset_curve_non_scalar_kwargs(): + msg = "only accepts scalar values" + with pytest.raises(TypeError, match=msg): + shapely.offset_curve([line_string, line_string], 1, quad_segs=np.array([8, 9])) + + with pytest.raises(TypeError, match=msg): + shapely.offset_curve( + [line_string, line_string], 1, join_style=["round", "bevel"] + ) + + with pytest.raises(TypeError, match=msg): + shapely.offset_curve([line_string, line_string], 1, mitre_limit=[5.0, 6.0]) + + +def test_offset_curve_join_style_invalid(): + with pytest.raises(ValueError, match="'invalid' is not a valid option"): + shapely.offset_curve(line_string, 1.0, join_style="invalid") + + +@pytest.mark.skipif(shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11") +@pytest.mark.parametrize( + "geom,expected", + [ + (LineString([(0, 0), (0, 0), (1, 0)]), LineString([(0, 0), (1, 0)])), + ( + LinearRing([(0, 0), (1, 2), (1, 2), (1, 3), (0, 0)]), + LinearRing([(0, 0), (1, 2), (1, 3), (0, 0)]), + ), + ( + Polygon([(0, 0), (0, 0), (1, 0), (1, 1), (1, 0), (0, 0)]), + Polygon([(0, 0), (1, 0), (1, 1), (1, 0), (0, 0)]), + ), + ( + Polygon( + [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)], + holes=[[(2, 2), (2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ), + Polygon( + [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ), + ), + ( + MultiPolygon( + [ + Polygon([(0, 0), (0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), + Polygon([(2, 2), (2, 2), (2, 3), (3, 3), (3, 2), (2, 2)]), + ] + ), + MultiPolygon( + [ + Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), + Polygon([(2, 2), (2, 3), (3, 3), (3, 2), (2, 2)]), + ] + ), + ), + # points are unchanged + (point, point), + (point_z, point_z), + (multi_point, multi_point), + # empty geometries are unchanged + (empty_point, empty_point), + (empty_line_string, empty_line_string), + (empty, empty), + (empty_polygon, empty_polygon), + ], +) +def test_remove_repeated_points(geom, expected): + assert_geometries_equal(shapely.remove_repeated_points(geom, 0), expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +@pytest.mark.parametrize( + "geom, tolerance", [[Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), 2]] +) +def test_remove_repeated_points_invalid_result(geom, tolerance): + # Requiring GEOS 3.12 instead of 3.11 + # (GEOS 3.11 had a bug causing this to intermittently not fail) + with pytest.raises(shapely.GEOSException, match="Invalid number of points"): + shapely.remove_repeated_points(geom, tolerance) + + +@pytest.mark.skipif(shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11") +def test_remove_repeated_points_none(): + assert shapely.remove_repeated_points(None, 1) is None + assert shapely.remove_repeated_points([None], 1).tolist() == [None] + + geometry = LineString([(0, 0), (0, 0), (1, 1)]) + expected = LineString([(0, 0), (1, 1)]) + result = shapely.remove_repeated_points([None, geometry], 1) + assert result[0] is None + assert_geometries_equal(result[1], expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11") +@pytest.mark.parametrize("geom, tolerance", [("Not a geometry", 1), (1, 1)]) +def test_remove_repeated_points_invalid_type(geom, tolerance): + with pytest.raises(TypeError, match="One of the arguments is of incorrect type"): + shapely.remove_repeated_points(geom, tolerance) + + +@pytest.mark.parametrize( + "geom,expected", + [ + (LineString([(0, 0), (1, 2)]), LineString([(1, 2), (0, 0)])), + ( + LinearRing([(0, 0), (1, 2), (1, 3), (0, 0)]), + LinearRing([(0, 0), (1, 3), (1, 2), (0, 0)]), + ), + ( + Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), + Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), + ), + ( + Polygon( + [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ), + Polygon( + [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + holes=[[(2, 2), (4, 2), (4, 4), (2, 4), (2, 2)]], + ), + ), + ( + MultiLineString([[(0, 0), (1, 2)], [(3, 3), (4, 4)]]), + MultiLineString([[(1, 2), (0, 0)], [(4, 4), (3, 3)]]), + ), + ( + MultiPolygon( + [ + Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), + Polygon([(2, 2), (2, 3), (3, 3), (3, 2), (2, 2)]), + ] + ), + MultiPolygon( + [ + Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), + Polygon([(2, 2), (3, 2), (3, 3), (2, 3), (2, 2)]), + ] + ), + ), + # points are unchanged + (point, point), + (point_z, point_z), + (multi_point, multi_point), + # empty geometries are unchanged + (empty_point, empty_point), + (empty_line_string, empty_line_string), + (empty, empty), + (empty_polygon, empty_polygon), + ], +) +def test_reverse(geom, expected): + assert_geometries_equal(shapely.reverse(geom), expected) + + +def test_reverse_none(): + assert shapely.reverse(None) is None + assert shapely.reverse([None]).tolist() == [None] + + geometry = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + expected = Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]) + result = shapely.reverse([None, geometry]) + assert result[0] is None + assert_geometries_equal(result[1], expected) + + +@pytest.mark.parametrize("geom", ["Not a geometry", 1]) +def test_reverse_invalid_type(geom): + with pytest.raises(TypeError, match="One of the arguments is of incorrect type"): + shapely.reverse(geom) + + +@pytest.mark.parametrize( + "geom,expected", + [ + # Point outside + (Point(0, 0), GeometryCollection()), + # Point inside + (Point(15, 15), Point(15, 15)), + # Point on boundary + (Point(15, 10), GeometryCollection()), + # Line outside + (LineString([(0, 0), (-5, 5)]), GeometryCollection()), + # Line inside + (LineString([(15, 15), (16, 15)]), LineString([(15, 15), (16, 15)])), + # Line on boundary + (LineString([(10, 15), (10, 10), (15, 10)]), GeometryCollection()), + # Line splitting rectangle + (LineString([(10, 5), (25, 20)]), LineString([(15, 10), (20, 15)])), + ], +) +def test_clip_by_rect(geom, expected): + actual = shapely.clip_by_rect(geom, 10, 10, 20, 20) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "geom, rect, expected", + [ + # Polygon hole (CCW) fully on rectangle boundary""" + ( + Polygon( + ((0, 0), (0, 30), (30, 30), (30, 0), (0, 0)), + holes=[((10, 10), (20, 10), (20, 20), (10, 20), (10, 10))], + ), + (10, 10, 20, 20), + GeometryCollection(), + ), + # Polygon hole (CW) fully on rectangle boundary""" + ( + Polygon( + ((0, 0), (0, 30), (30, 30), (30, 0), (0, 0)), + holes=[((10, 10), (10, 20), (20, 20), (20, 10), (10, 10))], + ), + (10, 10, 20, 20), + GeometryCollection(), + ), + # Polygon fully within rectangle""" + ( + Polygon( + ((1, 1), (1, 30), (30, 30), (30, 1), (1, 1)), + holes=[((10, 10), (20, 10), (20, 20), (10, 20), (10, 10))], + ), + (0, 0, 40, 40), + Polygon( + ((1, 1), (1, 30), (30, 30), (30, 1), (1, 1)), + holes=[((10, 10), (20, 10), (20, 20), (10, 20), (10, 10))], + ), + ), + # Polygon overlapping rectanglez + ( + Polygon( + [(0, 0), (0, 30), (30, 30), (30, 0), (0, 0)], + holes=[[(10, 10), (20, 10), (20, 20), (10, 20), (10, 10)]], + ), + (5, 5, 15, 15), + Polygon([(5, 5), (5, 15), (10, 15), (10, 10), (15, 10), (15, 5), (5, 5)]), + ), + ], +) +def test_clip_by_rect_polygon(geom, rect, expected): + actual = shapely.clip_by_rect(geom, *rect) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("geometry", all_types) +def test_clip_by_rect_array(geometry): + if ( + geometry.is_empty + and shapely.get_type_id(geometry) == shapely.GeometryType.POINT + and ( + (geos39 and geos_version < (3, 9, 5)) + or (geos310 and geos_version < (3, 10, 6)) + or (geos311 and geos_version < (3, 11, 3)) + ) + ): + # GEOS GH-913 + with pytest.raises(GEOSException): + shapely.clip_by_rect([geometry, geometry], 0.0, 0.0, 1.0, 1.0) + return + actual = shapely.clip_by_rect([geometry, geometry], 0.0, 0.0, 1.0, 1.0) + assert actual.shape == (2,) + assert actual[0] is None or isinstance(actual[0], Geometry) + + +def test_clip_by_rect_missing(): + actual = shapely.clip_by_rect(None, 0, 0, 1, 1) + assert actual is None + + +@pytest.mark.parametrize("geom", [empty, empty_line_string, empty_polygon]) +def test_clip_by_rect_empty(geom): + # TODO empty point + actual = shapely.clip_by_rect(geom, 0, 0, 1, 1) + assert actual == GeometryCollection() + + +def test_clip_by_rect_non_scalar_kwargs(): + msg = "only accepts scalar values" + with pytest.raises(TypeError, match=msg): + shapely.clip_by_rect([line_string, line_string], 0, 0, 1, np.array([0, 1])) + + +def test_polygonize(): + lines = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + LineString([(1, 1), (1, 0)]), + LineString([(1, 0), (0, 0)]), + LineString([(5, 5), (6, 6)]), + Point(0, 0), + None, + ] + result = shapely.polygonize(lines) + assert shapely.get_type_id(result) == 7 # GeometryCollection + expected = GeometryCollection( + [ + Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]), + Polygon([(1, 1), (0, 0), (0, 1), (1, 1)]), + ] + ) + assert result == expected + + +def test_polygonize_array(): + lines = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + ] + expected = GeometryCollection([Polygon([(1, 1), (0, 0), (0, 1), (1, 1)])]) + result = shapely.polygonize(np.array(lines)) + assert isinstance(result, shapely.Geometry) + assert result == expected + + result = shapely.polygonize(np.array([lines])) + assert isinstance(result, np.ndarray) + assert result.shape == (1,) + assert result[0] == expected + + arr = np.array([lines, lines]) + assert arr.shape == (2, 3) + result = shapely.polygonize(arr) + assert isinstance(result, np.ndarray) + assert result.shape == (2,) + assert result[0] == expected + assert result[1] == expected + + arr = np.array([[lines, lines], [lines, lines], [lines, lines]]) + assert arr.shape == (3, 2, 3) + result = shapely.polygonize(arr) + assert isinstance(result, np.ndarray) + assert result.shape == (3, 2) + for res in result.flatten(): + assert res == expected + + +def test_polygonize_array_axis(): + lines = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + ] + arr = np.array([lines, lines]) # shape (2, 3) + result = shapely.polygonize(arr, axis=1) + assert result.shape == (2,) + result = shapely.polygonize(arr, axis=0) + assert result.shape == (3,) + + +def test_polygonize_missing(): + # set of geometries that is all missing + result = shapely.polygonize([None, None]) + assert result == GeometryCollection() + + +def test_polygonize_full(): + lines = [ + None, + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + LineString([(1, 1), (1, 0)]), + None, + LineString([(1, 0), (0, 0)]), + LineString([(5, 5), (6, 6)]), + LineString([(1, 1), (100, 100)]), + Point(0, 0), + None, + ] + result = shapely.polygonize_full(lines) + assert len(result) == 4 + assert all(shapely.get_type_id(geom) == 7 for geom in result) # GeometryCollection + polygons, cuts, dangles, invalid = result + expected_polygons = GeometryCollection( + [ + Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]), + Polygon([(1, 1), (0, 0), (0, 1), (1, 1)]), + ] + ) + assert polygons == expected_polygons + assert cuts == GeometryCollection() + expected_dangles = GeometryCollection( + [LineString([(1, 1), (100, 100)]), LineString([(5, 5), (6, 6)])] + ) + assert dangles == expected_dangles + assert invalid == GeometryCollection() + + +def test_polygonize_full_array(): + lines = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + ] + expected = GeometryCollection([Polygon([(1, 1), (0, 0), (0, 1), (1, 1)])]) + result = shapely.polygonize_full(np.array(lines)) + assert len(result) == 4 + assert all(isinstance(geom, shapely.Geometry) for geom in result) + assert result[0] == expected + assert all(geom == GeometryCollection() for geom in result[1:]) + + result = shapely.polygonize_full(np.array([lines])) + assert len(result) == 4 + assert all(isinstance(geom, np.ndarray) for geom in result) + assert all(geom.shape == (1,) for geom in result) + assert result[0][0] == expected + assert all(geom[0] == GeometryCollection() for geom in result[1:]) + + arr = np.array([lines, lines]) + assert arr.shape == (2, 3) + result = shapely.polygonize_full(arr) + assert len(result) == 4 + assert all(isinstance(arr, np.ndarray) for arr in result) + assert all(arr.shape == (2,) for arr in result) + assert result[0][0] == expected + assert result[0][1] == expected + assert all(g == GeometryCollection() for geom in result[1:] for g in geom) + + arr = np.array([[lines, lines], [lines, lines], [lines, lines]]) + assert arr.shape == (3, 2, 3) + result = shapely.polygonize_full(arr) + assert len(result) == 4 + assert all(isinstance(arr, np.ndarray) for arr in result) + assert all(arr.shape == (3, 2) for arr in result) + for res in result[0].flatten(): + assert res == expected + for arr in result[1:]: + for res in arr.flatten(): + assert res == GeometryCollection() + + +def test_polygonize_full_array_axis(): + lines = [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (0, 1)]), + LineString([(0, 1), (1, 1)]), + ] + arr = np.array([lines, lines]) # shape (2, 3) + result = shapely.polygonize_full(arr, axis=1) + assert len(result) == 4 + assert all(arr.shape == (2,) for arr in result) + result = shapely.polygonize_full(arr, axis=0) + assert len(result) == 4 + assert all(arr.shape == (3,) for arr in result) + + +def test_polygonize_full_missing(): + # set of geometries that is all missing + result = shapely.polygonize_full([None, None]) + assert len(result) == 4 + assert all(geom == GeometryCollection() for geom in result) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize("geometry", all_types) +@pytest.mark.parametrize("max_segment_length", [-1, 0]) +def test_segmentize_invalid_max_segment_length(geometry, max_segment_length): + with pytest.raises(GEOSException, match="IllegalArgumentException"): + shapely.segmentize(geometry, max_segment_length=max_segment_length) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize("geometry", all_types) +def test_segmentize_max_segment_length_nan(geometry): + actual = shapely.segmentize(geometry, max_segment_length=np.nan) + assert actual is None + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry", [empty, empty_point, empty_line_string, empty_polygon] +) +def test_segmentize_empty(geometry): + actual = shapely.segmentize(geometry, max_segment_length=5) + assert_geometries_equal(actual, geometry) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize("geometry", [point, point_z, multi_point]) +def test_segmentize_no_change(geometry): + actual = shapely.segmentize(geometry, max_segment_length=5) + assert_geometries_equal(actual, geometry) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +def test_segmentize_none(): + assert shapely.segmentize(None, max_segment_length=5) is None + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry,tolerance, expected", + [ + # tolerance greater than max edge length, no change + ( + LineString([(0, 0), (0, 10)]), + 20, + LineString([(0, 0), (0, 10)]), + ), + ( + Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]), + 20, + Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]), + ), + # tolerance causes one vertex per segment + ( + LineString([(0, 0), (0, 10)]), + 5, + LineString([(0, 0), (0, 5), (0, 10)]), + ), + ( + Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]), + 5, + Polygon( + [ + (0, 0), + (5, 0), + (10, 0), + (10, 5), + (10, 10), + (5, 10), + (0, 10), + (0, 5), + (0, 0), + ] + ), + ), + # ensure input arrays are broadcast correctly + ( + [ + LineString([(0, 0), (0, 10)]), + LineString([(0, 0), (0, 2)]), + ], + 5, + [ + LineString([(0, 0), (0, 5), (0, 10)]), + LineString([(0, 0), (0, 2)]), + ], + ), + ( + [ + LineString([(0, 0), (0, 10)]), + LineString([(0, 0), (0, 2)]), + ], + [5], + [ + LineString([(0, 0), (0, 5), (0, 10)]), + LineString([(0, 0), (0, 2)]), + ], + ), + ( + [ + LineString([(0, 0), (0, 10)]), + LineString([(0, 0), (0, 2)]), + ], + [5, 1.5], + [ + LineString([(0, 0), (0, 5), (0, 10)]), + LineString([(0, 0), (0, 1), (0, 2)]), + ], + ), + ], +) +def test_segmentize(geometry, tolerance, expected): + actual = shapely.segmentize(geometry, tolerance) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("geometry", all_types) +def test_minimum_bounding_circle_all_types(geometry): + actual = shapely.minimum_bounding_circle([geometry, geometry]) + assert actual.shape == (2,) + assert actual[0] is None or isinstance(actual[0], Geometry) + + actual = shapely.minimum_bounding_circle(None) + assert actual is None + + +@pytest.mark.parametrize( + "geometry, expected", + [ + ( + Polygon([(0, 5), (5, 10), (10, 5), (5, 0), (0, 5)]), + shapely.buffer(Point(5, 5), 5), + ), + ( + LineString([(1, 0), (1, 10)]), + shapely.buffer(Point(1, 5), 5), + ), + ( + MultiPoint([(2, 2), (4, 2)]), + shapely.buffer(Point(3, 2), 1), + ), + ( + Point(2, 2), + Point(2, 2), + ), + ( + GeometryCollection(), + Polygon(), + ), + ], +) +def test_minimum_bounding_circle(geometry, expected): + actual = shapely.minimum_bounding_circle(geometry) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("geometry", all_types) +def test_oriented_envelope_all_types(geometry): + actual = shapely.oriented_envelope([geometry, geometry]) + assert actual.shape == (2,) + assert actual[0] is None or isinstance(actual[0], Geometry) + + actual = shapely.oriented_envelope(None) + assert actual is None + + +@pytest.mark.parametrize( + "func", [shapely.oriented_envelope, shapely.minimum_rotated_rectangle] +) +@pytest.mark.parametrize( + "geometry, expected", + [ + ( + MultiPoint([(1.0, 1.0), (1.0, 5.0), (3.0, 6.0), (4.0, 2.0), (5.0, 5.0)]), + Polygon([(1.0, 1.0), (1.0, 6.0), (5.0, 6.0), (5.0, 1.0), (1.0, 1.0)]), + ), + ( + LineString([(1, 1), (5, 1), (10, 10)]), + Polygon([(1, 1), (3, -1), (12, 8), (10, 10), (1, 1)]), + ), + ( + Polygon([(1, 1), (15, 1), (5, 9), (1, 1)]), + Polygon([(1.0, 1.0), (5.0, 9.0), (16.2, 3.4), (12.2, -4.6), (1.0, 1.0)]), + ), + ( + LineString([(1, 1), (10, 1)]), + LineString([(1, 1), (10, 1)]), + ), + ( + Point(2, 2), + Point(2, 2), + ), + ( + GeometryCollection(), + Polygon(), + ), + ], +) +def test_oriented_envelope(geometry, expected, func): + actual = func(geometry) + assert_geometries_equal(actual, expected, normalize=True, tolerance=1e-3) + + +@pytest.mark.skipif(shapely.geos_version >= (3, 12, 0), reason="GEOS >= 3.12") +@pytest.mark.parametrize( + "geometry, expected", + [ + ( + MultiPoint([(1.0, 1.0), (1.0, 5.0), (3.0, 6.0), (4.0, 2.0), (5.0, 5.0)]), + Polygon([(-0.2, 1.4), (1.5, 6.5), (5.1, 5.3), (3.4, 0.2), (-0.2, 1.4)]), + ), + ( + LineString([(1, 1), (5, 1), (10, 10)]), + Polygon([(1, 1), (3, -1), (12, 8), (10, 10), (1, 1)]), + ), + ( + Polygon([(1, 1), (15, 1), (5, 9), (1, 1)]), + Polygon([(1.0, 1.0), (1.0, 9.0), (15.0, 9.0), (15.0, 1.0), (1.0, 1.0)]), + ), + ( + LineString([(1, 1), (10, 1)]), + LineString([(1, 1), (10, 1)]), + ), + ( + Point(2, 2), + Point(2, 2), + ), + ( + GeometryCollection(), + Polygon(), + ), + ], +) +def test_oriented_envelope_pre_geos_312(geometry, expected): + # use private method (similar as direct shapely.lib.oriented_envelope) + # to cover the C code for older GEOS versions + actual = shapely.constructive._oriented_envelope_geos(geometry) + assert_geometries_equal(actual, expected, normalize=True, tolerance=1e-3) + + +def test_oriented_evelope_array_like(): + # https://github.com/shapely/shapely/issues/1929 + # because we have a custom python implementation, need to ensure this has + # the same capabilities as numpy ufuncs to work with array-likes + geometries = [Point(1, 1).buffer(1), Point(2, 2).buffer(1)] + actual = shapely.oriented_envelope(ArrayLike(geometries)) + assert isinstance(actual, ArrayLike) + expected = shapely.oriented_envelope(geometries) + assert_geometries_equal(np.asarray(actual), expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11") +def test_concave_hull_kwargs(): + p = Point(10, 10) + mp = MultiPoint(p.buffer(5).exterior.coords[:] + p.buffer(4).exterior.coords[:]) + + result1 = shapely.concave_hull(mp, ratio=0.5) + assert len(result1.interiors) == 0 + result2 = shapely.concave_hull(mp, ratio=0.5, allow_holes=True) + assert len(result2.interiors) == 1 + + result3 = shapely.concave_hull(mp, ratio=0) + result4 = shapely.concave_hull(mp, ratio=1) + assert shapely.get_num_coordinates(result4) < shapely.get_num_coordinates(result3) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +class TestConstrainedDelaunayTriangulation: + """ + Only testing the number of triangles and their type here. + This doesn't actually test the points in the resulting geometries. + + """ + + def test_poly(self): + polys = shapely.constrained_delaunay_triangles( + Polygon([(10, 10), (20, 40), (90, 90), (90, 10), (10, 10)]) + ) + assert len(polys.geoms) == 2 + for p in polys.geoms: + assert isinstance(p, Polygon) + + def test_multi_polygon(self): + multipoly = MultiPolygon( + [ + Polygon(((50, 30), (60, 30), (100, 100), (50, 30))), + Polygon(((10, 10), (20, 40), (90, 90), (90, 10), (10, 10))), + ] + ) + polys = shapely.constrained_delaunay_triangles(multipoly) + assert len(polys.geoms) == 3 + for p in polys.geoms: + assert isinstance(p, Polygon) + + def test_point(self): + p = Point(1, 1) + polys = shapely.constrained_delaunay_triangles(p) + assert len(polys.geoms) == 0 + + def test_empty_poly(self): + polys = shapely.constrained_delaunay_triangles(Polygon()) + assert len(polys.geoms) == 0 + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +def test_voronoi_polygons_ordered(): + mp = MultiPoint([(3.0, 1.0), (3.0, 2.0), (1.0, 2.0), (1.0, 1.0)]) + result = shapely.voronoi_polygons(mp, ordered=False) + assert result.geoms[0].equals( + Polygon([(-1, -1), (-1, 1.5), (2, 1.5), (2, -1), (-1, -1)]) + ) + + result_ordered = shapely.voronoi_polygons(mp, ordered=True) + assert result_ordered.geoms[0].equals( + Polygon([(5, -1), (2, -1), (2, 1.5), (5, 1.5), (5, -1)]) + ) + + +@pytest.mark.skipif(shapely.geos_version >= (3, 12, 0), reason="GEOS >= 3.12") +def test_voronoi_polygons_ordered_raise(): + mp = MultiPoint([(3.0, 1.0), (3.0, 2.0), (1.0, 2.0), (1.0, 1.0)]) + with pytest.raises( + UnsupportedGEOSVersionError, match="Ordered Voronoi polygons require GEOS" + ): + shapely.voronoi_polygons(mp, ordered=True) + + +@pytest.mark.parametrize("geometry", all_types) +def test_maximum_inscribed_circle_all_types(geometry): + if shapely.get_type_id(geometry) not in [3, 6]: + # Maximum Inscribed Circle is only supported for (Multi)Polygon input + with pytest.raises( + GEOSException, + match=( + "Argument must be Polygonal or LinearRing|" # GEOS < 3.10.4 + "must be a Polygon or MultiPolygon|" + "Operation not supported by GeometryCollection" + ), + ): + shapely.maximum_inscribed_circle(geometry) + return + + if geometry.is_empty: + with pytest.raises( + GEOSException, match="Empty input(?: geometry)? is not supported" + ): + shapely.maximum_inscribed_circle(geometry) + return + + actual = shapely.maximum_inscribed_circle([geometry, geometry]) + assert actual.shape == (2,) + assert actual[0] is None or isinstance(actual[0], Geometry) + + actual = shapely.maximum_inscribed_circle(None) + assert actual is None + + +@pytest.mark.parametrize( + "geometry, expected", + [ + ( + "POLYGON ((0 5, 5 10, 10 5, 5 0, 0 5))", + "LINESTRING (5 5, 2.5 7.5)", + ), + ], +) +def test_maximum_inscribed_circle(geometry, expected): + geometry, expected = shapely.from_wkt(geometry), shapely.from_wkt(expected) + actual = shapely.maximum_inscribed_circle(geometry) + assert_geometries_equal(actual, expected) + + +def test_maximum_inscribed_circle_empty(): + geometry = shapely.from_wkt("POINT EMPTY") + with pytest.raises( + GEOSException, + match=( + "Argument must be Polygonal or LinearRing|" # GEOS < 3.10.4 + "must be a Polygon or MultiPolygon" + ), + ): + shapely.maximum_inscribed_circle(geometry) + + geometry = shapely.from_wkt("POLYGON EMPTY") + with pytest.raises( + GEOSException, match="Empty input(?: geometry)? is not supported" + ): + shapely.maximum_inscribed_circle(geometry) + + +def test_maximum_inscribed_circle_invalid_tolerance(): + geometry = shapely.from_wkt("POLYGON ((0 5, 5 10, 10 5, 5 0, 0 5))") + with pytest.raises(ValueError, match="'tolerance' should be positive"): + shapely.maximum_inscribed_circle(geometry, tolerance=-1) + + +@pytest.mark.parametrize("geometry", all_types) +def test_orient_polygons_all_types(geometry): + actual = shapely.orient_polygons([geometry, geometry]) + assert actual.shape == (2,) + assert isinstance(actual[0], Geometry) + + actual = shapely.orient_polygons(None) + assert actual is None + + +def test_orient_polygons(): + # polygon with both shell and hole having clockwise orientation + polygon = Polygon( + [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ) + + result = shapely.orient_polygons(polygon) + assert result.exterior.is_ccw + assert not result.interiors[0].is_ccw + + result = shapely.orient_polygons(polygon, exterior_cw=True) + assert not result.exterior.is_ccw + assert result.interiors[0].is_ccw + + # in a MultiPolygon + mp = MultiPolygon([polygon, polygon]) + result = shapely.orient_polygons(mp) + assert len(result.geoms) == 2 + for geom in result.geoms: + assert geom.exterior.is_ccw + assert not geom.interiors[0].is_ccw + + result = shapely.orient_polygons([mp], exterior_cw=True)[0] + assert len(result.geoms) == 2 + for geom in result.geoms: + assert not geom.exterior.is_ccw + assert geom.interiors[0].is_ccw + + # in a GeometryCollection + gc = GeometryCollection([Point(1, 1), polygon, mp]) + result = shapely.orient_polygons(gc) + assert len(result.geoms) == 3 + assert result.geoms[0] == Point(1, 1) + assert result.geoms[1] == shapely.orient_polygons(polygon) + assert result.geoms[2] == shapely.orient_polygons(mp) + + +def test_orient_polygons_non_polygonal_input(): + arr = np.array([Point(0, 0), LineString([(0, 0), (1, 1)]), None]) + result = shapely.orient_polygons(arr) + assert_geometries_equal(result, arr) + + +def test_orient_polygons_array(): + # because we have a custom python implementation for older GEOS, need to + # ensure this has the same capabilities as numpy ufuncs to work with array-likes + polygon = Polygon( + [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ) + geometries = np.array([[polygon] * 3] * 2) + actual = shapely.orient_polygons(geometries) + assert isinstance(actual, np.ndarray) + assert actual.shape == (2, 3) + expected = shapely.orient_polygons(polygon) + assert (actual == expected).all() + + +def test_orient_polygons_array_like(): + # because we have a custom python implementation for older GEOS, need to + # ensure this has the same capabilities as numpy ufuncs to work with array-likes + polygon = Polygon( + [(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)], + holes=[[(2, 2), (2, 4), (4, 4), (4, 2), (2, 2)]], + ) + geometries = [polygon, Point(2, 2).buffer(1)] + actual = shapely.orient_polygons(ArrayLike(geometries)) + assert isinstance(actual, ArrayLike) + expected = shapely.orient_polygons(geometries) + assert_geometries_equal(np.asarray(actual), expected) + + +def test_buffer_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `quad_segs` for `buffer` is deprecated" + ): + shapely.buffer(point, 1.0, 8) + with pytest.deprecated_call( + match="positional arguments `quad_segs` and `cap_style` " + "for `buffer` are deprecated" + ): + shapely.buffer(point, 1.0, 8, "round") + with pytest.deprecated_call( + match="positional arguments `quad_segs`, `cap_style`, and `join_style` " + "for `buffer` are deprecated" + ): + shapely.buffer(point, 1.0, 8, "round", "round") + with pytest.deprecated_call(): + shapely.buffer(point, 1.0, 8, "round", "round", 5.0) + with pytest.deprecated_call(): + shapely.buffer(point, 1.0, 8, "round", "round", 5.0, False) + + +def test_offset_curve_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `quad_segs` for `offset_curve` is deprecated" + ): + shapely.offset_curve(line_string, 1.0, 8) + with pytest.deprecated_call( + match="positional arguments `quad_segs` and `join_style` " + "for `offset_curve` are deprecated" + ): + shapely.offset_curve(line_string, 1.0, 8, "round") + with pytest.deprecated_call( + match="positional arguments `quad_segs`, `join_style`, and `mitre_limit` " + "for `offset_curve` are deprecated" + ): + shapely.offset_curve(line_string, 1.0, 8, "round", 5.0) + + +def test_simplify_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `preserve_topology` for `simplify` is deprecated" + ): + shapely.simplify(line_string, 1.0, True) + + +def test_voronoi_polygons_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `extend_to` for `voronoi_polygons` is deprecated" + ): + shapely.voronoi_polygons(multi_point, 0.0, None) + with pytest.deprecated_call( + match="positional arguments `extend_to` and `only_edges` " + "for `voronoi_polygons` are deprecated" + ): + shapely.voronoi_polygons(multi_point, 0.0, None, False) + with pytest.deprecated_call( + match="positional arguments `extend_to`, `only_edges`, and `ordered` " + "for `voronoi_polygons` are deprecated" + ): + shapely.voronoi_polygons(multi_point, 0.0, None, False, False) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_coordinates.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_coordinates.py new file mode 100644 index 0000000000000000000000000000000000000000..a72d5a3cd733a54ed403e590fd3916e634af5e8e --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_coordinates.py @@ -0,0 +1,422 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_equal + +import shapely +from shapely import count_coordinates, get_coordinates, set_coordinates, transform +from shapely.tests.common import ( + empty, + empty_line_string_z, + empty_point, + empty_point_m, + empty_point_z, + empty_point_zm, + geometry_collection, + geometry_collection_z, + geometry_collection_zm, + line_string, + line_string_m, + line_string_z, + line_string_zm, + linear_ring, + multi_line_string, + multi_point, + multi_polygon, + point, + point_m, + point_z, + point_zm, + polygon, + polygon_with_hole, + polygon_z, +) + +nested_2 = shapely.geometrycollections([geometry_collection, point]) +nested_3 = shapely.geometrycollections([nested_2, point]) + + +@pytest.mark.parametrize( + "geoms,count", + [ + ([], 0), + ([empty], 0), + ([point, empty], 1), + ([empty, point, empty], 1), + ([point, None], 1), + ([None, point, None], 1), + ([point, point], 2), + ([point, point_z], 2), + ([line_string, linear_ring], 8), + ([polygon], 5), + ([polygon_with_hole], 10), + ([multi_point, multi_line_string], 4), + ([multi_polygon], 10), + ([geometry_collection], 3), + ([nested_2], 4), + ([nested_3], 5), + ], +) +def test_count_coords(geoms, count): + actual = count_coordinates(np.array(geoms, np.object_)) + assert actual == count + + +@pytest.mark.parametrize("include_m", [True, False]) +@pytest.mark.parametrize("include_z", [True, False]) +@pytest.mark.parametrize( + "geoms,x,y", + [ + ([], [], []), + ([empty], [], []), + ([point, empty], [2], [3]), + ([empty, point, empty], [2], [3]), + ([point, None], [2], [3]), + ([None, point, None], [2], [3]), + ([point, point], [2, 2], [3, 3]), + ( + [line_string, linear_ring], + [0, 1, 1, 0, 1, 1, 0, 0], + [0, 0, 1, 0, 0, 1, 1, 0], + ), + ([polygon], [0, 2, 2, 0, 0], [0, 0, 2, 2, 0]), + ( + [polygon_with_hole], + [0, 0, 10, 10, 0, 2, 2, 4, 4, 2], + [0, 10, 10, 0, 0, 2, 4, 4, 2, 2], + ), + ([multi_point, multi_line_string], [0, 1, 0, 1], [0, 2, 0, 2]), + ( + [multi_polygon], + [0, 1, 1, 0, 0, 2.1, 2.2, 2.2, 2.1, 2.1], + [0, 0, 1, 1, 0, 2.1, 2.1, 2.2, 2.2, 2.1], + ), + ([geometry_collection], [51, 52, 49], [-1, -1, 2]), + ([nested_2], [51, 52, 49, 2], [-1, -1, 2, 3]), + ([nested_3], [51, 52, 49, 2, 2], [-1, -1, 2, 3, 3]), + ], +) +def test_get_coords(geoms, x, y, include_z, include_m): + actual = get_coordinates(geoms, include_z=include_z, include_m=include_m) + expected = [x, y] + if include_z: + expected.append([np.nan] * len(x)) + if include_m: + expected.append([np.nan] * len(x)) + assert_equal(actual, np.array(expected, np.float64).T) + + +@pytest.mark.parametrize( + "geoms,index", + [ + ([], []), + ([empty], []), + ([point, empty], [0]), + ([empty, point, empty], [1]), + ([point, None], [0]), + ([None, point, None], [1]), + ([point, point], [0, 1]), + ([point, line_string], [0, 1, 1, 1]), + ([line_string, point], [0, 0, 0, 1]), + ([line_string, linear_ring], [0, 0, 0, 1, 1, 1, 1, 1]), + ], +) +def test_get_coords_index(geoms, index): + _, actual = get_coordinates(np.array(geoms, np.object_), return_index=True) + expected = np.array(index, dtype=np.intp) + assert_equal(actual, expected) + + +@pytest.mark.parametrize("order", ["C", "F"]) +def test_get_coords_index_multidim(order): + geometry = np.array([[point, line_string], [empty, empty]], order=order) + expected = [0, 1, 1, 1] # would be [0, 2, 2, 2] with fortran order + _, actual = get_coordinates(geometry, return_index=True) + assert_equal(actual, expected) + + +@pytest.mark.parametrize("include_m", [True, False]) +@pytest.mark.parametrize("include_z", [True, False]) +@pytest.mark.parametrize( + "geoms,x,y,z", + [ + ([point, point_z], [2, 2], [3, 3], [np.nan, 4]), + ([line_string_z], [0, 1, 1], [0, 0, 1], [4, 4, 4]), + ([polygon_z], [0, 2, 2, 0, 0], [0, 0, 2, 2, 0], [4, 4, 4, 4, 4]), + ([geometry_collection_z], [2, 0, 1, 1], [3, 0, 0, 1], [4, 4, 4, 4]), + ([point, empty_point], [2], [3], [np.nan]), + ], +) +def test_get_coords_z(geoms, x, y, z, include_z, include_m): + actual = get_coordinates(geoms, include_z=include_z, include_m=include_m) + expected = [x, y] + if include_z: + expected.append(z) + if include_m: + expected.append([np.nan] * len(x)) + assert_equal(actual, np.array(expected, np.float64).T) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +@pytest.mark.parametrize("include_m", [True, False]) +@pytest.mark.parametrize("include_z", [True, False]) +@pytest.mark.parametrize( + "geoms,x,y,z,m", + [ + ( + [point, point_z, point_m, point_zm], + [2, 2, 2, 2], + [3, 3, 3, 3], + [np.nan, 4, np.nan, 4], + [np.nan, np.nan, 5, 5], + ), + ( + [line_string, line_string_z, line_string_m, line_string_zm], + [0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1], + [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], + [np.nan, np.nan, np.nan, 4, 4, 4] * 2, + [np.nan] * 6 + [1, 2, 3, 1, 2, 3], + ), + ( + [geometry_collection_zm], + [2, 0, 1, 1], + [3, 0, 0, 1], + [4, 4, 4, 4], + [5, 1, 2, 3], + ), + ( + [point, empty_point, empty_point_z, empty_point_m, empty_point_zm], + [2], + [3], + [np.nan], + [np.nan], + ), + ], +) +def test_get_coords_zm(geoms, x, y, z, m, include_z, include_m): + actual = get_coordinates(geoms, include_z=include_z, include_m=include_m) + expected = [x, y] + if include_z: + expected.append(z) + if include_m: + expected.append(m) + assert_equal(actual, np.array(expected, np.float64).T) + + +def test_get_coords_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `include_z` for `get_coordinates` is deprecated" + ): + get_coordinates(point, False) + with pytest.deprecated_call( + match="positional arguments `include_z` and `return_index` " + "for `get_coordinates` are deprecated" + ): + get_coordinates(point, False, False) + + +@pytest.mark.parametrize("include_z", [True, False]) +@pytest.mark.parametrize( + "geoms,count,has_ring", + [ + ([], 0, False), + ([empty], 0, False), + ([empty_point], 0, False), + ([point, empty], 1, False), + ([empty, point, empty], 1, False), + ([point, None], 1, False), + ([None, point, None], 1, False), + ([point, point], 2, False), + ([point, point_z], 2, False), + ([line_string, linear_ring], 8, True), + ([line_string_z], 3, True), + ([polygon], 5, True), + ([polygon_z], 5, True), + ([polygon_with_hole], 10, True), + ([multi_point, multi_line_string], 4, False), + ([multi_polygon], 10, True), + ([geometry_collection], 3, False), + ([geometry_collection_z], 3, False), + ([nested_2], 4, False), + ([nested_3], 5, False), + ], +) +def test_set_coords(geoms, count, has_ring, include_z): + arr_geoms = np.array(geoms, np.object_) + n = 3 if include_z else 2 + coords = get_coordinates(arr_geoms, include_z=include_z) + np.random.random((1, n)) + new_geoms = set_coordinates(arr_geoms, coords) + assert_equal(coords, get_coordinates(new_geoms, include_z=include_z)) + + +def test_set_coords_nan(): + geoms = np.array([point]) + coords = np.array([[np.nan, np.inf]]) + new_geoms = set_coordinates(geoms, coords) + assert_equal(coords, get_coordinates(new_geoms)) + + +def test_set_coords_breaks_ring(): + with pytest.raises(shapely.GEOSException): + set_coordinates(linear_ring, np.random.random((5, 2))) + + +def test_set_coords_0dim(): + # a geometry input returns a geometry + actual = set_coordinates(point, [[1, 1]]) + assert isinstance(actual, shapely.Geometry) + # a 0-dim array input returns a 0-dim array + actual = set_coordinates(np.asarray(point), [[1, 1]]) + assert isinstance(actual, np.ndarray) + assert actual.ndim == 0 + + +@pytest.mark.parametrize("include_z", [True, False]) +def test_set_coords_mixed_dimension(include_z): + geoms = np.array([point, point_z], dtype=object) + coords = get_coordinates(geoms, include_z=include_z) + new_geoms = set_coordinates(geoms, coords * 2) + if include_z: + # preserve original dimensionality + assert not shapely.has_z(new_geoms[0]) + assert shapely.has_z(new_geoms[1]) + else: + # all 2D + assert not shapely.has_z(new_geoms).any() + + +@pytest.mark.parametrize("include_z", [True, False]) +@pytest.mark.parametrize( + "geoms", + [[], [empty], [None, point, None], [nested_3], [point, point_z], [line_string_z]], +) +@pytest.mark.parametrize("interleaved", [True, False]) +def test_transform(geoms, include_z, interleaved): + geoms = np.array(geoms, np.object_) + coordinates_before = get_coordinates(geoms, include_z=include_z) + if interleaved: + transformation = lambda coords: coords + 1 + elif not include_z: + transformation = lambda x, y: (x + 1, y + 1) + else: + transformation = lambda x, y, z: (x + 1, y + 1, z + 1) + new_geoms = transform( + geoms, transformation, include_z=include_z, interleaved=interleaved + ) + assert new_geoms is not geoms + coordinates_after = get_coordinates(new_geoms, include_z=include_z) + assert_allclose(coordinates_before + 1, coordinates_after, equal_nan=True) + + +def test_transform_0dim(): + # a geometry input returns a geometry + actual = transform(point, lambda x: x + 1) + assert isinstance(actual, shapely.Geometry) + # a 0-dim array input returns a 0-dim array + actual = transform(np.asarray(point), lambda x: x + 1) + assert isinstance(actual, np.ndarray) + assert actual.ndim == 0 + + +def test_transform_no_geoms(): + # a geometry input returns a geometry + actual = transform([], lambda x: x + 1) + assert actual.shape == (0,) + + +def test_transform_check_shape(): + def remove_coord(arr): + return arr[:-1] + + with pytest.raises(ValueError): + transform(linear_ring, remove_coord) + + +def test_transform_correct_coordinate_dimension(): + # ensure that new geometry is 2D with include_z=False + geom = line_string_z + assert shapely.get_coordinate_dimension(geom) == 3 + new_geom = transform(geom, lambda x: x + 1, include_z=False) + assert shapely.get_coordinate_dimension(new_geom) == 2 + + +@pytest.mark.parametrize( + "geom", + [ + empty_point_z, + empty_line_string_z, + ], +) +def test_transform_empty_preserve_z(geom): + assert shapely.get_coordinate_dimension(geom) == 3 + new_geom = transform(geom, lambda x: x + 1, include_z=True) + assert shapely.get_coordinate_dimension(new_geom) == 3 + + +@pytest.mark.parametrize( + "geom", + [ + empty_point_z, + empty_line_string_z, + ], +) +def test_transform_remove_z(geom): + assert shapely.get_coordinate_dimension(geom) == 3 + new_geom = transform(geom, lambda x: x + 1, include_z=False) + assert shapely.get_coordinate_dimension(new_geom) == 2 + + +@pytest.mark.parametrize( + "geom,expected", + [ + (line_string, 2), + (line_string_z, 3), + ], +) +def test_transform_auto_coordinate_dimension(geom, expected): + new_geom = transform(geom, lambda x: x + 1, include_z=None) + assert (shapely.get_coordinate_dimension(new_geom) == expected).all() + + +def test_transform_auto_coordinate_dimension_mixed(): + new_geom = transform([line_string, line_string_z], lambda x: x + 1, include_z=None) + assert_equal(shapely.get_coordinate_dimension(new_geom), [2, 3]) + assert_equal( + shapely.get_coordinates(line_string, include_z=False) + 1, + shapely.get_coordinates(new_geom[0], include_z=False), + ) + assert_equal( + shapely.get_coordinates(line_string_z, include_z=True) + 1, + shapely.get_coordinates(new_geom[1], include_z=True), + ) + + +def transform_non_interleaved(x, y, z=None): + if z is None: + return [x + 1, y + 2] + else: + return [x + 1, y + 2, z + 3] + + +def test_transform_auto_coordinate_dimension_mixed_interleaved(): + new_geom = transform( + [line_string, line_string_z], + transform_non_interleaved, + include_z=None, + interleaved=False, + ) + assert_equal(shapely.get_coordinate_dimension(new_geom), [2, 3]) + assert_equal( + shapely.get_coordinates(line_string, include_z=False) + [1, 2], + shapely.get_coordinates(new_geom[0], include_z=False), + ) + assert_equal( + shapely.get_coordinates(line_string_z, include_z=True) + [1, 2, 3], + shapely.get_coordinates(new_geom[1], include_z=True), + ) + + +def test_transform_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `include_z` for `transform` is deprecated" + ): + transform(line_string_z, lambda x: x + 1, False) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_coverage.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..db6f370ede58ce0505ee89de297de62a6dc5482d --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_coverage.py @@ -0,0 +1,249 @@ +import numpy as np +import pytest + +import shapely +from shapely import ( + Geometry, + LineString, + MultiPolygon, + Polygon, +) +from shapely.errors import UnsupportedGEOSVersionError +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + all_types, + all_types_z, + empty_line_string, +) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="requires >= 3.12") +@pytest.mark.parametrize("geometry", all_types + all_types_z) +def test_coverage_is_valid(geometry): + actual = shapely.coverage_is_valid([geometry]) + assert actual.ndim == 0 + assert actual.dtype == np.bool_ + assert actual.item() is True + + actual = shapely.coverage_invalid_edges([geometry]) + expected = np.array([empty_line_string], dtype=object) + assert_geometries_equal(actual, expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="requires >= 3.12") +def test_coverage_is_valid_non_polygonal(): + # non-polygonal geometries are ignored to validate the coverage + # (e.g. even if you have crossing linestrings) + geoms = [ + LineString([(0, 0), (1, 1)]), + LineString([(1, 0), (0, 1)]), + Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), + ] + assert shapely.coverage_is_valid(geoms) + assert (shapely.coverage_invalid_edges(geoms) == empty_line_string).all() + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="requires >= 3.12") +def test_coverage_is_valid_polygonal(): + # adjacent triangles + poly1 = Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]) + poly2 = Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]) + assert shapely.coverage_is_valid([poly1, poly2]) + assert shapely.is_empty(shapely.coverage_invalid_edges([poly1, poly2])).all() + + # shared egde but without identical vertices + poly2b = Polygon([(0, 0), (0.5, 0.5), (1, 1), (0, 1), (0, 0)]) + assert not shapely.coverage_is_valid([poly1, poly2b]) + result = shapely.coverage_invalid_edges([poly1, poly2b]) + expected = [LineString([(0, 0), (1, 1)]), LineString([(0, 0), (0.5, 0.5), (1, 1)])] + assert_geometries_equal(result, expected) + + # overlap + poly3 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]) + assert not shapely.coverage_is_valid([poly1, poly3]) + result = shapely.coverage_invalid_edges([poly1, poly3]) + assert not shapely.is_empty(result).any() + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="requires >= 3.12") +def test_coverage_is_valid_gap_width(): + # shared edge of boxes with multiple vertices + poly1 = shapely.from_wkt("POLYGON ((0 10, 10 10, 10 7, 10 3, 10 0, 0 0, 0 10))") + poly2 = shapely.from_wkt("POLYGON ((10 10, 20 10, 20 0, 10 0, 10 3, 10 7, 10 10))") + + # extra vertex in middle of shared edge + poly2_extra = shapely.from_wkt( + "POLYGON ((10 10, 20 10, 20 0, 10 0, 10 3, 10 5, 10 7, 10 10))" + ) + # extra vertex shifted -> gap of max 1 wide + poly2_shift = shapely.from_wkt( + "POLYGON ((10 10, 20 10, 20 0, 10 0, 10 3, 11 5, 10 7, 10 10))" + ) + + # valid coverage -> gap_width value does not matter + assert shapely.coverage_is_valid([poly1, poly2], gap_width=0.0) + assert shapely.coverage_is_valid([poly1, poly2], gap_width=2.0) + + result = shapely.coverage_invalid_edges([poly1, poly2], gap_width=0.0) + assert_geometries_equal(result, [empty_line_string] * 2) + result = shapely.coverage_invalid_edges([poly1, poly2], gap_width=2.0) + assert_geometries_equal(result, [empty_line_string] * 2) + + # invalid coverage -> gap_width value does not matter + assert not shapely.coverage_is_valid([poly1, poly2_extra], gap_width=0.0) + assert not shapely.coverage_is_valid([poly1, poly2_extra], gap_width=2.0) + + expected = shapely.from_wkt( + ["LINESTRING (10 7, 10 3)", "LINESTRING (10 3, 10 5, 10 7)"] + ) + result = shapely.coverage_invalid_edges([poly1, poly2_extra], gap_width=0.0) + assert_geometries_equal(result, expected) + result = shapely.coverage_invalid_edges([poly1, poly2_extra], gap_width=2.0) + assert_geometries_equal(result, expected) + + # coverage with gap of 1 unit wide + assert shapely.coverage_is_valid([poly1, poly2_shift], gap_width=0.0) + assert shapely.coverage_is_valid([poly1, poly2_shift], gap_width=0.5) + assert not shapely.coverage_is_valid([poly1, poly2_shift], gap_width=1.0) + assert not shapely.coverage_is_valid([poly1, poly2_shift], gap_width=1.5) + # TODO why this behaviour? + assert shapely.coverage_is_valid([poly1, poly2_shift], gap_width=2.0) + + assert_geometries_equal( + shapely.coverage_invalid_edges([poly1, poly2_shift], gap_width=0.0), + [empty_line_string] * 2, + ) + assert_geometries_equal( + shapely.coverage_invalid_edges([poly1, poly2_shift], gap_width=1.0), + shapely.from_wkt(["LINESTRING (10 7, 10 3)", "LINESTRING (10 3, 11 5, 10 7)"]), + ) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="requires >= 3.12") +def test_coverage_invalid_edges_gufunc(): + poly1 = shapely.from_wkt("POLYGON ((0 10, 10 10, 10 7, 10 3, 10 0, 0 0, 0 10))") + poly2 = shapely.from_wkt("POLYGON ((10 10, 20 10, 20 0, 10 0, 10 3, 10 7, 10 10))") + poly2_extra = shapely.from_wkt( + "POLYGON ((10 10, 20 10, 20 0, 10 0, 10 3, 10 5, 10 7, 10 10))" + ) + poly3 = shapely.from_wkt("POLYGON ((20 10, 30 10, 30 7, 30 3, 30 0, 20 0, 20 10))") + + arr = np.array([[poly1, poly2, poly3], [poly1, poly2_extra, poly3]]) + result = shapely.lib.coverage_invalid_edges(arr, 0.0) + expected = shapely.from_wkt( + [ + ["LINESTRING EMPTY"] * 3, + [ + "LINESTRING (10 7, 10 3)", + "LINESTRING (10 3, 10 5, 10 7)", + "LINESTRING EMPTY", + ], + ] + ) + assert_geometries_equal(result, expected) + + arr2 = np.array(arr, order="F") + result = shapely.lib.coverage_invalid_edges(arr2, 0.0) + assert_geometries_equal(result, expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +@pytest.mark.parametrize("geometry", all_types) +def test_coverage_simplify_scalars(geometry): + if geometry.geom_type in ("Polygon", "MultiPolygon"): + actual = shapely.coverage_simplify(geometry, 0.0) + assert isinstance(actual, Geometry) + assert shapely.get_type_id(actual) == shapely.get_type_id(geometry) + assert actual.equals(geometry) + else: + with pytest.raises(TypeError, match="incorrect geometry type"): + shapely.coverage_simplify(geometry, 0.0) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +@pytest.mark.parametrize("geometry", all_types) +def test_coverage_simplify_geom_types(geometry): + if geometry.geom_type in ("Polygon", "MultiPolygon"): + actual = shapely.coverage_simplify([geometry, geometry], 0.0) + assert isinstance(actual, np.ndarray) + assert actual.shape == (2,) + assert (shapely.get_type_id(actual) == shapely.get_type_id(geometry)).all() + else: + with pytest.raises(TypeError, match="incorrect geometry type"): + shapely.coverage_simplify([geometry, geometry], 0.0) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +def test_coverage_simplify_multipolygon(): + mp = MultiPolygon( + [ + Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), + Polygon([(2, 2), (2, 3), (3, 3), (3, 2), (2, 2)]), + ] + ) + actual = shapely.coverage_simplify(mp, 1) + assert actual.equals( + shapely.from_wkt( + "MULTIPOLYGON (((0 1, 1 1, 1 0, 0 1)), ((2 3, 3 3, 3 2, 2 3)))" + ) + ) + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +def test_coverage_simplify_array(): + polygons = np.array( + [ + shapely.Polygon([(0, 0), (20, 0), (20, 10), (10, 5), (0, 10), (0, 0)]), + shapely.Polygon([(0, 10), (10, 5), (20, 10), (20, 20), (0, 20), (0, 10)]), + ] + ) + low_tolerance = shapely.coverage_simplify(polygons, 1) + mid_tolerance = shapely.coverage_simplify(polygons, 8) + high_tolerance = shapely.coverage_simplify(polygons, 10) + + assert shapely.equals(low_tolerance, shapely.normalize(polygons)).all() + assert shapely.equals( + mid_tolerance, + shapely.from_wkt( + [ + "POLYGON ((20 10, 0 10, 0 0, 20 0, 20 10))", + "POLYGON ((20 10, 0 10, 0 20, 20 20, 20 10))", + ] + ), + ).all() + assert shapely.equals( + high_tolerance, + shapely.from_wkt( + [ + "POLYGON ((20 10, 0 10, 20 0, 20 10))", + "POLYGON ((20 10, 0 10, 0 20, 20 10))", + ] + ), + ).all() + + no_boundary = shapely.coverage_simplify(polygons, 10, simplify_boundary=False) + assert shapely.equals( + no_boundary, + shapely.from_wkt( + [ + "POLYGON ((20 10, 0 10, 0 0, 20 0, 20 10))", + "POLYGON ((20 10, 0 10, 0 20, 20 20, 20 10))", + ] + ), + ).all() + + +@pytest.mark.skipif(shapely.geos_version >= (3, 12, 0), reason="requires >= 3.12") +def test_coverage_unsupported_geos(): + geoms = [ + Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]), + Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]), + ] + with pytest.raises(UnsupportedGEOSVersionError): + shapely.coverage_is_valid(geoms) + + with pytest.raises(UnsupportedGEOSVersionError): + shapely.coverage_invalid_edges(geoms) + + with pytest.raises(UnsupportedGEOSVersionError): + shapely.coverage_simplify(geoms, 1.0) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_creation.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_creation.py new file mode 100644 index 0000000000000000000000000000000000000000..6f7d08f445f59cdd31b157c01e01d187f5c8ae83 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_creation.py @@ -0,0 +1,742 @@ +"""See test_creation_indices.py for tests with 'indices' parameter.""" + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +import shapely + +# Note: Point is not imported because it is overridden for testing +from shapely import ( + GeometryCollection, + GeometryType, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Polygon, +) +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + empty_polygon, + geometry_collection, + ignore_invalid, + line_string, + linear_ring, + multi_line_string, + multi_point, + multi_polygon, + point, + polygon, +) + + +def box_tpl(x1, y1, x2, y2): + return (x2, y1), (x2, y2), (x1, y2), (x1, y1), (x2, y1) + + +def test_points_from_coords(): + actual = shapely.points([[0, 0], [2, 2]]) + assert_geometries_equal(actual, [shapely.Point(0, 0), shapely.Point(2, 2)]) + + +def test_points_from_xy(): + actual = shapely.points(2, [0, 1]) + assert_geometries_equal(actual, [shapely.Point(2, 0), shapely.Point(2, 1)]) + + +def test_points_from_xyz(): + actual = shapely.points(1, 1, [0, 1]) + assert_geometries_equal(actual, [shapely.Point(1, 1, 0), shapely.Point(1, 1, 1)]) + + +def test_points_invalid_ndim(): + with pytest.raises(ValueError, match="dimension should be 2 or 3, got 4"): + shapely.points([0, 1, 2, 3]) + + with pytest.raises(ValueError, match="dimension should be 2 or 3, got 1"): + shapely.points([0]) + + +@pytest.mark.skipif( + shapely.geos_version[:2] not in ((3, 10), (3, 11), (3, 12)), + reason="GEOS not in 3.10, 3.11, 3.12", +) +def test_points_nan_all_nan_becomes_empty(): + actual = shapely.points(np.nan, np.nan) + assert actual.wkt == "POINT EMPTY" + + +@pytest.mark.skipif( + shapely.geos_version[:2] not in ((3, 10), (3, 11)), + reason="GEOS not in 3.10, 3.11", +) +def test_points_nan_3D_all_nan_becomes_empty_2D(): + actual = shapely.points(np.nan, np.nan, np.nan) + assert actual.wkt == "POINT EMPTY" + + +@pytest.mark.skipif(shapely.geos_version[:2] != (3, 12), reason="GEOS != 3.12") +def test_points_nan_3D_all_nan_becomes_empty(): + actual = shapely.points(np.nan, np.nan, np.nan) + assert actual.wkt == "POINT Z EMPTY" + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +@pytest.mark.parametrize( + "coords,expected_wkt", + [ + pytest.param( + [np.nan, np.nan], + "POINT (NaN NaN)", + marks=pytest.mark.skipif( + shapely.geos_version < (3, 13, 0), reason="GEOS < 3.13" + ), + ), + pytest.param( + [np.nan, np.nan, np.nan], + "POINT Z (NaN NaN NaN)", + marks=pytest.mark.skipif( + shapely.geos_version < (3, 13, 0), reason="GEOS < 3.13" + ), + ), + ([1, np.nan], "POINT (1 NaN)"), + ([np.nan, 1], "POINT (NaN 1)"), + ([np.nan, 1, np.nan], "POINT Z (NaN 1 NaN)"), + ([np.nan, np.nan, 1], "POINT Z (NaN NaN 1)"), + ], +) +def test_points_handle_nan_allow(coords, expected_wkt): + actual = shapely.points(coords, handle_nan="allow") + assert actual.wkt == expected_wkt + + +@pytest.mark.parametrize( + "coords,handle_nan,expected_wkt", + [ + ([0, np.nan], "skip", "POINT EMPTY"), + ([np.nan, 0], "skip", "POINT EMPTY"), + ([0, np.nan, 1], "skip", "POINT Z EMPTY"), + ([0, 1, np.nan], "skip", "POINT Z EMPTY"), + ([0, 1], "error", "POINT (0 1)"), + ([0, 1, 2], "error", "POINT Z (0 1 2)"), + ([0, np.inf], "skip", "POINT EMPTY"), + ], +) +def test_points_handle_nan(coords, handle_nan, expected_wkt): + actual = shapely.points(coords, handle_nan=handle_nan) + assert actual.wkt in expected_wkt + + +@pytest.mark.parametrize( + "coords", + [ + [0, np.nan], + [np.nan, 0], + [0, 0, np.nan], + [0, np.inf], + [0, -np.inf], + ], +) +def test_points_handle_nan_error(coords): + with pytest.raises(ValueError, match=".*NaN.*"): + shapely.points(coords, handle_nan="error") + + +def test_linestrings_from_coords(): + actual = shapely.linestrings([[[0, 0], [1, 1]], [[0, 0], [2, 2]]]) + assert_geometries_equal( + actual, + [ + LineString([(0, 0), (1, 1)]), + LineString([(0, 0), (2, 2)]), + ], + ) + + +def test_linestrings_from_xy(): + actual = shapely.linestrings([0, 1], [2, 3]) + assert_geometries_equal(actual, LineString([(0, 2), (1, 3)])) + + +def test_linestrings_from_xy_broadcast(): + x = [0, 1] # the same X coordinates for both linestrings + y = [2, 3], [4, 5] # each linestring has a different set of Y coordinates + actual = shapely.linestrings(x, y) + assert_geometries_equal( + actual, + [ + LineString([(0, 2), (1, 3)]), + LineString([(0, 4), (1, 5)]), + ], + ) + + +def test_linestrings_from_xyz(): + actual = shapely.linestrings([0, 1], [2, 3], 0) + assert_geometries_equal(actual, LineString([(0, 2, 0), (1, 3, 0)])) + + +@pytest.mark.parametrize("dim", [2, 3]) +def test_linestrings_buffer(dim): + coords = np.random.randn(10, 3, dim) + coords1 = np.asarray(coords, order="C") + result1 = shapely.linestrings(coords1) + + coords2 = np.asarray(coords1, order="F") + result2 = shapely.linestrings(coords2) + assert_geometries_equal(result1, result2) + + # creating (.., 8, 8*3) strided array so it uses copyFromArrays + coords3 = np.asarray(np.swapaxes(np.swapaxes(coords, 0, 2), 1, 0), order="F") + coords3 = np.swapaxes(np.swapaxes(coords3, 0, 2), 1, 2) + result3 = shapely.linestrings(coords3) + assert_geometries_equal(result1, result3) + + +def test_linestrings_empty(): + actual = shapely.linestrings(np.empty((0, 2))) + assert actual.is_empty + + +def test_linestrings_invalid_shape_scalar(): + with pytest.raises(ValueError): + shapely.linestrings((1, 1)) + + +@pytest.mark.parametrize( + "shape", + [ + (2, 1, 2), # 2 linestrings of 1 2D point + (1, 1, 2), # 1 linestring of 1 2D point + (1, 2), # 1 linestring of 1 2D point (scalar) + ], +) +def test_linestrings_invalid_shape(shape): + with pytest.raises(shapely.GEOSException): + shapely.linestrings(np.ones(shape)) + + +def test_linestrings_invalid_ndim(): + msg = r"The ordinate \(last\) dimension should be 2 or 3, got {}" + + coords = np.ones((10, 2, 4), order="C") + with pytest.raises(ValueError, match=msg.format(4)): + shapely.linestrings(coords) + + coords = np.ones((10, 2, 4), order="F") + with pytest.raises(ValueError, match=msg.format(4)): + shapely.linestrings(coords) + + coords = np.swapaxes(np.swapaxes(np.ones((10, 2, 4)), 0, 2), 1, 0) + coords = np.swapaxes(np.swapaxes(np.asarray(coords, order="F"), 0, 2), 1, 2) + with pytest.raises(ValueError, match=msg.format(4)): + shapely.linestrings(coords) + + # too few ordinates + coords = np.ones((10, 2, 1)) + with pytest.raises(ValueError, match=msg.format(1)): + shapely.linestrings(coords) + + +@pytest.mark.parametrize( + "coords", + [ + [[0, 1], [2, float("nan")]], + [[0, 1, float("nan")], [2, 2, float("nan")]], + [[0, 1, 2], [2, 2, float("nan")]], + [[0, 1, float("nan")], [2, 2, 3]], + [[float("nan"), float("nan")], [float("nan"), float("nan")]], + ], +) +def test_linestrings_handle_nan_allow(coords): + with ignore_invalid(): + actual = shapely.linestrings(coords, handle_nan="allow") + actual = shapely.get_coordinates(actual, include_z=len(coords[0]) == 3) + + assert_array_equal(actual, coords) + + +@pytest.mark.parametrize( + "coords", + [ + [[2, float("nan")], [0, 1], [2, 3]], + [[0, 1], [2, float("nan")], [2, 3]], + [[0, 1], [2, 3], [2, float("nan")]], + ], +) +def test_linestrings_handle_nan_skip(coords): + actual = shapely.linestrings(coords, handle_nan="skip") + assert_geometries_equal(actual, LineString([(0, 1), (2, 3)])) + + +def test_linestrings_handle_nan_skip_invalid(): + with pytest.raises(shapely.GEOSException): + shapely.linestrings([[0, 1], [2, float("nan")]], handle_nan="skip") + + +def test_linestrings_handle_nan_skip_only_nan(): + # all-nan becomes an empty linestring + actual = shapely.linestrings(np.full((3, 2), fill_value=np.nan), handle_nan="skip") + assert actual.is_empty + + +def test_linestrings_handle_nan_error(): + with pytest.raises(ValueError, match=".*NaN.*"): + shapely.linestrings([[0, 1], [2, float("nan")], [2, 3]], handle_nan="error") + + +def test_linearrings(): + actual = shapely.linearrings(box_tpl(0, 0, 1, 1)) + assert_geometries_equal( + actual, LinearRing([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)]) + ) + + +def test_linearrings_empty(): + actual = shapely.linearrings(np.empty((0, 2))) + assert actual.is_empty + + +def test_linearrings_from_xy(): + actual = shapely.linearrings([0, 1, 2, 0], [3, 4, 5, 3]) + assert_geometries_equal(actual, LinearRing([(0, 3), (1, 4), (2, 5), (0, 3)])) + + +def test_linearrings_unclosed(): + actual = shapely.linearrings(box_tpl(0, 0, 1, 1)[:-1]) + assert_geometries_equal( + actual, LinearRing([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)]) + ) + + +def test_linearrings_unclosed_all_coords_equal(): + actual = shapely.linearrings([(0, 0), (0, 0), (0, 0)]) + assert_geometries_equal(actual, LinearRing([(0, 0), (0, 0), (0, 0), (0, 0)])) + + +def test_linearrings_invalid_shape_scalar(): + with pytest.raises(ValueError): + shapely.linearrings((1, 1)) + + +@pytest.mark.parametrize( + "shape", + [ + (2, 1, 2), # 2 linearrings of 1 2D point + (1, 1, 2), # 1 linearring of 1 2D point + (1, 2), # 1 linearring of 1 2D point (scalar) + (2, 2, 2), # 2 linearrings of 2 2D points + (1, 2, 2), # 1 linearring of 2 2D points + (2, 2), # 1 linearring of 2 2D points (scalar) + ], +) +def test_linearrings_invalid_shape(shape): + coords = np.ones(shape) + with pytest.raises(ValueError): + shapely.linearrings(coords) + + # make sure the first coordinate != second coordinate + coords[..., 1] += 1 + with pytest.raises(ValueError): + shapely.linearrings(coords) + + +def test_linearrings_invalid_ndim(): + msg = r"The ordinate \(last\) dimension should be 2 or 3, got {}" + + coords1 = np.random.randn(10, 3, 4) + with pytest.raises(ValueError, match=msg.format(4)): + shapely.linearrings(coords1) + + coords2 = np.hstack((coords1, coords1[:, [0], :])) + with pytest.raises(ValueError, match=msg.format(4)): + shapely.linearrings(coords2) + + # too few ordinates + coords3 = np.random.randn(10, 3, 1) + with pytest.raises(ValueError, match=msg.format(1)): + shapely.linearrings(coords3) + + +def test_linearrings_all_nan(): + coords = np.full((4, 2), np.nan) + with pytest.raises(shapely.GEOSException): + shapely.linearrings(coords) + + +@pytest.mark.parametrize("dim", [2, 3]) +@pytest.mark.parametrize("order", ["C", "F"]) +def test_linearrings_buffer(dim, order): + coords1 = np.random.randn(10, 4, dim) + coords1 = np.asarray(coords1, order=order) + result1 = shapely.linearrings(coords1) + + # with manual closure -> can directly copy from buffer if C order + coords2 = np.hstack((coords1, coords1[:, [0], :])) + coords2 = np.asarray(coords2, order=order) + result2 = shapely.linearrings(coords2) + assert_geometries_equal(result1, result2) + + # create scalar -> can also directly copy from buffer if F order + coords3 = np.asarray(coords2[0], order=order) + result3 = shapely.linearrings(coords3) + assert_geometries_equal(result3, result1[0]) + + +@pytest.mark.parametrize( + "coords", + [ + [[0, 2], [1, float("nan")], [1, 3], [0, 2]], + [[0, 2], [float("nan"), 0], [1, 3], [0, 2]], + [[0, 2, 5], [float("nan"), 2, 5], [1, 3, 5], [0, 2, 5]], + [[0, 2, 5], [1, 2, float("nan")], [1, 3, 5], [0, 2, 5]], + ], +) +def test_linearrings_handle_nan_allow(coords): + with ignore_invalid(): + actual = shapely.linearrings(coords, handle_nan="allow") + actual = shapely.get_coordinates(actual, include_z=len(coords[0]) == 3) + + assert_array_equal(actual, coords) + + +@pytest.mark.parametrize( + "x,y", + [ + ([0, 1, float("nan"), 2, 0], [3, 4, 5, 5, 3]), + ([0, 1, 1, 2, 0], [3, 4, float("nan"), 5, 3]), + ([0, 1, 2, 0, float("nan")], [3, 4, 5, 3, 3]), + ([float("nan"), 0, 1, 2, 0], [3, 3, 4, 5, 3]), + ], +) +def test_linearrings_handle_nan_skip(x, y): + actual = shapely.linearrings(x, y, handle_nan="skip") + assert_geometries_equal(actual, LinearRing([(0, 3), (1, 4), (2, 5), (0, 3)])) + + +def test_linearrings_handle_nan_skip_invalid(): + with pytest.raises(ValueError): + shapely.linearrings([0, float("nan"), 0], [3, 4, 3], handle_nan="skip") + + +def test_linearrings_handle_nan_skip_only_nan(): + actual = shapely.linearrings(np.full((5, 2), fill_value=np.nan), handle_nan="skip") + assert actual.is_empty + + +def test_linearrings_handle_nan_error(): + with pytest.raises(ValueError, match=".*NaN.*"): + shapely.linearrings( + [0, 1, float("nan"), 2, 0], [3, 4, 5, 5, 3], handle_nan="error" + ) + + +def test_polygon_from_linearring(): + actual = shapely.polygons(shapely.linearrings(box_tpl(0, 0, 1, 1))) + assert_geometries_equal(actual, Polygon([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)])) + + +def test_polygons_none(): + assert_geometries_equal(shapely.polygons(None), empty_polygon) + assert_geometries_equal(shapely.polygons(None, holes=[linear_ring]), empty_polygon) + + +def test_polygons(): + actual = shapely.polygons(box_tpl(0, 0, 1, 1)) + assert_geometries_equal(actual, Polygon([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)])) + + +def test_polygon_no_hole_list_raises(): + with pytest.raises(ValueError): + shapely.polygons(box_tpl(0, 0, 10, 10), box_tpl(1, 1, 2, 2)) + + +def test_polygon_no_hole_wrong_type(): + with pytest.raises((TypeError, shapely.GEOSException)): + shapely.polygons(point) + + +def test_polygon_with_hole_wrong_type(): + with pytest.raises((TypeError, shapely.GEOSException)): + shapely.polygons(point, [linear_ring]) + + +def test_polygon_wrong_hole_type(): + with pytest.raises((TypeError, shapely.GEOSException)): + shapely.polygons(linear_ring, [point]) + + +def test_polygon_with_1_hole(): + actual = shapely.polygons(box_tpl(0, 0, 10, 10), [box_tpl(1, 1, 2, 2)]) + assert shapely.area(actual) == 99.0 + + +def test_polygon_with_2_holes(): + actual = shapely.polygons( + box_tpl(0, 0, 10, 10), [box_tpl(1, 1, 2, 2), box_tpl(3, 3, 4, 4)] + ) + assert shapely.area(actual) == 98.0 + + +def test_polygon_with_none_hole(): + actual = shapely.polygons( + shapely.linearrings(box_tpl(0, 0, 10, 10)), + [ + shapely.linearrings(box_tpl(1, 1, 2, 2)), + None, + shapely.linearrings(box_tpl(3, 3, 4, 4)), + ], + ) + assert shapely.area(actual) == 98.0 + + +def test_2_polygons_with_same_hole(): + actual = shapely.polygons( + [box_tpl(0, 0, 10, 10), box_tpl(0, 0, 5, 5)], [box_tpl(1, 1, 2, 2)] + ) + assert shapely.area(actual).tolist() == [99.0, 24.0] + + +def test_2_polygons_with_2_same_holes(): + actual = shapely.polygons( + [box_tpl(0, 0, 10, 10), box_tpl(0, 0, 5, 5)], + [box_tpl(1, 1, 2, 2), box_tpl(3, 3, 4, 4)], + ) + assert shapely.area(actual).tolist() == [98.0, 23.0] + + +def test_2_polygons_with_different_holes(): + actual = shapely.polygons( + [box_tpl(0, 0, 10, 10), box_tpl(0, 0, 5, 5)], + [[box_tpl(1, 1, 3, 3)], [box_tpl(1, 1, 2, 2)]], + ) + assert shapely.area(actual).tolist() == [96.0, 24.0] + + +def test_polygons_not_enough_points_in_shell_scalar(): + with pytest.raises(ValueError): + shapely.polygons((1, 1)) + + +@pytest.mark.parametrize( + "shape", + [ + (2, 1, 2), # 2 linearrings of 1 2D point + (1, 1, 2), # 1 linearring of 1 2D point + (1, 2), # 1 linearring of 1 2D point (scalar) + (2, 2, 2), # 2 linearrings of 2 2D points + (1, 2, 2), # 1 linearring of 2 2D points + (2, 2), # 1 linearring of 2 2D points (scalar) + ], +) +def test_polygons_not_enough_points_in_shell(shape): + coords = np.ones(shape) + with pytest.raises(ValueError): + shapely.polygons(coords) + + # make sure the first coordinate != second coordinate + coords[..., 1] += 1 + with pytest.raises(ValueError): + shapely.polygons(coords) + + +def test_polygons_not_enough_points_in_holes_scalar(): + with pytest.raises(ValueError): + shapely.polygons(np.ones((1, 4, 2)), (1, 1)) + + +@pytest.mark.parametrize( + "shape", + [ + (2, 1, 2), # 2 linearrings of 1 2D point + (1, 1, 2), # 1 linearring of 1 2D point + (1, 2), # 1 linearring of 1 2D point (scalar) + (2, 2, 2), # 2 linearrings of 2 2D points + (1, 2, 2), # 1 linearring of 2 2D points + (2, 2), # 1 linearring of 2 2D points (scalar) + ], +) +def test_polygons_not_enough_points_in_holes(shape): + coords = np.ones(shape) + with pytest.raises(ValueError): + shapely.polygons(np.ones((1, 4, 2)), coords) + + # make sure the first coordinate != second coordinate + coords[..., 1] += 1 + with pytest.raises(ValueError): + shapely.polygons(np.ones((1, 4, 2)), coords) + + +@pytest.mark.parametrize( + "func,expected", + [ + (shapely.multipoints, MultiPoint()), + (shapely.multilinestrings, MultiLineString()), + (shapely.multipolygons, MultiPolygon()), + (shapely.geometrycollections, GeometryCollection()), + ], +) +def test_create_collection_only_none(func, expected): + actual = func(np.array([None], dtype=object)) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "func,sub_geom", + [ + (shapely.multipoints, point), + (shapely.multilinestrings, line_string), + (shapely.multilinestrings, linear_ring), + (shapely.multipolygons, polygon), + (shapely.geometrycollections, point), + (shapely.geometrycollections, line_string), + (shapely.geometrycollections, linear_ring), + (shapely.geometrycollections, polygon), + (shapely.geometrycollections, multi_point), + (shapely.geometrycollections, multi_line_string), + (shapely.geometrycollections, multi_polygon), + (shapely.geometrycollections, geometry_collection), + ], +) +def test_create_collection(func, sub_geom): + actual = func([sub_geom, sub_geom]) + assert shapely.get_num_geometries(actual) == 2 + + +@pytest.mark.parametrize( + "func,sub_geom", + [ + (shapely.multipoints, point), + (shapely.multilinestrings, line_string), + (shapely.multipolygons, polygon), + (shapely.geometrycollections, polygon), + ], +) +def test_create_collection_skips_none(func, sub_geom): + actual = func([sub_geom, None, None, sub_geom]) + assert shapely.get_num_geometries(actual) == 2 + + +@pytest.mark.parametrize( + "func,sub_geom", + [ + (shapely.multipoints, line_string), + (shapely.multipoints, geometry_collection), + (shapely.multipoints, multi_point), + (shapely.multilinestrings, point), + (shapely.multilinestrings, polygon), + (shapely.multilinestrings, multi_line_string), + (shapely.multipolygons, linear_ring), + (shapely.multipolygons, multi_point), + (shapely.multipolygons, multi_polygon), + ], +) +def test_create_collection_wrong_geom_type(func, sub_geom): + with pytest.raises(TypeError): + func([sub_geom]) + + +@pytest.mark.parametrize( + "coords,ccw,expected", + [ + ((0, 0, 1, 1), True, Polygon([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)])), + ( + (0, 0, 1, 1), + False, + Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), + ), + ], +) +def test_box(coords, ccw, expected): + actual = shapely.box(*coords, ccw=ccw) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "coords,ccw,expected", + [ + ( + (0, 0, [1, 2], [1, 2]), + True, + [ + Polygon([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)]), + Polygon([(2, 0), (2, 2), (0, 2), (0, 0), (2, 0)]), + ], + ), + ( + (0, 0, [1, 2], [1, 2]), + [True, False], + [ + Polygon([(1, 0), (1, 1), (0, 1), (0, 0), (1, 0)]), + Polygon([(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)]), + ], + ), + ], +) +def test_box_array(coords, ccw, expected): + actual = shapely.box(*coords, ccw=ccw) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "coords", + [ + [np.nan, np.nan, np.nan, np.nan], + [np.nan, 0, 1, 1], + [0, np.nan, 1, 1], + [0, 0, np.nan, 1], + [0, 0, 1, np.nan], + ], +) +def test_box_nan(coords): + assert shapely.box(*coords) is None + + +def test_box_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `ccw` for `box` is deprecated" + ): + shapely.box(0, 0, 1, 1, True) + + +def test_prepare(): + arr = np.array([shapely.points(1, 1), None, shapely.box(0, 0, 1, 1)]) + assert arr[0]._geom_prepared == 0 + assert arr[2]._geom_prepared == 0 + shapely.prepare(arr) + assert arr[0]._geom_prepared != 0 + assert arr[1] is None + assert arr[2]._geom_prepared != 0 + + # preparing again actually does nothing + original = arr[0]._geom_prepared + shapely.prepare(arr) + assert arr[0]._geom_prepared == original + + +def test_destroy_prepared(): + arr = np.array([shapely.points(1, 1), None, shapely.box(0, 0, 1, 1)]) + shapely.prepare(arr) + assert arr[0]._geom_prepared != 0 + assert arr[2]._geom_prepared != 0 + shapely.destroy_prepared(arr) + assert arr[0]._geom_prepared == 0 + assert arr[1] is None + assert arr[2]._geom_prepared == 0 + shapely.destroy_prepared(arr) # does not error + + +@pytest.mark.parametrize("geom_type", [None, GeometryType.MISSING, -1]) +def test_empty_missing(geom_type): + actual = shapely.empty((2,), geom_type=geom_type) + assert shapely.is_missing(actual).all() + + +@pytest.mark.parametrize("geom_type", range(8)) +def test_empty(geom_type): + actual = shapely.empty((2,), geom_type=geom_type) + assert (~shapely.is_missing(actual)).all() + assert shapely.is_empty(actual).all() + assert (shapely.get_type_id(actual) == geom_type).all() diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_creation_indices.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_creation_indices.py new file mode 100644 index 0000000000000000000000000000000000000000..86d7e8625ecb8367c2ed7353b266bf4522eb3089 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_creation_indices.py @@ -0,0 +1,585 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +import shapely +from shapely import LinearRing, Polygon +from shapely.testing import assert_geometries_equal +from shapely.tests.common import empty_point, line_string, linear_ring, point, polygon + +pnts = shapely.points +lstrs = shapely.linestrings +geom_coll = shapely.geometrycollections + + +@pytest.mark.parametrize( + "func", [shapely.points, shapely.linestrings, shapely.linearrings] +) +@pytest.mark.parametrize( + "coordinates", + [ + np.empty((2,)), # not enough dimensions + np.empty((2, 4, 1)), # too many dimensions + np.empty((2, 4)), # wrong inner dimension size + None, + np.full((2, 2), "foo", dtype=object), # wrong type + ], +) +def test_invalid_coordinates(func, coordinates): + with pytest.raises((TypeError, ValueError)): + func(coordinates, indices=[0, 1]) + + +@pytest.mark.parametrize( + "func", + [ + shapely.multipoints, + shapely.multilinestrings, + shapely.multipolygons, + shapely.geometrycollections, + ], +) +@pytest.mark.parametrize( + "geometries", [np.array([1, 2], dtype=np.intp), None, np.array([[point]]), "hello"] +) +def test_invalid_geometries(func, geometries): + with pytest.raises((TypeError, ValueError)): + func(geometries, indices=[0, 1]) + + +@pytest.mark.parametrize( + "func", [shapely.points, shapely.linestrings, shapely.linearrings] +) +@pytest.mark.parametrize("indices", [[point], " hello", [0, 1], [-1]]) +def test_invalid_indices_simple(func, indices): + with pytest.raises((TypeError, ValueError)): + func([[0.2, 0.3]], indices=indices) + + +non_writeable = np.empty(3, dtype=object) +non_writeable.flags.writeable = False + + +@pytest.mark.parametrize( + "func", [shapely.points, shapely.linestrings, shapely.geometrycollections] +) +@pytest.mark.parametrize( + "out", + [ + [None, None, None], # not an ndarray + np.empty(3), # wrong dtype + non_writeable, # not writeable + np.empty((3, 2), dtype=object), # too many dimensions + np.empty((), dtype=object), # too few dimensions + np.empty((2,), dtype=object), # too small + ], +) +def test_invalid_out(func, out): + if func is shapely.points: + x = [[0.2, 0.3], [0.4, 0.5]] + indices = [0, 2] + elif func is shapely.linestrings: + x = [[1, 1], [2, 1], [2, 2], [3, 3], [3, 4], [4, 4]] + indices = [0, 0, 0, 2, 2, 2] + else: + x = [point, line_string] + indices = [0, 2] + with pytest.raises((TypeError, ValueError)): + func(x, indices=indices, out=out) + + +def test_points_invalid(): + # attempt to construct a point with 2 coordinates + with pytest.raises(shapely.GEOSException): + shapely.points([[1, 1], [2, 2]], indices=[0, 0]) + + +def test_points(): + actual = shapely.points( + np.array([[2, 3], [2, 3]], dtype=float), + indices=np.array([0, 1], dtype=np.intp), + ) + assert_geometries_equal(actual, [point, point]) + + +def test_points_no_index_raises(): + with pytest.raises(ValueError): + shapely.points( + np.array([[2, 3], [2, 3]], dtype=float), + indices=np.array([0, 2], dtype=np.intp), + ) + + +@pytest.mark.parametrize( + "indices,expected", + [ + ([0, 1], [point, point, empty_point, None]), + ([0, 3], [point, None, empty_point, point]), + ([2, 3], [None, None, point, point]), + ], +) +def test_points_out(indices, expected): + out = np.empty(4, dtype=object) + out[2] = empty_point + actual = shapely.points( + [[2, 3], [2, 3]], + indices=indices, + out=out, + ) + assert_geometries_equal(out, expected) + assert actual is out + + +@pytest.mark.parametrize( + "coordinates,indices,expected", + [ + ([[1, 1], [2, 2]], [0, 0], [lstrs([[1, 1], [2, 2]])]), + ([[1, 1, 1], [2, 2, 2]], [0, 0], [lstrs([[1, 1, 1], [2, 2, 2]])]), + ( + [[1, 1], [2, 2], [2, 2], [3, 3]], + [0, 0, 1, 1], + [lstrs([[1, 1], [2, 2]]), lstrs([[2, 2], [3, 3]])], + ), + ], +) +def test_linestrings(coordinates, indices, expected): + actual = shapely.linestrings( + np.array(coordinates, dtype=float), indices=np.array(indices, dtype=np.intp) + ) + assert_geometries_equal(actual, expected) + + +def test_linestrings_invalid(): + # attempt to construct linestrings with 1 coordinate + with pytest.raises(shapely.GEOSException): + shapely.linestrings([[1, 1], [2, 2]], indices=[0, 1]) + + +@pytest.mark.parametrize( + "indices,expected", + [ + ([0, 0, 0, 1, 1, 1], [line_string, line_string, empty_point, None]), + ([0, 0, 0, 3, 3, 3], [line_string, None, empty_point, line_string]), + ([2, 2, 2, 3, 3, 3], [None, None, line_string, line_string]), + ], +) +def test_linestrings_out(indices, expected): + out = np.empty(4, dtype=object) + out[2] = empty_point + actual = shapely.linestrings( + [(0, 0), (1, 0), (1, 1), (0, 0), (1, 0), (1, 1)], + indices=indices, + out=out, + ) + assert_geometries_equal(out, expected) + assert actual is out + + +@pytest.mark.parametrize( + "coordinates", + [ + [[1, 1], [1, float("nan")], [2, 2]], + ], +) +def test_linestrings_allow_nan(coordinates): + actual = shapely.linestrings( + np.array(coordinates, dtype=float), + indices=np.zeros(len(coordinates), dtype=np.intp), + ) + assert_array_equal(shapely.get_coordinates(actual), coordinates) + + +@pytest.mark.parametrize( + "coordinates,indices,expected", + [ + ([[1, 1], [1, float("nan")], [2, 2]], [0, 0, 0], [lstrs([[1, 1], [2, 2]])]), + ], +) +def test_linestrings_handle_nan_skip(coordinates, indices, expected): + actual = shapely.linestrings( + np.array(coordinates, dtype=float), + indices=np.array(indices, dtype=np.intp), + handle_nan="skip", + ) + assert_geometries_equal(actual, expected) + + +def test_linestrings_handle_nan_skip_invalid(): + # the NaN makes the linestring too short + with pytest.raises(shapely.GEOSException): + shapely.linestrings( + [[1, 1], [2, float("nan")]], indices=[0, 0], handle_nan="skip" + ) + + +def test_linestrings_handle_nan_skip_only_nan(): + actual = shapely.linestrings( + np.full((3, 2), fill_value=np.nan), indices=[0, 0, 0], handle_nan="skip" + ) + assert actual[0].is_empty + + +def test_linestrings_handle_nan_error(): + with pytest.raises(ValueError, match=".*NaN.*"): + shapely.linestrings( + [[0, 0], [float("nan"), 0], [1, 1]], indices=[0, 0, 0], handle_nan="error" + ) + + +@pytest.mark.parametrize( + "coordinates", [([[1, 1], [2, 1], [2, 2], [1, 1]]), ([[1, 1], [2, 1], [2, 2]])] +) +def test_linearrings(coordinates): + actual = shapely.linearrings( + np.array(coordinates, dtype=np.float64), + indices=np.zeros(len(coordinates), dtype=np.intp), + ) + assert_geometries_equal(actual, shapely.linearrings(coordinates)) + + +@pytest.mark.parametrize( + "coordinates", + [ + ([[1, 1], [1, 1]]), # too short + ([[1, np.nan], [2, 1], [2, 2], [1, 1]]), # starting with nan + ], +) +def test_linearrings_invalid(coordinates): + with pytest.raises((shapely.GEOSException, ValueError)): + shapely.linearrings(coordinates, indices=np.zeros(len(coordinates))) + + +def test_linearrings_unclosed_all_coords_equal(): + actual = shapely.linearrings([(0, 0), (0, 0), (0, 0)], indices=np.zeros(3)) + assert_geometries_equal(actual, LinearRing([(0, 0), (0, 0), (0, 0), (0, 0)])) + + +@pytest.mark.parametrize( + "indices,expected", + [ + ([0, 0, 0, 0, 0], [linear_ring, None, None, empty_point]), + ([1, 1, 1, 1, 1], [None, linear_ring, None, empty_point]), + ([3, 3, 3, 3, 3], [None, None, None, linear_ring]), + ], +) +def test_linearrings_out(indices, expected): + out = np.empty(4, dtype=object) + out[3] = empty_point + actual = shapely.linearrings( + [(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)], + indices=indices, + out=out, + ) + assert_geometries_equal(out, expected) + assert actual is out + + +@pytest.mark.parametrize("dim", [2, 3]) +@pytest.mark.parametrize("order", ["C", "F"]) +def test_linearrings_buffer(dim, order): + coords = np.random.randn(10, 4, dim) + coords1 = np.asarray(coords.reshape(10 * 4, dim), order=order) + indices1 = np.repeat(range(10), 4) + result1 = shapely.linearrings(coords1, indices=indices1) + + # with manual closure -> can directly copy from buffer if C order + coords2 = np.hstack((coords, coords[:, [0], :])) + coords2 = np.asarray(coords2.reshape(10 * 5, dim), order=order) + indices2 = np.repeat(range(10), 5) + result2 = shapely.linearrings(coords2, indices=indices2) + assert_geometries_equal(result1, result2) + + +@pytest.mark.parametrize( + "coordinates", + [ + [[1, 1], [2, 1], [2, float("nan")], [1, 1]], + ], +) +def test_linearrings_allow_nan(coordinates): + actual = shapely.linearrings( + np.array(coordinates, dtype=float), + indices=np.zeros(len(coordinates), dtype=np.intp), + ) + assert_array_equal(shapely.get_coordinates(actual), coordinates) + + +@pytest.mark.parametrize( + "coordinates", + [ + [[1, 1], [2, 1], [2, 2], [2, float("nan")], [1, 1]], + [[1, 1], [2, 1], [2, float("nan")], [2, 2]], + [[1, 1], [2, 1], [2, 2], [1, 1], [2, float("nan")]], + [[2, float("nan")], [1, 1], [2, 1], [2, 2], [1, 1]], + [[1, 1], [2, 1], [2, 2], [2, float("nan")]], + [[2, float("nan")], [1, 1], [2, 1], [2, 2]], + ], +) +def test_linearrings_handle_nan_skip(coordinates): + actual = shapely.linearrings( + np.array(coordinates, dtype=np.float64), + indices=np.zeros(len(coordinates), dtype=np.intp), + handle_nan="skip", + ) + assert_geometries_equal(actual, shapely.linearrings(coordinates, handle_nan="skip")) + + +def test_linearrings_handle_nan_skip_invalid(): + # the NaN makes the linearring too short + with pytest.raises(ValueError): + shapely.linearrings( + [[1, 1], [float("nan"), 1], [1, 1]], indices=[0, 0, 0], handle_nan="skip" + ) + + +def test_linearrings_handle_nan_skip_only_nan(): + actual = shapely.linearrings( + np.full((5, 2), fill_value=np.nan), indices=[0] * 5, handle_nan="skip" + ) + + assert actual[0].is_empty + + +def test_linearrings_handle_nan_error(): + with pytest.raises(ValueError, match=".*NaN.*"): + shapely.linearrings( + [[1, 1], [2, 1], [2, 2], [2, float("nan")], [1, 1]], + indices=[0, 0, 0, 0, 0], + handle_nan="error", + ) + + +hole_1 = shapely.linearrings([(0.2, 0.2), (0.2, 0.4), (0.4, 0.4)]) +hole_2 = shapely.linearrings([(0.6, 0.6), (0.6, 0.8), (0.8, 0.8)]) +poly = shapely.polygons(linear_ring) +poly_empty = Polygon() +poly_hole_1 = shapely.polygons(linear_ring, holes=[hole_1]) +poly_hole_2 = shapely.polygons(linear_ring, holes=[hole_2]) +poly_hole_1_2 = shapely.polygons(linear_ring, holes=[hole_1, hole_2]) + + +@pytest.mark.parametrize( + "rings,indices,expected", + [ + ([linear_ring, linear_ring], [0, 1], [poly, poly]), + ([None, linear_ring], [0, 1], [poly_empty, poly]), + ([None, linear_ring, None, None], [0, 0, 1, 1], [poly, poly_empty]), + ([linear_ring, hole_1, linear_ring], [0, 0, 1], [poly_hole_1, poly]), + ([linear_ring, linear_ring, hole_1], [0, 1, 1], [poly, poly_hole_1]), + ([None, linear_ring, linear_ring, hole_1], [0, 0, 1, 1], [poly, poly_hole_1]), + ([linear_ring, None, linear_ring, hole_1], [0, 0, 1, 1], [poly, poly_hole_1]), + ([linear_ring, None, linear_ring, hole_1], [0, 1, 1, 1], [poly, poly_hole_1]), + ([linear_ring, linear_ring, None, hole_1], [0, 1, 1, 1], [poly, poly_hole_1]), + ([linear_ring, linear_ring, hole_1, None], [0, 1, 1, 1], [poly, poly_hole_1]), + ( + [linear_ring, hole_1, hole_2, linear_ring], + [0, 0, 0, 1], + [poly_hole_1_2, poly], + ), + ( + [linear_ring, hole_1, linear_ring, hole_2], + [0, 0, 1, 1], + [poly_hole_1, poly_hole_2], + ), + ( + [linear_ring, linear_ring, hole_1, hole_2], + [0, 1, 1, 1], + [poly, poly_hole_1_2], + ), + ( + [linear_ring, hole_1, None, hole_2, linear_ring], + [0, 0, 0, 0, 1], + [poly_hole_1_2, poly], + ), + ( + [linear_ring, hole_1, None, linear_ring, hole_2], + [0, 0, 0, 1, 1], + [poly_hole_1, poly_hole_2], + ), + ( + [linear_ring, hole_1, linear_ring, None, hole_2], + [0, 0, 1, 1, 1], + [poly_hole_1, poly_hole_2], + ), + ], +) +def test_polygons(rings, indices, expected): + actual = shapely.polygons( + np.array(rings, dtype=object), indices=np.array(indices, dtype=np.intp) + ) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "indices,expected", + [ + ([0, 1], [poly, poly, empty_point, None]), + ([0, 3], [poly, None, empty_point, poly]), + ([2, 3], [None, None, poly, poly]), + ], +) +def test_polygons_out(indices, expected): + out = np.empty(4, dtype=object) + out[2] = empty_point + actual = shapely.polygons([linear_ring, linear_ring], indices=indices, out=out) + assert_geometries_equal(out, expected) + assert actual is out + + +@pytest.mark.parametrize( + "func", + [ + shapely.polygons, + shapely.multipoints, + shapely.multilinestrings, + shapely.multipolygons, + shapely.geometrycollections, + ], +) +@pytest.mark.parametrize("indices", [np.array([point]), " hello", [0, 1], [-1]]) +def test_invalid_indices_collections(func, indices): + with pytest.raises((TypeError, ValueError)): + func([point], indices=indices) + + +@pytest.mark.parametrize( + "geometries,indices,expected", + [ + ([point, line_string], [0, 0], [geom_coll([point, line_string])]), + ([point, line_string], [0, 1], [geom_coll([point]), geom_coll([line_string])]), + ([point, None], [0, 0], [geom_coll([point])]), + ([point, None], [0, 1], [geom_coll([point]), geom_coll([])]), + ([None, point, None, None], [0, 0, 1, 1], [geom_coll([point]), geom_coll([])]), + ([point, None, line_string], [0, 0, 0], [geom_coll([point, line_string])]), + ], +) +def test_geometrycollections(geometries, indices, expected): + actual = shapely.geometrycollections( + np.array(geometries, dtype=object), indices=indices + ) + assert_geometries_equal(actual, expected) + + +def test_geometrycollections_no_index_raises(): + with pytest.raises(ValueError): + shapely.geometrycollections( + np.array([point, line_string], dtype=object), indices=[0, 2] + ) + + +@pytest.mark.parametrize( + "indices,expected", + [ + ([0, 0], [geom_coll([point, line_string]), None, None, empty_point]), + ([3, 3], [None, None, None, geom_coll([point, line_string])]), + ], +) +def test_geometrycollections_out(indices, expected): + out = np.empty(4, dtype=object) + out[3] = empty_point + actual = shapely.geometrycollections([point, line_string], indices=indices, out=out) + assert_geometries_equal(out, expected) + assert actual is out + + +def test_multipoints(): + actual = shapely.multipoints( + np.array([point], dtype=object), indices=np.zeros(1, dtype=np.intp) + ) + assert_geometries_equal(actual, shapely.multipoints([point])) + + +def test_multilinestrings(): + actual = shapely.multilinestrings( + np.array([line_string], dtype=object), indices=np.zeros(1, dtype=np.intp) + ) + assert_geometries_equal(actual, shapely.multilinestrings([line_string])) + + +def test_multilinearrings(): + actual = shapely.multilinestrings( + np.array([linear_ring], dtype=object), indices=np.zeros(1, dtype=np.intp) + ) + assert_geometries_equal(actual, shapely.multilinestrings([linear_ring])) + + +def test_multipolygons(): + actual = shapely.multipolygons( + np.array([polygon], dtype=object), indices=np.zeros(1, dtype=np.intp) + ) + assert_geometries_equal(actual, shapely.multipolygons([polygon])) + + +@pytest.mark.parametrize( + "geometries,func", + [ + ([point], shapely.polygons), + ([line_string], shapely.polygons), + ([polygon], shapely.polygons), + ([line_string], shapely.multipoints), + ([polygon], shapely.multipoints), + ([point], shapely.multilinestrings), + ([polygon], shapely.multilinestrings), + ([point], shapely.multipolygons), + ([line_string], shapely.multipolygons), + ], +) +def test_incompatible_types(geometries, func): + with pytest.raises(TypeError): + func(geometries, indices=[0]) + + +def test_points_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `points` is deprecated" + ): + shapely.points([[0, 1], [2, 3]], None, None, [0, 1]) + + +def test_linestrings_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `linestrings` is deprecated" + ): + shapely.linestrings([[0, 1], [2, 3], [4, 5], [6, 7]], None, None, [0, 0, 1, 1]) + + +def test_linearrings_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `linearrings` is deprecated" + ): + shapely.linearrings([[0, 1], [1, 1], [1, 0]], None, None, [0, 0, 0]) + + +def test_polygons_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `polygons` is deprecated" + ): + shapely.polygons([linear_ring, linear_ring], None, [0, 1]) + + +def test_multipoints_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `multipoints` is deprecated" + ): + shapely.multipoints([point, point], [0, 1]) + + +def test_multilinestrings_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `multilinestrings` is deprecated" + ): + shapely.multilinestrings([line_string, line_string], [0, 1]) + + +def test_multipolygons_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `multipolygons` is deprecated" + ): + shapely.multipolygons([polygon, polygon], [0, 1]) + + +def test_geometrycollections_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `indices` for `geometrycollections` is deprecated" + ): + shapely.geometrycollections([point, polygon], [0, 1]) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_decorators.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..0ba8ba7182f2fa504351424e7b6e2e4dbde793dc --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_decorators.py @@ -0,0 +1,138 @@ +import pytest +from pytest import WarningsRecorder + +from shapely.decorators import deprecate_positional + + +@deprecate_positional(["b", "c"]) +def func_two(a, b=2, c=3): + return a, b, c + + +@deprecate_positional(["b", "c", "d"]) +def func_three(a, b=1, c=2, d=3): + return a, b, c, d + + +@deprecate_positional(["b", "d"]) +def func_noncontig(a, b=1, c=2, d=3): + return a, b, c, d + + +@deprecate_positional(["b"], category=UserWarning) +def func_custom_category(a, b=1): + return a, b + + +@deprecate_positional(["b"]) +def func_varargs(a, b=1, *args): + return a, b, args + + +@deprecate_positional([]) +def func_no_deprecations(a, b=1): + return a, b + + +def test_all_kwargs_no_warning(recwarn: WarningsRecorder) -> None: + assert func_two(a=10, b=20, c=30) == (10, 20, 30) + assert not recwarn.list + + +def test_only_required_arg_no_warning(recwarn: WarningsRecorder) -> None: + assert func_two(1) == (1, 2, 3) + assert not recwarn.list + + +def test_single_positional_warning() -> None: + with pytest.warns( + DeprecationWarning, match="positional argument `b` for `func_two` is deprecated" + ): + out = func_two(1, 4) + assert out == (1, 4, 3) + + +def test_multiple_positional_warning() -> None: + with pytest.warns( + DeprecationWarning, + match="positional arguments `b` and `c` for `func_two` are deprecated", + ): + out = func_two(1, 4, 5) + assert out == (1, 4, 5) + + +def test_three_positional_warning_oxford_comma() -> None: + with pytest.warns( + DeprecationWarning, + match="positional arguments `b`, `c`, and `d` for `func_three` are deprecated", + ): + out = func_three(1, 2, 3, 4) + assert out == (1, 2, 3, 4) + + +def test_noncontiguous_partial_warning() -> None: + with pytest.warns( + DeprecationWarning, + match="positional argument `b` for `func_noncontig` is deprecated", + ): + out = func_noncontig(1, 2, 3) + assert out == (1, 2, 3, 3) + + +def test_noncontiguous_full_warning() -> None: + with pytest.warns( + DeprecationWarning, + match="positional arguments `b` and `d` for `func_noncontig` are deprecated", + ): + out = func_noncontig(1, 2, 3, 4) + assert out == (1, 2, 3, 4) + + +def test_custom_warning_category() -> None: + with pytest.warns( + UserWarning, + match="positional argument `b` for `func_custom_category` is deprecated", + ): + out = func_custom_category(1, 2) + assert out == (1, 2) + + +def test_func_no_deprecations_never_warns(recwarn: WarningsRecorder) -> None: + out = func_no_deprecations(7, 8) + assert out == (7, 8) + assert not recwarn.list + + +def test_missing_required_arg_no_warning(recwarn: WarningsRecorder) -> None: + with pytest.raises(TypeError): + func_two() # missing required 'a' # type: ignore + assert not recwarn.list + + +def test_unknown_keyword_no_warning(recwarn: WarningsRecorder) -> None: + with pytest.raises(TypeError): + func_two(1, 4, d=5) # unknown keyword 'd' # type: ignore + assert not recwarn.list + + +def test_varargs_behavior_and_deprecation() -> None: + with pytest.warns( + DeprecationWarning, + match="positional argument `b` for `func_varargs` is deprecated", + ): + out = func_varargs(1, 2, 3, 4) + assert out == (1, 2, (3, 4)) + + +def test_varargs_no_warning(recwarn: WarningsRecorder) -> None: + out = func_varargs(1) + assert out == (1, 1, ()) + assert not recwarn.list + + +def test_repeated_warnings() -> None: + with pytest.warns(DeprecationWarning) as record: + func_two(1, 4, 5) + func_two(1, 4, 5) + assert len(record) == 2 + assert str(record[0].message) == str(record[1].message) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_geometry.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..8a255befe04c65c944207d473560c7e0e0fdcdd2 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_geometry.py @@ -0,0 +1,739 @@ +import warnings + +import numpy as np +import pytest + +import shapely +from shapely import LinearRing, LineString, MultiPolygon, Point, Polygon +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + all_types, + empty as empty_geometry_collection, + empty_line_string, + empty_line_string_z, + empty_point, + empty_point_z, + empty_polygon, + equal_geometries_abnormally_yield_unequal, + geometry_collection, + geometry_collection_z, + ignore_invalid, + ignore_warnings, + line_string, + line_string_nan, + line_string_z, + linear_ring, + multi_line_string, + multi_line_string_z, + multi_point, + multi_point_z, + multi_polygon, + multi_polygon_z, + point, + point_m, + point_z, + point_zm, + polygon, + polygon_with_hole, + polygon_with_hole_z, + polygon_z, +) + + +def test_get_num_points(): + actual = shapely.get_num_points(all_types + (None,)).tolist() + assert actual == [0, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + + +def test_get_num_interior_rings(): + actual = shapely.get_num_interior_rings(all_types + (None,)).tolist() + assert actual == [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + + +def test_get_num_geometries(): + actual = shapely.get_num_geometries(all_types + (None,)).tolist() + assert actual == [1, 1, 1, 1, 1, 2, 1, 2, 2, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0] + + +@pytest.mark.parametrize( + "geom", + [ + point, + polygon, + multi_point, + multi_line_string, + multi_polygon, + geometry_collection, + ], +) +def test_get_point_non_linestring(geom): + actual = shapely.get_point(geom, [0, 2, -1]) + assert shapely.is_missing(actual).all() + + +@pytest.mark.parametrize("geom", [line_string, linear_ring]) +def test_get_point(geom): + n = shapely.get_num_points(geom) + actual = shapely.get_point(geom, [0, -n, n, -(n + 1)]) + assert_geometries_equal(actual[0], actual[1]) + assert shapely.is_missing(actual[2:4]).all() + + +@pytest.mark.parametrize( + "geom", + [ + point, + line_string, + linear_ring, + multi_point, + multi_line_string, + multi_polygon, + geometry_collection, + ], +) +def test_get_exterior_ring_non_polygon(geom): + actual = shapely.get_exterior_ring(geom) + assert shapely.is_missing(actual).all() + + +def test_get_exterior_ring(): + actual = shapely.get_exterior_ring([polygon, polygon_with_hole]) + assert (shapely.get_type_id(actual) == shapely.GeometryType.LINEARRING).all() + + +@pytest.mark.parametrize( + "geom", + [ + point, + line_string, + linear_ring, + multi_point, + multi_line_string, + multi_polygon, + geometry_collection, + ], +) +def test_get_interior_ring_non_polygon(geom): + actual = shapely.get_interior_ring(geom, [0, 2, -1]) + assert shapely.is_missing(actual).all() + + +def test_get_interior_ring(): + actual = shapely.get_interior_ring(polygon_with_hole, [0, -1, 1, -2]) + assert_geometries_equal(actual[0], actual[1]) + assert shapely.is_missing(actual[2:4]).all() + + +@pytest.mark.parametrize("geom", [point, line_string, linear_ring, polygon]) +def test_get_geometry_simple(geom): + actual = shapely.get_geometry(geom, [0, -1, 1, -2]) + assert_geometries_equal(actual[0], actual[1]) + assert shapely.is_missing(actual[2:4]).all() + + +@pytest.mark.parametrize( + "geom", [multi_point, multi_line_string, multi_polygon, geometry_collection] +) +def test_get_geometry_collection(geom): + n = shapely.get_num_geometries(geom) + actual = shapely.get_geometry(geom, [0, -n, n, -(n + 1)]) + assert_geometries_equal(actual[0], actual[1]) + assert shapely.is_missing(actual[2:4]).all() + + +def test_get_type_id(): + actual = shapely.get_type_id(all_types + (None,)).tolist() + assert actual == [0, 1, 2, 3, 3, 4, 5, 6, 7, 7, 0, 1, 3, 4, 5, 6, 4, 5, 6, 7, -1] + + +def test_get_dimensions(): + actual = shapely.get_dimensions(all_types + (None,)).tolist() + assert actual == [0, 1, 1, 2, 2, 0, 1, 2, 1, -1, 0, 1, 2, 0, 1, 2, 0, 1, 2, 1, -1] + + +def test_get_coordinate_dimension(): + actual = shapely.get_coordinate_dimension([point, point_z, None]).tolist() + assert actual == [2, 3, -1] + + +def test_get_num_coordinates(): + actual = shapely.get_num_coordinates(all_types + (None,)).tolist() + assert actual == [1, 3, 5, 5, 10, 2, 2, 10, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + + +def test_get_srid(): + """All geometry types have no SRID by default; None returns -1""" + actual = shapely.get_srid(all_types + (None,)).tolist() + assert actual == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1] + + +def test_get_set_srid(): + actual = shapely.set_srid(point, 4326) + assert shapely.get_srid(point) == 0 + assert shapely.get_srid(actual) == 4326 + + +@pytest.mark.parametrize( + "func", + [ + shapely.get_x, + shapely.get_y, + shapely.get_z, + pytest.param( + shapely.get_m, + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + ], +) +@pytest.mark.parametrize( + "geom", + np.array(all_types)[shapely.get_type_id(all_types) != shapely.GeometryType.POINT], +) +def test_get_xyz_no_point(func, geom): + assert np.isnan(func(geom)) + + +def test_get_x(): + assert shapely.get_x([point, point_z]).tolist() == [2.0, 2.0] + + +def test_get_y(): + assert shapely.get_y([point, point_z]).tolist() == [3.0, 3.0] + + +def test_get_z(): + assert shapely.get_z([point_z]).tolist() == [4.0] + + +def test_get_z_2d(): + assert np.isnan(shapely.get_z(point)) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +def test_get_m(): + assert shapely.get_m([point_m, point_zm]).tolist() == [5.0, 5.0] + assert np.isnan(shapely.get_m(point)) + assert np.isnan(shapely.get_m(point_z)) + + +@pytest.mark.parametrize("geom", all_types) +def test_new_from_wkt(geom): + actual = shapely.from_wkt(str(geom)) + if equal_geometries_abnormally_yield_unequal(geom): + # abnormal test + with pytest.raises(AssertionError): + assert_geometries_equal(actual, geom) + else: + # normal test + assert_geometries_equal(actual, geom) + + +def test_adapt_ptr_raises(): + point = Point(2, 2) + with pytest.raises(AttributeError): + point._geom += 1 + + +@pytest.mark.parametrize("geom", all_types) +def test_set_unique(geom): + a = {geom, shapely.transform(geom, lambda x: x)} + assert len(a) == 1 + + +def test_set_nan(): + # Although NaN != NaN, you cannot have multiple "NaN" points in a set + # This is because "NaN" coordinates in a geometry are considered as equal. + with ignore_invalid(): + a = set(shapely.linestrings([[[np.nan, np.nan], [np.nan, np.nan]]] * 10)) + assert len(a) == 1 # same objects: NaN == NaN (as geometry coordinates) + + +def test_set_nan_same_objects(): + # You can't put identical objects in a set. + # x = float("nan"); set([x, x]) also returns a set with 1 element + a = set([line_string_nan] * 10) + assert len(a) == 1 + + +@pytest.mark.parametrize( + "geom", + [ + point, + multi_point, + line_string, + multi_line_string, + polygon, + multi_polygon, + geometry_collection, + empty_point, + empty_line_string, + empty_polygon, + empty_geometry_collection, + np.array([None]), + np.empty_like(np.array([None])), + ], +) +def test_get_parts(geom): + expected_num_parts = shapely.get_num_geometries(geom) + if expected_num_parts == 0: + expected_parts = [] + else: + expected_parts = shapely.get_geometry(geom, range(expected_num_parts)) + + parts = shapely.get_parts(geom) + assert len(parts) == expected_num_parts + assert_geometries_equal(parts, expected_parts) + + +def test_get_parts_array(): + # note: this also verifies that None is handled correctly + # in the mix; internally it returns -1 for count of geometries + geom = np.array([None, empty_line_string, multi_point, point, multi_polygon]) + expected_parts = [] + for g in geom: + for i in range(shapely.get_num_geometries(g)): + expected_parts.append(shapely.get_geometry(g, i)) + + parts = shapely.get_parts(geom) + assert len(parts) == len(expected_parts) + assert_geometries_equal(parts, expected_parts) + + +def test_get_parts_geometry_collection_multi(): + """On the first pass, the individual Multi* geometry objects are returned + from the collection. On the second pass, the individual singular geometry + objects within those are returned. + """ + geom = shapely.geometrycollections([multi_point, multi_line_string, multi_polygon]) + expected_num_parts = shapely.get_num_geometries(geom) + expected_parts = shapely.get_geometry(geom, range(expected_num_parts)) + + parts = shapely.get_parts(geom) + assert len(parts) == expected_num_parts + assert_geometries_equal(parts, expected_parts) + + expected_subparts = [] + for g in np.asarray(expected_parts): + for i in range(shapely.get_num_geometries(g)): + expected_subparts.append(shapely.get_geometry(g, i)) + + subparts = shapely.get_parts(parts) + assert len(subparts) == len(expected_subparts) + assert_geometries_equal(subparts, expected_subparts) + + +def test_get_parts_return_index(): + geom = np.array([multi_point, point, multi_polygon]) + expected_parts = [] + expected_index = [] + for i, g in enumerate(geom): + for j in range(shapely.get_num_geometries(g)): + expected_parts.append(shapely.get_geometry(g, j)) + expected_index.append(i) + + parts, index = shapely.get_parts(geom, return_index=True) + assert len(parts) == len(expected_parts) + assert_geometries_equal(parts, expected_parts) + assert np.array_equal(index, expected_index) + + +@pytest.mark.parametrize( + "geom", + ([[None]], [[empty_point]], [[multi_point]], [[multi_point, multi_line_string]]), +) +def test_get_parts_invalid_dimensions(geom): + """Only 1D inputs are supported""" + with pytest.raises(ValueError, match="Array should be one dimensional"): + shapely.get_parts(geom) + + +@pytest.mark.parametrize("geom", [point, line_string, polygon]) +def test_get_parts_non_multi(geom): + """Non-multipart geometries should be returned identical to inputs""" + assert_geometries_equal(geom, shapely.get_parts(geom)) + + +@pytest.mark.parametrize("geom", [None, [None], []]) +def test_get_parts_None(geom): + assert len(shapely.get_parts(geom)) == 0 + + +@pytest.mark.parametrize("geom", ["foo", ["foo"], 42]) +def test_get_parts_invalid_geometry(geom): + with pytest.raises(TypeError, match="One of the arguments is of incorrect type."): + shapely.get_parts(geom) + + +def test_get_parts_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `return_index` for `get_parts` is deprecated" + ): + shapely.get_parts(multi_point, False) + + +@pytest.mark.parametrize( + "geom", + [ + point, + multi_point, + line_string, + multi_line_string, + polygon, + multi_polygon, + geometry_collection, + empty_point, + empty_line_string, + empty_polygon, + empty_geometry_collection, + None, + ], +) +def test_get_rings(geom): + if (shapely.get_type_id(geom) != shapely.GeometryType.POLYGON) or shapely.is_empty( + geom + ): + rings = shapely.get_rings(geom) + assert len(rings) == 0 + else: + rings = shapely.get_rings(geom) + assert len(rings) == 1 + assert rings[0] == shapely.get_exterior_ring(geom) + + +def test_get_rings_holes(): + rings = shapely.get_rings(polygon_with_hole) + assert len(rings) == 2 + assert rings[0] == shapely.get_exterior_ring(polygon_with_hole) + assert rings[1] == shapely.get_interior_ring(polygon_with_hole, 0) + + +def test_get_rings_return_index(): + geom = np.array([polygon, None, empty_polygon, polygon_with_hole]) + expected_parts = [] + expected_index = [] + for i, g in enumerate(geom): + if g is None or shapely.is_empty(g): + continue + expected_parts.append(shapely.get_exterior_ring(g)) + expected_index.append(i) + for j in range(shapely.get_num_interior_rings(g)): + expected_parts.append(shapely.get_interior_ring(g, j)) + expected_index.append(i) + + parts, index = shapely.get_rings(geom, return_index=True) + assert len(parts) == len(expected_parts) + assert_geometries_equal(parts, expected_parts) + assert np.array_equal(index, expected_index) + + +@pytest.mark.parametrize("geom", [[[None]], [[polygon]]]) +def test_get_rings_invalid_dimensions(geom): + """Only 1D inputs are supported""" + with pytest.raises(ValueError, match="Array should be one dimensional"): + shapely.get_parts(geom) + + +def test_get_rings_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `return_index` for `get_rings` is deprecated" + ): + shapely.get_rings(polygon, False) + + +def test_get_precision(): + geometries = all_types + (point_z, empty_point, empty_line_string, empty_polygon) + # default is 0 + actual = shapely.get_precision(geometries).tolist() + assert actual == [0] * len(geometries) + + geometry = shapely.set_precision(geometries, 1) + actual = shapely.get_precision(geometry).tolist() + assert actual == [1] * len(geometries) + + +def test_get_precision_none(): + assert np.all(np.isnan(shapely.get_precision([None]))) + + +@pytest.mark.parametrize("mode", ("valid_output", "pointwise", "keep_collapsed")) +def test_set_precision(mode): + initial_geometry = Point(0.9, 0.9) + assert shapely.get_precision(initial_geometry) == 0 + + with ignore_warnings((3, 10, 0), UserWarning): + # GEOS < 3.10 emits warning for 'pointwise' + geometry = shapely.set_precision(initial_geometry, 0, mode=mode) + assert shapely.get_precision(geometry) == 0 + assert_geometries_equal(geometry, initial_geometry) + + with ignore_warnings((3, 10, 0), UserWarning): + geometry = shapely.set_precision(initial_geometry, 1, mode=mode) + assert shapely.get_precision(geometry) == 1 + assert_geometries_equal(geometry, Point(1, 1)) + # original should remain unchanged + assert_geometries_equal(initial_geometry, Point(0.9, 0.9)) + + +def test_set_precision_drop_coords(): + # setting precision of 0 will not drop duplicated points in original + geometry = shapely.set_precision(LineString([(0, 0), (0, 0), (0, 1), (1, 1)]), 0) + assert_geometries_equal(geometry, LineString([(0, 0), (0, 0), (0, 1), (1, 1)])) + + # setting precision will remove duplicated points + geometry = shapely.set_precision(geometry, 1) + assert_geometries_equal(geometry, LineString([(0, 0), (0, 1), (1, 1)])) + + +@pytest.mark.parametrize("mode", ("valid_output", "pointwise", "keep_collapsed")) +def test_set_precision_z(mode): + with ignore_warnings((3, 10, 0), UserWarning): + # GEOS < 3.10 emits warning for 'pointwise' + geometry = shapely.set_precision(Point(0.9, 0.9, 0.9), 1, mode=mode) + assert shapely.get_precision(geometry) == 1 + assert_geometries_equal(geometry, Point(1, 1, 0.9)) + + +@pytest.mark.parametrize("mode", ("valid_output", "pointwise", "keep_collapsed")) +def test_set_precision_nan(mode): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") # GEOS emits warnings + actual = shapely.set_precision(line_string_nan, 1, mode=mode) + assert_geometries_equal(actual, line_string_nan) + + +def test_set_precision_none(): + assert shapely.set_precision(None, 0) is None + + +def test_set_precision_grid_size_nan(): + assert shapely.set_precision(Point(0.9, 0.9), np.nan) is None + + +@pytest.mark.parametrize( + "geometry,mode,expected", + [ + ( + Polygon([(2, 2), (4, 2), (3.2, 3), (4, 4), (2, 4), (2.8, 3), (2, 2)]), + "valid_output", + MultiPolygon( + [ + Polygon([(4, 2), (2, 2), (3, 3), (4, 2)]), + Polygon([(2, 4), (4, 4), (3, 3), (2, 4)]), + ] + ), + ), + pytest.param( + Polygon([(2, 2), (4, 2), (3.2, 3), (4, 4), (2, 4), (2.8, 3), (2, 2)]), + "pointwise", + Polygon([(2, 2), (4, 2), (3, 3), (4, 4), (2, 4), (3, 3), (2, 2)]), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), + reason="pointwise does not work pre-GEOS 3.10", + ), + ), + ( + Polygon([(2, 2), (4, 2), (3.2, 3), (4, 4), (2, 4), (2.8, 3), (2, 2)]), + "keep_collapsed", + MultiPolygon( + [ + Polygon([(4, 2), (2, 2), (3, 3), (4, 2)]), + Polygon([(2, 4), (4, 4), (3, 3), (2, 4)]), + ] + ), + ), + (LineString([(0, 0), (0.1, 0.1)]), "valid_output", LineString()), + pytest.param( + LineString([(0, 0), (0.1, 0.1)]), + "pointwise", + LineString([(0, 0), (0, 0)]), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), + reason="pointwise does not work pre-GEOS 3.10", + ), + ), + ( + LineString([(0, 0), (0.1, 0.1)]), + "keep_collapsed", + LineString([(0, 0), (0, 0)]), + ), + pytest.param( + LinearRing([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "valid_output", + LinearRing(), + marks=pytest.mark.skipif( + shapely.geos_version == (3, 10, 0), reason="Segfaults on GEOS 3.10.0" + ), + ), + pytest.param( + LinearRing([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "pointwise", + LinearRing([(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), + reason="pointwise does not work pre-GEOS 3.10", + ), + ), + pytest.param( + LinearRing([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "keep_collapsed", + # See https://trac.osgeo.org/geos/ticket/1135#comment:5 + LineString([(0, 0), (0, 0), (0, 0)]), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), + reason="this collapsed into an invalid linearring pre-GEOS 3.10", + ), + ), + ( + Polygon([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "valid_output", + Polygon(), + ), + pytest.param( + Polygon([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "pointwise", + Polygon([(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), + reason="pointwise does not work pre-GEOS 3.10", + ), + ), + ( + Polygon([(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1), (0, 0)]), + "keep_collapsed", + Polygon(), + ), + ], +) +def test_set_precision_collapse(geometry, mode, expected): + """Lines and polygons collapse to empty geometries if vertices are too close""" + actual = shapely.set_precision(geometry, 1, mode=mode) + assert_geometries_equal( + # force to 2D because of various dimension issues; GEOS GH-1152 + shapely.force_2d(actual), + expected, + normalize=shapely.geos_version == (3, 9, 0), + ) + + +def test_set_precision_intersection(): + """Operations should use the most precise precision grid size of the inputs""" + + box1 = shapely.normalize(shapely.box(0, 0, 0.9, 0.9)) + box2 = shapely.normalize(shapely.box(0.75, 0, 1.75, 0.75)) + + assert shapely.get_precision(shapely.intersection(box1, box2)) == 0 + + # GEOS will use and keep the most precise precision grid size + box1 = shapely.set_precision(box1, 0.5) + box2 = shapely.set_precision(box2, 1) + out = shapely.intersection(box1, box2) + assert shapely.get_precision(out) == 0.5 + assert_geometries_equal(out, LineString([(1, 1), (1, 0)])) + + +@pytest.mark.parametrize("preserve_topology", [False, True]) +def set_precision_preserve_topology(preserve_topology): + # the preserve_topology kwarg is deprecated (ignored) + with pytest.warns(UserWarning): + actual = shapely.set_precision( + LineString([(0, 0), (0.1, 0.1)]), + 1.0, + preserve_topology=preserve_topology, + ) + assert_geometries_equal(shapely.force_2d(actual), LineString()) + + +@pytest.mark.skipif(shapely.geos_version >= (3, 10, 0), reason="GEOS >= 3.10") +def set_precision_pointwise_pre_310(): + # using 'pointwise' emits a warning + with pytest.warns(UserWarning): + actual = shapely.set_precision( + LineString([(0, 0), (0.1, 0.1)]), + 1.0, + mode="pointwise", + ) + assert_geometries_equal(shapely.force_2d(actual), LineString()) + + +@pytest.mark.parametrize("flags", [np.array([0, 1]), 4, "foo"]) +def set_precision_illegal_flags(flags): + # the preserve_topology kwarg is deprecated (ignored) + with pytest.raises((ValueError, TypeError)): + shapely.lib.set_precision(line_string, 1.0, flags) + + +def test_empty(): + """Compatibility with empty_like, see GH373""" + g = np.empty_like(np.array([None, None])) + assert shapely.is_missing(g).all() + + +# corresponding to geometry_collection_z: +geometry_collection_2 = shapely.geometrycollections([point, line_string]) + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point), + (point_z, point), + (empty_point, empty_point), + (empty_point_z, empty_point), + (line_string, line_string), + (line_string_z, line_string), + (empty_line_string, empty_line_string), + (empty_line_string_z, empty_line_string), + (polygon, polygon), + (polygon_z, polygon), + (polygon_with_hole, polygon_with_hole), + (polygon_with_hole_z, polygon_with_hole), + (multi_point, multi_point), + (multi_point_z, multi_point), + (multi_line_string, multi_line_string), + (multi_line_string_z, multi_line_string), + (multi_polygon, multi_polygon), + (multi_polygon_z, multi_polygon), + (geometry_collection_2, geometry_collection_2), + (geometry_collection_z, geometry_collection_2), + ], +) +def test_force_2d(geom, expected): + actual = shapely.force_2d(geom) + assert shapely.get_coordinate_dimension(actual) == 2 + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, point_z), + (point_z, point_z), + (empty_point, empty_point_z), + (empty_point_z, empty_point_z), + (line_string, line_string_z), + (line_string_z, line_string_z), + (empty_line_string, empty_line_string_z), + (empty_line_string_z, empty_line_string_z), + (polygon, polygon_z), + (polygon_z, polygon_z), + (polygon_with_hole, polygon_with_hole_z), + (polygon_with_hole_z, polygon_with_hole_z), + (multi_point, multi_point_z), + (multi_point_z, multi_point_z), + (multi_line_string, multi_line_string_z), + (multi_line_string_z, multi_line_string_z), + (multi_polygon, multi_polygon_z), + (multi_polygon_z, multi_polygon_z), + (geometry_collection_2, geometry_collection_z), + (geometry_collection_z, geometry_collection_z), + ], +) +def test_force_3d(geom, expected): + actual = shapely.force_3d(geom, z=4) + assert shapely.get_coordinate_dimension(actual) == 3 + assert_geometries_equal(actual, expected) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_io.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..f41d61e7efbbc698549158d16d2fef9c9b6fa720 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_io.py @@ -0,0 +1,1351 @@ +import json +import pickle +import struct +import warnings +from contextlib import nullcontext + +import numpy as np +import pytest + +import shapely +from shapely import ( + GeometryCollection, + GEOSException, + LinearRing, + LineString, + MultiLineString, + MultiPoint, + MultiPolygon, + Point, + Polygon, +) +from shapely.errors import UnsupportedGEOSVersionError +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + all_types, + all_types_m, + all_types_z, + all_types_zm, + empty_point, + empty_point_m, + empty_point_z, + empty_point_zm, + equal_geometries_abnormally_yield_unequal, + multi_point_empty, + multi_point_empty_m, + multi_point_empty_z, + multi_point_empty_zm, + point, + point_m, + point_z, + point_zm, + polygon_z, +) + +EWKBZ = 0x80000000 +EWKBM = 0x40000000 +EWKBZM = EWKBZ | EWKBM +ISOWKBZ = 1000 +ISOWKBM = 2000 +ISOWKBZM = ISOWKBZ + ISOWKBM +POINT11_WKB = struct.pack("1 elements"), + ("LINESTRING (0 0)", "warn", Warning, "must contain 0 or >1 elements"), + ("NOT A WKT STRING", "ignore", None, None), + ("NOT A WKT STRING", "warn", Warning, "Unknown type: 'NOT'"), + ("POLYGON ((0 0, 0 0))", "ignore", None, None), + ("POLYGON ((0 0, 0 0))", "raise", GEOSException, "Invalid number of points"), + ("POLYGON ((0 0, 0 0))", "warn", Warning, "Invalid number of points"), + ], +) +def test_from_wkt_on_invalid(wkt, on_invalid, error, message): + if on_invalid == "warn": + handler = pytest.warns(error, match=message) + elif on_invalid == "raise": + handler = pytest.raises(error, match=message) + elif on_invalid == "ignore": + handler = nullcontext() + else: + handler = pytest.raises(error, match=message) + + with handler: + result = shapely.from_wkt(wkt, on_invalid=on_invalid) + assert result is None + + +@pytest.mark.skipif( + shapely.geos_version < (3, 11, 0), + reason="on_invalid='fix' not supported with GEOS < 3.11", +) +@pytest.mark.parametrize( + "wkt, expected_wkt", + [ + ("", None), + ("LINESTRING (0 0)", None), + ("NOT A WKT STRING", None), + ("POLYGON ((0 0, 0 0))", None), + ("POLYGON ((0 0, 1 1, 0 1))", "POLYGON ((0 0, 1 1, 0 1, 0 0))"), + ("POLYGON ((0 0, 1 1))", "POLYGON ((0 0, 1 1, 0 0))"), + ("MULTIPOLYGON (((5 5, 6 6, 6 5, 5 5)), ((0 0, 0 0)))", None), + ( + "MULTIPOLYGON (((5 5, 6 6, 6 5, 5 5)), ((0 0, 1 1)))", + "MULTIPOLYGON (((5 5, 6 6, 6 5, 5 5)), ((0 0, 1 1, 0 0)))", + ), + ( + "GEOMETRYCOLLECTION (POLYGON ((5 5, 6 6, 6 5, 5 5)), POLYGON ((0 0, 0 0)))", + None, + ), + ], +) +def test_from_wkt_on_invalid_fix(wkt, expected_wkt): + """Tests for on_invalid="fix". + + Geometries that cannot be fixed are returned as None. + """ + geom = shapely.from_wkt(wkt, on_invalid="fix") + assert shapely.to_wkt(geom) == expected_wkt + + +@pytest.mark.skipif( + shapely.geos_version >= (3, 11, 0), + reason="on_invalid='fix' is supported with GEOS >= 3.11", +) +def test_from_wkt_on_invalid_fix_unsupported_geos(): + """on_invalid="fix" not supported with GEOS < 3.11""" + with pytest.raises( + ValueError, match="on_invalid='fix' only supported for GEOS >= 3.11" + ): + _ = shapely.from_wkt("", on_invalid="fix") + + +@pytest.mark.parametrize("geom", all_types) +def test_from_wkt_all_types(geom): + wkt = shapely.to_wkt(geom) + actual = shapely.from_wkt(wkt) + + if equal_geometries_abnormally_yield_unequal(geom): + # check abnormal test + with pytest.raises(AssertionError): + assert_geometries_equal(actual, geom) + else: + # normal test + assert_geometries_equal(actual, geom) + + +@pytest.mark.parametrize( + "wkt", + ("POINT EMPTY", "LINESTRING EMPTY", "POLYGON EMPTY", "GEOMETRYCOLLECTION EMPTY"), +) +def test_from_wkt_empty(wkt): + geom = shapely.from_wkt(wkt) + assert shapely.is_geometry(geom).all() + assert shapely.is_empty(geom).all() + assert shapely.to_wkt(geom) == wkt + + +# WKT from https://github.com/libgeos/geos/blob/main/tests/unit/io/WKBReaderTest.cpp +@pytest.mark.parametrize( + "wkt", + ( + "CIRCULARSTRING(1 3,2 4,3 1)", + "COMPOUNDCURVE(CIRCULARSTRING(1 3,2 4,3 1),(3 1,0 0))", + "CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING(0 0,2 0,2 1,2 3,4 3),(4 3,4 5,1 4,0 0)),CIRCULARSTRING(1.7 1,1.4 0.4,1.6 0.4,1.6 0.5,1.7 1))", # noqa: E501 + "MULTICURVE((0 0,5 5),COMPOUNDCURVE((-1 -1,0 0),CIRCULARSTRING(0 0,1 1,2 0)),CIRCULARSTRING(4 0,4 4,8 4))", # noqa: E501 + "MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0,4 0,4 4,0 4,0 0),(1 1,3 3,3 1,1 1)),((10 10,14 12,11 10,10 10),(11 11,11.5 11,11 11.5,11 11)))", # noqa: E501 + ), +) +def test_from_wkt_nonlinear_unsupported(wkt): + if shapely.geos_version >= (3, 13, 0): + with pytest.raises( + NotImplementedError, + match="Nonlinear geometry types are not currently supported", + ): + shapely.from_wkt(wkt) + + else: + # prior to GEOS 3.13 nonlinear types were rejected by GEOS on read from WKT + with pytest.raises(shapely.errors.GEOSException, match="Unknown type"): + shapely.from_wkt(wkt) + + +def test_from_wkb(): + expected = shapely.points(1, 1) + actual = shapely.from_wkb(POINT11_WKB) + assert_geometries_equal(actual, expected) + + +def test_from_wkb_hex(): + # HEX form + expected = shapely.points(1, 1) + actual = shapely.from_wkb("0101000000000000000000F03F000000000000F03F") + assert_geometries_equal(actual, expected) + actual = shapely.from_wkb(b"0101000000000000000000F03F000000000000F03F") + assert_geometries_equal(actual, expected) + + +def test_from_wkb_none(): + # None propagates + assert shapely.from_wkb(None) is None + + +@pytest.mark.parametrize( + "wkb, on_invalid, error, message", + [ + (1, "raise", TypeError, "Expected bytes or string, got int"), + ("", "ignore", None, None), + ("", "raise", GEOSException, "Unexpected EOF parsing WKB"), + ("", "warn", Warning, "Unexpected EOF parsing WKB"), + ("", "unsupported_option", ValueError, "not a valid option"), + (b"\x01\x01\x00\x00\x00\x00", "ignore", None, None), + (b"\x01\x01\x00\x00\x00\x00", "raise", GEOSException, "ParseException"), + (b"\x01\x01\x00\x00\x00\x00", "warn", Warning, "ParseException"), + (INVALID_WKB, "ignore", None, None), + ( + INVALID_WKB, + "raise", + GEOSException, + "Points of LinearRing do not form a closed linestring", + ), + ( + INVALID_WKB, + "warn", + Warning, + "Points of LinearRing do not form a closed linestring", + ), + ], +) +def test_from_wkb_on_invalid(wkb, on_invalid, error, message): + if on_invalid == "warn": + handler = pytest.warns(error, match=message) + elif on_invalid == "raise": + handler = pytest.raises(error, match=message) + elif on_invalid == "ignore": + handler = nullcontext() + else: + handler = pytest.raises(error, match=message) + + with handler: + result = shapely.from_wkb(wkb, on_invalid=on_invalid) + assert result is None + + +@pytest.mark.skipif( + shapely.geos_version < (3, 11, 0), + reason="on_invalid='fix' not supported with GEOS < 3.11", +) +@pytest.mark.parametrize( + "wkb, expected_wkt", + [ + (b"", None), + (b"\x01\x01\x00\x00\x00\x00", None), + ( + INVALID_WKB, + "POLYGON ((1421568.7761 1924750.2852, 1421564.1314 1924752.2408, 1421568.7761 1924750.2852))", # noqa: E501 + ), + ], +) +def test_from_wkb_on_invalid_fix(wkb, expected_wkt): + """Tests for on_invalid="fix". + + Geometries that cannot be fixed are returned as None. + """ + geom = shapely.from_wkb(wkb, on_invalid="fix") + assert shapely.to_wkt(geom) == expected_wkt + + +@pytest.mark.skipif( + shapely.geos_version >= (3, 11, 0), + reason="on_invalid='fix' is supported with GEOS >= 3.11", +) +def test_from_wkb_on_invalid_fix_unsupported_geos(): + """on_invalid="fix" not supported with GEOS < 3.11""" + with pytest.raises( + ValueError, match="on_invalid='fix' only supported for GEOS >= 3.11" + ): + _ = shapely.from_wkb(b"", on_invalid="fix") + + +@pytest.mark.parametrize("geom", all_types) +@pytest.mark.parametrize("use_hex", [False, True]) +@pytest.mark.parametrize("byte_order", [0, 1]) +def test_from_wkb_all_types(geom, use_hex, byte_order): + if shapely.get_type_id(geom) == shapely.GeometryType.LINEARRING: + pytest.skip("Linearrings are not preserved in WKB") + wkb = shapely.to_wkb(geom, hex=use_hex, byte_order=byte_order) + actual = shapely.from_wkb(wkb) + assert_geometries_equal(actual, geom) + + +@pytest.mark.parametrize("geom", all_types_z) +@pytest.mark.parametrize("use_hex", [False, True]) +@pytest.mark.parametrize("byte_order", [0, 1]) +def test_from_wkb_all_types_z(geom, use_hex, byte_order): + if shapely.get_type_id(geom) == shapely.GeometryType.LINEARRING: + pytest.skip("Linearrings are not preserved in WKB") + wkb = shapely.to_wkb(geom, hex=use_hex, byte_order=byte_order) + actual = shapely.from_wkb(wkb) + assert_geometries_equal(actual, geom) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geom", all_types_m) +@pytest.mark.parametrize("use_hex", [False, True]) +@pytest.mark.parametrize("byte_order", [0, 1]) +def test_from_wkb_all_types_m(geom, use_hex, byte_order): + if shapely.get_type_id(geom) == shapely.GeometryType.LINEARRING: + pytest.skip("Linearrings are not preserved in WKB") + wkb = shapely.to_wkb(geom, hex=use_hex, byte_order=byte_order) + actual = shapely.from_wkb(wkb) + assert_geometries_equal(actual, geom) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geom", all_types_zm) +@pytest.mark.parametrize("use_hex", [False, True]) +@pytest.mark.parametrize("byte_order", [0, 1]) +def test_from_wkb_all_types_zm(geom, use_hex, byte_order): + if shapely.get_type_id(geom) == shapely.GeometryType.LINEARRING: + pytest.skip("Linearrings are not preserved in WKB") + wkb = shapely.to_wkb(geom, hex=use_hex, byte_order=byte_order) + actual = shapely.from_wkb(wkb) + assert_geometries_equal(actual, geom) + + +@pytest.mark.parametrize( + "geom", + (Point(), LineString(), Polygon(), GeometryCollection()), +) +def test_from_wkb_empty(geom): + wkb = shapely.to_wkb(geom) + geom = shapely.from_wkb(wkb) + assert shapely.is_geometry(geom).all() + assert shapely.is_empty(geom).all() + assert shapely.to_wkb(geom) == wkb + + +# WKB from https://github.com/libgeos/geos/blob/main/tests/unit/io/WKBReaderTest.cpp +@pytest.mark.parametrize( + "wkb", + ( + # "CIRCULARSTRING(1 3,2 4,3 1)", + "010800000003000000000000000000F03F0000000000000840000000000000004000000000000010400000000000000840000000000000F03F", + # "COMPOUNDCURVE(CIRCULARSTRING(1 3,2 4,3 1),(3 1,0 0))", + "01090000200E16000002000000010800000003000000000000000000F03F0000000000000840000000000000004000000000000010400000000000000840000000000000F03F0102000000020000000000000000000840000000000000F03F00000000000000000000000000000000", + # "CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING(0 0,2 0,2 1,2 3,4 3),(4 3,4 5,1 4,0 0)),CIRCULARSTRING(1.7 1,1.4 0.4,1.6 0.4,1.6 0.5,1.7 1))", # noqa: E501 + "010A0000200E1600000200000001090000000200000001080000000500000000000000000000000000000000000000000000000000004000000000000000000000000000000040000000000000F03F00000000000000400000000000000840000000000000104000000000000008400102000000040000000000000000001040000000000000084000000000000010400000000000001440000000000000F03F000000000000104000000000000000000000000000000000010800000005000000333333333333FB3F000000000000F03F666666666666F63F9A9999999999D93F9A9999999999F93F9A9999999999D93F9A9999999999F93F000000000000E03F333333333333FB3F000000000000F03F", + # "MULTICURVE((0 0,5 5),COMPOUNDCURVE((-1 -1,0 0),CIRCULARSTRING(0 0,1 1,2 0)),CIRCULARSTRING(4 0,4 4,8 4))", # noqa: E501 + "010B000000030000000102000000020000000000000000000000000000000000000000000000000014400000000000001440010900000002000000010200000002000000000000000000F0BF000000000000F0BF0000000000000000000000000000000001080000000300000000000000000000000000000000000000000000000000F03F000000000000F03F00000000000000400000000000000000010800000003000000000000000000104000000000000000000000000000001040000000000000104000000000000020400000000000001040", + # "MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0,4 0,4 4,0 4,0 0),(1 1,3 3,3 1,1 1)),((10 10,14 12,11 10,10 10),(11 11,11.5 11,11 11.5,11 11)))", # noqa: E501 + "010C00000002000000010A000000020000000108000000050000000000000000000000000000000000000000000000000010400000000000000000000000000000104000000000000010400000000000000000000000000000104000000000000000000000000000000000010200000004000000000000000000F03F000000000000F03F000000000000084000000000000008400000000000000840000000000000F03F000000000000F03F000000000000F03F01030000000200000004000000000000000000244000000000000024400000000000002C40000000000000284000000000000026400000000000002440000000000000244000000000000024400400000000000000000026400000000000002640000000000000274000000000000026400000000000002640000000000000274000000000000026400000000000002640", + ), +) +def test_from_wkb_nonlinear_unsupported(wkb): + if shapely.geos_version >= (3, 13, 0): + with pytest.raises( + NotImplementedError, + match="Nonlinear geometry types are not currently supported", + ): + shapely.from_wkb(wkb) + + else: + # prior to GEOS 3.13 nonlinear types were rejected by GEOS on read from WKB + with pytest.raises(shapely.errors.GEOSException, match="Unknown WKB type"): + shapely.from_wkb(wkb) + + +def test_to_wkt(): + point = shapely.points(1, 1) + actual = shapely.to_wkt(point) + assert actual == "POINT (1 1)" + + actual = shapely.to_wkt(point, trim=False) + assert actual == "POINT (1.000000 1.000000)" + + actual = shapely.to_wkt(point, rounding_precision=3, trim=False) + assert actual == "POINT (1.000 1.000)" + + +def test_to_wkt_z(): + point = shapely.points(1, 2, 3) + + assert shapely.to_wkt(point) == "POINT Z (1 2 3)" + assert shapely.to_wkt(point, output_dimension=2) == "POINT (1 2)" + assert shapely.to_wkt(point, output_dimension=3) == "POINT Z (1 2 3)" + assert shapely.to_wkt(point, old_3d=True) == "POINT (1 2 3)" + + if shapely.geos_version >= (3, 12, 0): + assert shapely.to_wkt(point, output_dimension=4) == "POINT Z (1 2 3)" + + +def test_to_wkt_m(): + point = shapely.from_wkt("POINT M (1 2 4)") + + assert shapely.to_wkt(point, output_dimension=2) == "POINT (1 2)" + + if shapely.geos_version < (3, 12, 0): + # previous behavior was to incorrectly parse M as Z + assert shapely.to_wkt(point) == "POINT Z (1 2 4)" + assert shapely.to_wkt(point, output_dimension=3) == "POINT Z (1 2 4)" + assert shapely.to_wkt(point, old_3d=True) == "POINT (1 2 4)" + else: + assert shapely.to_wkt(point) == "POINT M (1 2 4)" + assert shapely.to_wkt(point, output_dimension=3) == "POINT M (1 2 4)" + assert shapely.to_wkt(point, output_dimension=4) == "POINT M (1 2 4)" + assert shapely.to_wkt(point, old_3d=True) == "POINT M (1 2 4)" + + +def test_to_wkt_zm(): + point = shapely.from_wkt("POINT ZM (1 2 3 4)") + + assert shapely.to_wkt(point, output_dimension=2) == "POINT (1 2)" + assert shapely.to_wkt(point, output_dimension=3) == "POINT Z (1 2 3)" + + if shapely.geos_version < (3, 12, 0): + # previous behavior was to parse and ignore M + assert shapely.to_wkt(point) == "POINT Z (1 2 3)" + assert shapely.to_wkt(point, old_3d=True) == "POINT (1 2 3)" + else: + assert shapely.to_wkt(point) == "POINT ZM (1 2 3 4)" + assert shapely.to_wkt(point, output_dimension=4) == "POINT ZM (1 2 3 4)" + assert shapely.to_wkt(point, old_3d=True) == "POINT (1 2 3 4)" + + +def test_to_wkt_none(): + # None propagates + assert shapely.to_wkt(None) is None + + +def test_to_wkt_array_with_empty_z(): + # See GH-2004 + empty_wkt = ["POINT Z EMPTY", None, "POLYGON Z EMPTY"] + empty_geoms = shapely.from_wkt(empty_wkt) + assert list(shapely.to_wkt(empty_geoms)) == empty_wkt + + +def test_to_wkt_exceptions(): + with pytest.raises(TypeError): + shapely.to_wkt(1) + + with pytest.raises(shapely.GEOSException): + shapely.to_wkt(point, output_dimension=5) + + +def test_to_wkt_point_empty(): + assert shapely.to_wkt(empty_point) == "POINT EMPTY" + + +@pytest.mark.parametrize( + "wkt", + [ + "POINT Z EMPTY", + "LINESTRING Z EMPTY", + "LINEARRING Z EMPTY", + "POLYGON Z EMPTY", + ], +) +def test_to_wkt_empty_z(wkt): + assert shapely.to_wkt(shapely.from_wkt(wkt)) == wkt + + +def test_to_wkt_geometrycollection_with_point_empty(): + collection = shapely.geometrycollections([empty_point, point]) + # do not check the full value as some GEOS versions give + # GEOMETRYCOLLECTION Z (...) and others give GEOMETRYCOLLECTION (...) + assert shapely.to_wkt(collection).endswith("(POINT EMPTY, POINT (2 3))") + + +def test_to_wkt_multipoint_with_point_empty(): + geom = shapely.multipoints([empty_point, point]) + if shapely.geos_version >= (3, 12, 0): + expected = "MULTIPOINT (EMPTY, (2 3))" + else: + # invalid WKT form + expected = "MULTIPOINT (EMPTY, 2 3)" + assert shapely.to_wkt(geom) == expected + + +@pytest.mark.parametrize("geom", [Point(1e100, 0), Point(0, 1e100)]) +def test_to_wkt_large_float_ok(geom): + # https://github.com/shapely/shapely/issues/1903 + shapely.to_wkt(geom) + assert "Exception in WKT writer" not in repr(geom) + + +@pytest.mark.parametrize("geom", [Point(1e101, 0), Point(0, 1e101)]) +def test_to_wkt_large_float(geom): + if shapely.geos_version >= (3, 13, 0): + # round-trip WKT + assert geom.equals(shapely.from_wkt(shapely.to_wkt(geom))) + else: + # https://github.com/shapely/shapely/issues/1903 + with pytest.raises( + ValueError, match="WKT output of coordinates greater than.*" + ): + shapely.to_wkt(geom) + assert "Exception in WKT writer" in repr(geom) + + +@pytest.mark.parametrize( + "geom", + [ + # We implemented our own "GetZMax", so go through all geometry types: + Point(0, 0, 1e101), + LineString([(0, 0, 0), (0, 0, 1e101)]), + LinearRing([(0, 0, 0), (0, 1, 0), (1, 0, 1e101), (0, 0, 0)]), + Polygon([(0, 0, 0), (0, 1, 0), (1, 0, 1e101), (0, 0, 0)]), + Polygon( + [(0, 0, 0), (0, 10, 0), (10, 0, 0), (0, 0, 0)], + [[(0, 0, 0), (0, 1, 0), (1, 0, 1e101), (0, 0, 0)]], + ), + MultiPoint([(0, 0, 0), (0, 0, 1e101)]), + MultiLineString( + [LineString([(0, 0, 0), (0, 1, 0)]), LineString([(0, 0, 0), (0, 1, 1e101)])] + ), + MultiPolygon( + [polygon_z, Polygon([(0, 0, 0), (0, 1, 0), (1, 0, 1e101), (0, 0, 0)])] + ), + GeometryCollection([point_z, Point(0, 0, 1e101)]), + GeometryCollection([GeometryCollection([Point(0, 0, 1e101)])]), + LineString([(0, 0, np.nan), (0, 0, 1e101)]), + Polygon([(0, 0, np.nan), (0, 1, 0), (1, 0, 1e101), (0, 0, 0)]), + GeometryCollection([Point(0, 0), Point(0, 0, 1e101)]), + ], +) +def test_to_wkt_large_float_3d_no_crash(geom): + # https://github.com/shapely/shapely/issues/1903 + # just test if there is a crash (detailed behaviour differs per GEOS version) + try: + shapely.to_wkt(geom) + except ValueError as e: + assert str(e).startswith("WKT output of coordinates greater than") + repr(geom) + + +def test_to_wkt_large_float_skip_z(): + # https://github.com/shapely/shapely/issues/1903 + assert shapely.to_wkt(Point(0, 0, 1e101), output_dimension=2) == "POINT (0 0)" + + +def test_to_wkt_large_float_no_trim(): + # https://github.com/shapely/shapely/issues/1903 + # don't test the exact number, it is ridiculously large and probably platform + # dependent + assert shapely.to_wkt(Point(1e101, 0), trim=False).startswith("POINT (") + + +def test_repr(): + assert repr(point) == "" + assert repr(point_z) == "" + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +def test_repr_m(): + assert repr(point_m) == "" + assert repr(point_zm) == "" + + +def test_repr_max_length(): + # the repr is limited to 80 characters + geom = shapely.linestrings(np.arange(1000), np.arange(1000)) + representation = repr(geom) + assert len(representation) == 80 + assert representation.endswith("...>") + + +def test_repr_point_z_empty(): + assert repr(empty_point_z) == "" + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +def test_repr_point_m_empty(): + assert repr(empty_point_m) == "" + assert repr(empty_point_zm) == "" + + +def test_to_wkb(): + point = shapely.points(1, 1) + actual = shapely.to_wkb(point, byte_order=1) + assert actual == POINT11_WKB + + +def test_to_wkb_hex(): + point = shapely.points(1, 1) + actual = shapely.to_wkb(point, hex=True, byte_order=1) + le = "01" + point_type = "01000000" + coord = "000000000000F03F" # 1.0 as double (LE) + assert actual == le + point_type + 2 * coord + + +def test_to_wkb_z(): + point = shapely.points(1, 2, 3) + + expected_wkb = struct.pack("= (3, 12, 0): + assert shapely.to_wkb(point, output_dimension=4, byte_order=1) == expected_wkb_z + + +def test_to_wkb_m(): + # POINT M (1 2 4) + point = shapely.from_wkb(struct.pack("= (3, 12, 0): + assert shapely.to_wkb(point, output_dimension=4, byte_order=1) == expected_wkb_m + + +def test_to_wkb_zm(): + # POINT ZM (1 2 3 4) + point = shapely.from_wkb(struct.pack("= (3, 12, 0): + assert ( + shapely.to_wkb(point, output_dimension=4, byte_order=1) == expected_wkb_zm + ) + + +def test_to_wkb_none(): + # None propagates + assert shapely.to_wkb(None) is None + + +def test_to_wkb_exceptions(): + with pytest.raises(TypeError): + shapely.to_wkb(1) + + with pytest.raises(shapely.GEOSException): + shapely.to_wkb(point, output_dimension=5) + + with pytest.raises(ValueError): + shapely.to_wkb(point, flavor="other") + + +def test_to_wkb_byte_order(): + point = shapely.points(1.0, 1.0) + be = b"\x00" + le = b"\x01" + point_type = b"\x01\x00\x00\x00" # 1 as 32-bit uint (LE) + coord = b"\x00\x00\x00\x00\x00\x00\xf0?" # 1.0 as double (LE) + + assert shapely.to_wkb(point, byte_order=1) == le + point_type + 2 * coord + assert ( + shapely.to_wkb(point, byte_order=0) == be + point_type[::-1] + 2 * coord[::-1] + ) + + +def test_to_wkb_srid(): + # hex representation of POINT (0 0) with SRID=4 + ewkb = "01010000200400000000000000000000000000000000000000" + wkb = "010100000000000000000000000000000000000000" + + actual = shapely.from_wkb(ewkb) + assert shapely.to_wkt(actual, trim=True) == "POINT (0 0)" + + assert shapely.to_wkb(actual, hex=True, byte_order=1) == wkb + assert shapely.to_wkb(actual, hex=True, include_srid=True, byte_order=1) == ewkb + + point = shapely.points(1, 1) + point_with_srid = shapely.set_srid(point, np.int32(4326)) + result = shapely.to_wkb(point_with_srid, include_srid=True, byte_order=1) + assert np.frombuffer(result[5:9], "= (3, 10, 0), reason="GEOS < 3.10.0") +def test_to_wkb_flavor_unsupported_geos(): + with pytest.raises(UnsupportedGEOSVersionError): + shapely.to_wkb(point_z, flavor="iso") + + +@pytest.mark.parametrize( + "geom,expected", + [ + pytest.param(empty_point, POINT_NAN_WKB, id="POINT EMPTY"), + pytest.param(empty_point_z, POINT_NAN_WKB, id="POINT Z EMPTY"), + pytest.param(empty_point_m, POINT_NAN_WKB, id="POINT M EMPTY"), + pytest.param(empty_point_zm, POINT_NAN_WKB, id="POINT ZM EMPTY"), + pytest.param( + multi_point_empty, + MULTIPOINT_NAN_WKB, + id="MULTIPOINT EMPTY", + ), + pytest.param( + multi_point_empty_z, + MULTIPOINT_NAN_WKB, + id="MULTIPOINT Z EMPTY", + ), + pytest.param( + multi_point_empty_m, + MULTIPOINT_NAN_WKB, + id="MULTIPOINT M EMPTY", + ), + pytest.param( + multi_point_empty_zm, + MULTIPOINT_NAN_WKB, + id="MULTIPOINT ZM EMPTY", + ), + pytest.param( + shapely.geometrycollections([empty_point]), + GEOMETRYCOLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT EMPTY)", + ), + pytest.param( + shapely.geometrycollections([empty_point_z]), + GEOMETRYCOLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT Z EMPTY)", + ), + pytest.param( + shapely.geometrycollections([empty_point_m]), + GEOMETRYCOLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT M EMPTY)", + ), + pytest.param( + shapely.geometrycollections([empty_point_zm]), + GEOMETRYCOLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT ZM EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty]), + NESTED_COLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_z]), + NESTED_COLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT Z EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_m]), + NESTED_COLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT M EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_zm]), + NESTED_COLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT ZM EMPTY)", + ), + ], +) +def test_to_wkb_point_empty_2d(geom, expected): + actual = shapely.to_wkb(geom, output_dimension=2, byte_order=1) + # Split 'actual' into header and coordinates + coordinate_length = 16 + header_length = len(expected) - coordinate_length + # Check the total length (this checks the correct dimensionality) + assert len(actual) == header_length + coordinate_length + # Check the header + assert actual[:header_length] == expected[:header_length] + # Check the coordinates (using numpy.isnan; there are many byte representations for + # NaN) + assert np.isnan(struct.unpack("<2d", actual[header_length:])).all() + + +@pytest.mark.parametrize( + "geom,expected", + [ + pytest.param(empty_point_z, POINTZ_NAN_WKB, id="POINT Z EMPTY"), + pytest.param(empty_point_zm, POINTZ_NAN_WKB, id="POINT ZM EMPTY"), + pytest.param( + multi_point_empty_z, + MULTIPOINTZ_NAN_WKB, + id="MULTIPOINT Z EMPTY", + ), + pytest.param( + multi_point_empty_zm, + MULTIPOINTZ_NAN_WKB, + id="MULTIPOINT ZM EMPTY", + ), + pytest.param( + shapely.geometrycollections([empty_point_z]), + GEOMETRYCOLLECTIONZ_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT Z EMPTY)", + ), + pytest.param( + shapely.geometrycollections([empty_point_zm]), + GEOMETRYCOLLECTIONZ_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT ZM EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_z]), + NESTED_COLLECTIONZ_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT Z EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_zm]), + NESTED_COLLECTIONZ_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT ZM EMPTY)", + ), + ], +) +def test_to_wkb_point_empty_z(geom, expected): + actual = shapely.to_wkb(geom, output_dimension=3, byte_order=1) + # Split 'actual' into header and coordinates + coordinate_length = 8 * 3 + header_length = len(expected) - coordinate_length + # Check the total length (this checks the correct dimensionality) + assert len(actual) == header_length + coordinate_length + # Check the header + assert actual[:header_length] == expected[:header_length] + # Check the coordinates (using numpy.isnan; there are many byte representations for + # NaN) + assert np.isnan(struct.unpack("<3d", actual[header_length:])).all() + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize( + "geom,expected", + [ + pytest.param(empty_point_m, POINTM_NAN_WKB, id="POINT M EMPTY"), + pytest.param( + multi_point_empty_m, + MULTIPOINTM_NAN_WKB, + id="MULTIPOINT M EMPTY", + ), + pytest.param( + shapely.geometrycollections([empty_point_m]), + GEOMETRYCOLLECTIONM_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT M EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_m]), + NESTED_COLLECTIONM_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT M EMPTY)", + ), + ], +) +def test_to_wkb_point_empty_m(geom, expected): + actual = shapely.to_wkb(geom, output_dimension=3, byte_order=1) + # Split 'actual' into header and coordinates + coordinate_length = 8 * 3 + header_length = len(expected) - coordinate_length + assert len(actual) == header_length + coordinate_length + assert actual[:header_length] == expected[:header_length] + assert np.isnan(struct.unpack("<3d", actual[header_length:])).all() + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize( + "geom,expected", + [ + pytest.param(empty_point_zm, POINTZM_NAN_WKB, id="POINT ZM EMPTY"), + pytest.param( + multi_point_empty_zm, + MULTIPOINTZM_NAN_WKB, + id="MULTIPOINT ZM EMPTY", + ), + pytest.param( + shapely.geometrycollections([empty_point_zm]), + GEOMETRYCOLLECTIONZM_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT ZM EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty_zm]), + NESTED_COLLECTIONZM_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT ZM EMPTY)", + ), + ], +) +def test_to_wkb_point_empty_zm(geom, expected): + actual = shapely.to_wkb(geom, output_dimension=4, byte_order=1) + # Split 'actual' into header and coordinates + coordinate_length = 8 * 4 + header_length = len(expected) - coordinate_length + assert len(actual) == header_length + coordinate_length + assert actual[:header_length] == expected[:header_length] + assert np.isnan(struct.unpack("<4d", actual[header_length:])).all() + + +@pytest.mark.parametrize( + "geom,expected", + [ + pytest.param(empty_point, POINT_NAN_WKB, id="POINT EMPTY"), + pytest.param(multi_point_empty, MULTIPOINT_NAN_WKB, id="MULTIPOINT EMPTY"), + pytest.param( + shapely.geometrycollections([empty_point]), + GEOMETRYCOLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (POINT EMPTY)", + ), + pytest.param( + shapely.geometrycollections([multi_point_empty]), + NESTED_COLLECTION_NAN_WKB, + id="GEOMETRYCOLLECTION (MULTIPOINT EMPTY)", + ), + ], +) +def test_to_wkb_point_empty_2d_output_dim_3(geom, expected): + actual = shapely.to_wkb(geom, output_dimension=3, byte_order=1) + # Split 'actual' into header and coordinates + coordinate_length = 16 + header_length = len(expected) - coordinate_length + # Check the total length (this checks the correct dimensionality) + assert len(actual) == header_length + coordinate_length + # Check the header + assert actual[:header_length] == expected[:header_length] + # Check the coordinates (using numpy.isnan; there are many byte representations for + # NaN) + assert np.isnan(struct.unpack("<2d", actual[header_length:])).all() + + +@pytest.mark.parametrize( + "wkb,expected_type,expected_dim", + [ + pytest.param(POINT_NAN_WKB, 0, 2, id="POINT_NAN_WKB"), + pytest.param(POINTZ_NAN_WKB, 0, 3, id="POINTZ_NAN_WKB"), + pytest.param(MULTIPOINT_NAN_WKB, 4, 2, id="MULTIPOINT_NAN_WKB"), + pytest.param(MULTIPOINTZ_NAN_WKB, 4, 3, id="MULTIPOINTZ_NAN_WKB"), + pytest.param(GEOMETRYCOLLECTION_NAN_WKB, 7, 2, id="GEOMETRYCOLLECTION_NAN_WKB"), + pytest.param( + GEOMETRYCOLLECTIONZ_NAN_WKB, 7, 3, id="GEOMETRYCOLLECTIONZ_NAN_WKB" + ), + pytest.param(NESTED_COLLECTION_NAN_WKB, 7, 2, id="NESTED_COLLECTION_NAN_WKB"), + pytest.param(NESTED_COLLECTIONZ_NAN_WKB, 7, 3, id="NESTED_COLLECTIONZ_NAN_WKB"), + ], +) +def test_from_wkb_point_empty(wkb, expected_type, expected_dim): + geom = shapely.from_wkb(wkb) + # POINT (nan nan) transforms to an empty point + assert shapely.is_empty(geom) + assert shapely.get_type_id(geom) == expected_type + assert shapely.get_coordinate_dimension(geom) == expected_dim + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize( + "wkb,expected_type", + [ + pytest.param(POINTM_NAN_WKB, 0, id="POINTM_NAN_WKB"), + pytest.param(MULTIPOINTM_NAN_WKB, 4, id="MULTIPOINTM_NAN_WKB"), + pytest.param(GEOMETRYCOLLECTIONM_NAN_WKB, 7, id="GEOMETRYCOLLECTIONM_NAN_WKB"), + pytest.param(NESTED_COLLECTIONM_NAN_WKB, 7, id="NESTED_COLLECTIONM_NAN_WKB"), + ], +) +def test_from_wkb_point_empty_m(wkb, expected_type): + geom = shapely.from_wkb(wkb) + + assert shapely.is_empty(geom) + assert shapely.get_type_id(geom) == expected_type + assert shapely.get_coordinate_dimension(geom) == 3 + assert not shapely.has_z(geom) + assert shapely.has_m(geom) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize( + "wkb,expected_type", + [ + pytest.param(POINTZM_NAN_WKB, 0, id="POINTZM_NAN_WKB"), + pytest.param(MULTIPOINTZM_NAN_WKB, 4, id="MULTIPOINTZM_NAN_WKB"), + pytest.param( + GEOMETRYCOLLECTIONZM_NAN_WKB, 7, id="GEOMETRYCOLLECTIONZM_NAN_WKB" + ), + pytest.param(NESTED_COLLECTIONZM_NAN_WKB, 7, id="NESTED_COLLECTIONZM_NAN_WKB"), + ], +) +def test_from_wkb_point_empty_zm(wkb, expected_type): + geom = shapely.from_wkb(wkb) + + assert shapely.is_empty(geom) + assert shapely.get_type_id(geom) == expected_type + assert shapely.get_coordinate_dimension(geom) == 4 + assert shapely.has_z(geom) + assert shapely.has_m(geom) + + +def test_to_wkb_point_empty_srid(): + expected = shapely.set_srid(empty_point, 4236) + wkb = shapely.to_wkb(expected, include_srid=True) + actual = shapely.from_wkb(wkb) + assert shapely.get_srid(actual) == 4236 + + +@pytest.mark.parametrize("geom", all_types + (point_z, empty_point)) +def test_pickle(geom): + pickled = pickle.dumps(geom) + assert_geometries_equal(pickle.loads(pickled), geom, tolerance=0) + + +@pytest.mark.parametrize("geom", all_types_z) +def test_pickle_z(geom): + pickled = pickle.dumps(geom) + actual = pickle.loads(pickled) + assert_geometries_equal(actual, geom, tolerance=0) + if not actual.is_empty: # GEOSHasZ with EMPTY geometries is inconsistent + assert actual.has_z + if shapely.geos_version >= (3, 12, 0): + assert not actual.has_m + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geom", all_types_m) +def test_pickle_m(geom): + pickled = pickle.dumps(geom) + actual = pickle.loads(pickled) + assert_geometries_equal(actual, geom, tolerance=0) + assert not actual.has_z + if not actual.is_empty: # GEOSHasM with EMPTY geometries is inconsistent + assert actual.has_m + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geom", all_types_zm) +def test_pickle_zm(geom): + pickled = pickle.dumps(geom) + actual = pickle.loads(pickled) + assert_geometries_equal(actual, geom, tolerance=0) + if not actual.is_empty: # GEOSHasZ with EMPTY geometries is inconsistent + assert actual.has_z + assert actual.has_m + + +@pytest.mark.parametrize("geom", all_types + (point_z, empty_point)) +def test_pickle_with_srid(geom): + geom = shapely.set_srid(geom, 4326) + pickled = pickle.dumps(geom) + assert shapely.get_srid(pickle.loads(pickled)) == 4326 + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +@pytest.mark.parametrize( + "geojson,expected", + [ + pytest.param( + GEOJSON_GEOMETRY, GEOJSON_GEOMETRY_EXPECTED, id="GEOJSON_GEOMETRY" + ), + pytest.param(GEOJSON_FEATURE, GEOJSON_GEOMETRY_EXPECTED, id="GEOJSON_FEATURE"), + pytest.param( + GEOJSON_FEATURECOLECTION, + shapely.geometrycollections(GEOJSON_COLLECTION_EXPECTED), + id="GEOJSON_FEATURECOLECTION", + ), + pytest.param( + [GEOJSON_GEOMETRY] * 2, + [GEOJSON_GEOMETRY_EXPECTED] * 2, + id="GEOJSON_GEOMETRYx2", + ), + pytest.param(None, None, id="None"), + pytest.param( + [GEOJSON_GEOMETRY, None], + [GEOJSON_GEOMETRY_EXPECTED, None], + id="GEOJSON_GEOMETRY_None", + ), + ], +) +def test_from_geojson(geojson, expected): + actual = shapely.from_geojson(geojson) + assert_geometries_equal(actual, expected) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +def test_from_geojson_exceptions(): + with pytest.raises(TypeError, match="Expected bytes or string, got int"): + shapely.from_geojson(1) + + with pytest.raises(shapely.GEOSException, match="Error parsing JSON"): + shapely.from_geojson("") + + with pytest.raises(shapely.GEOSException, match="Unknown geometry type"): + shapely.from_geojson('{"type": "NoGeometry", "coordinates": []}') + + with pytest.raises(shapely.GEOSException, match="type must be array, but is null"): + shapely.from_geojson('{"type": "LineString", "coordinates": null}') + + # Note: The two below tests are the reason that from_geojson is disabled for + # GEOS 3.10.0 See https://trac.osgeo.org/geos/ticket/1138 + with pytest.raises(shapely.GEOSException, match="key 'type' not found"): + shapely.from_geojson('{"geometry": null, "properties": []}') + + with pytest.raises(shapely.GEOSException, match="key 'type' not found"): + shapely.from_geojson('{"no": "geojson"}') + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +def test_from_geojson_warn_on_invalid(): + with pytest.warns(Warning, match="Invalid GeoJSON"): + assert shapely.from_geojson("", on_invalid="warn") is None + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +def test_from_geojson_ignore_on_invalid(): + with warnings.catch_warnings(): + warnings.simplefilter("error") + assert shapely.from_geojson("", on_invalid="ignore") is None + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +def test_from_geojson_on_invalid_unsupported_option(): + with pytest.raises(ValueError, match="not a valid option"): + shapely.from_geojson(GEOJSON_GEOMETRY, on_invalid="unsupported_option") + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "expected,geometry", + [ + pytest.param( + GEOJSON_GEOMETRY, GEOJSON_GEOMETRY_EXPECTED, id="GEOJSON_GEOMETRY" + ), + pytest.param( + [GEOJSON_GEOMETRY] * 2, + [GEOJSON_GEOMETRY_EXPECTED] * 2, + id="GEOJSON_GEOMETRYx2", + ), + pytest.param(None, None, id="None"), + pytest.param( + [GEOJSON_GEOMETRY, None], + [GEOJSON_GEOMETRY_EXPECTED, None], + id="GEOJSON_GEOMETRY_None", + ), + ], +) +def test_to_geojson(geometry, expected): + actual = shapely.to_geojson(geometry, indent=4) + assert np.all(actual == np.asarray(expected)) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize("indent", [None, 0, 4]) +def test_to_geojson_indent(indent): + separators = (",", ":") if indent is None else (",", ": ") + expected = json.dumps( + json.loads(GEOJSON_GEOMETRY), indent=indent, separators=separators + ) + actual = shapely.to_geojson(GEOJSON_GEOMETRY_EXPECTED, indent=indent) + assert actual == expected + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +def test_to_geojson_exceptions(): + with pytest.raises(TypeError): + shapely.to_geojson(1) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 2), reason="GEOS < 3.10.2") +@pytest.mark.parametrize( + "geom", + [ + empty_point, + shapely.multipoints([empty_point, point]), + shapely.geometrycollections([empty_point, point]), + shapely.geometrycollections( + [shapely.geometrycollections([empty_point]), point] + ), + ], +) +def test_to_geojson_point_empty(geom): + assert geom.equals(shapely.from_geojson(shapely.to_geojson(geom))) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 1), reason="GEOS < 3.10.1") +@pytest.mark.parametrize("geom", all_types) +def test_geojson_all_types(geom): + type_id = shapely.get_type_id(geom) + if type_id == shapely.GeometryType.LINEARRING: + pytest.skip("Linearrings are not preserved in GeoJSON") + elif ( + geom.is_empty + and type_id == shapely.GeometryType.POINT + and shapely.geos_version < (3, 10, 2) + ): + pytest.skip("GEOS < 3.10.2 with POINT EMPTY") # TRAC-1139 + geojson = shapely.to_geojson(geom) + actual = shapely.from_geojson(geojson) + assert not actual.has_z + geoms_are_empty = shapely.is_empty([geom, actual]) + if geoms_are_empty.any(): + # Ensure both are EMPTY + assert geoms_are_empty.all() + else: + assert_geometries_equal(actual, geom) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_linear.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..e1a5d13c894123d6ac9dcf07867613dded7a6b89 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_linear.py @@ -0,0 +1,224 @@ +import numpy as np +import pytest + +import shapely +from shapely import GeometryCollection, LinearRing, LineString, MultiLineString, Point +from shapely.errors import UnsupportedGEOSVersionError +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + empty_line_string, + empty_point, + line_string, + linear_ring, + multi_line_string, + multi_point, + multi_polygon, + point, + polygon, +) + + +def test_line_interpolate_point_geom_array(): + actual = shapely.line_interpolate_point( + [line_string, linear_ring, multi_line_string], -1 + ) + assert_geometries_equal(actual[0], Point(1, 0)) + assert_geometries_equal(actual[1], Point(0, 1)) + assert_geometries_equal(actual[2], Point(0.5528, 1.1056), tolerance=0.001) + + +def test_line_interpolate_point_geom_array_normalized(): + actual = shapely.line_interpolate_point( + [line_string, linear_ring, multi_line_string], 1, normalized=True + ) + assert_geometries_equal(actual[0], Point(1, 1)) + assert_geometries_equal(actual[1], Point(0, 0)) + assert_geometries_equal(actual[2], Point(1, 2)) + + +def test_line_interpolate_point_float_array(): + actual = shapely.line_interpolate_point(line_string, [0.2, 1.5, -0.2]) + assert_geometries_equal(actual[0], Point(0.2, 0)) + assert_geometries_equal(actual[1], Point(1, 0.5)) + assert_geometries_equal(actual[2], Point(1, 0.8)) + + +@pytest.mark.parametrize("normalized", [False, True]) +@pytest.mark.parametrize( + "geom", + [ + LineString(), + LinearRing(), + MultiLineString(), + shapely.from_wkt("MULTILINESTRING (EMPTY, (0 0, 1 1))"), + GeometryCollection(), + GeometryCollection([LineString(), Point(1, 1)]), + ], +) +def test_line_interpolate_point_empty(geom, normalized): + assert_geometries_equal( + shapely.line_interpolate_point(geom, 0.2, normalized=normalized), empty_point + ) + + +@pytest.mark.parametrize("normalized", [False, True]) +@pytest.mark.parametrize( + "geom", + [ + empty_point, + point, + polygon, + multi_point, + multi_polygon, + shapely.geometrycollections([point]), + shapely.geometrycollections([polygon]), + shapely.geometrycollections([multi_line_string]), + shapely.geometrycollections([multi_point]), + shapely.geometrycollections([multi_polygon]), + ], +) +def test_line_interpolate_point_invalid_type(geom, normalized): + with pytest.raises(TypeError): + assert shapely.line_interpolate_point(geom, 0.2, normalized=normalized) + + +def test_line_interpolate_point_none(): + assert shapely.line_interpolate_point(None, 0.2) is None + + +def test_line_interpolate_point_nan(): + assert shapely.line_interpolate_point(line_string, np.nan) is None + + +def test_line_interpolate_point_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `normalized` for `line_interpolate_point` " + "is deprecated" + ): + shapely.line_interpolate_point(line_string, 0, False) + + +def test_line_locate_point_geom_array(): + point = shapely.points(0, 1) + actual = shapely.line_locate_point([line_string, linear_ring], point) + np.testing.assert_allclose(actual, [0.0, 3.0]) + + +def test_line_locate_point_geom_array2(): + points = shapely.points([[0, 0], [1, 0]]) + actual = shapely.line_locate_point(line_string, points) + np.testing.assert_allclose(actual, [0.0, 1.0]) + + +@pytest.mark.parametrize("normalized", [False, True]) +def test_line_locate_point_none(normalized): + assert np.isnan(shapely.line_locate_point(line_string, None, normalized=normalized)) + assert np.isnan(shapely.line_locate_point(None, point, normalized=normalized)) + + +@pytest.mark.parametrize("normalized", [False, True]) +def test_line_locate_point_empty(normalized): + assert np.isnan( + shapely.line_locate_point(line_string, empty_point, normalized=normalized) + ) + assert np.isnan( + shapely.line_locate_point(empty_line_string, point, normalized=normalized) + ) + + +@pytest.mark.parametrize("normalized", [False, True]) +def test_line_locate_point_invalid_geometry(normalized): + with pytest.raises(shapely.GEOSException): + shapely.line_locate_point(line_string, line_string, normalized=normalized) + + with pytest.raises(shapely.GEOSException): + shapely.line_locate_point(polygon, point, normalized=normalized) + + +def test_line_locate_point_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `normalized` for `line_locate_point` is deprecated" + ): + shapely.line_locate_point(line_string, point, False) + + +def test_line_merge_geom_array(): + actual = shapely.line_merge([line_string, multi_line_string]) + assert_geometries_equal(actual[0], line_string) + assert_geometries_equal(actual[1], LineString([(0, 0), (1, 2)])) + + +@pytest.mark.skipif(shapely.geos_version < (3, 11, 0), reason="GEOS < 3.11.0") +def test_line_merge_directed(): + lines = MultiLineString([[(0, 0), (1, 0)], [(0, 0), (3, 0)]]) + # Merge lines without directed, this requires changing the vertex ordering + result = shapely.line_merge(lines) + assert_geometries_equal(result, LineString([(1, 0), (0, 0), (3, 0)])) + # Since the lines can't be merged when directed is specified + # the original geometry is returned + result = shapely.line_merge(lines, directed=True) + assert_geometries_equal(result, lines) + + +@pytest.mark.skipif(shapely.geos_version >= (3, 11, 0), reason="GEOS >= 3.11.0") +def test_line_merge_error(): + lines = MultiLineString([[(0, 0), (1, 0)], [(0, 0), (3, 0)]]) + with pytest.raises(UnsupportedGEOSVersionError): + shapely.line_merge(lines, directed=True) + + +def test_shared_paths_linestring(): + g1 = shapely.linestrings([(0, 0), (1, 0), (1, 1)]) + g2 = shapely.linestrings([(0, 0), (1, 0)]) + actual1 = shapely.shared_paths(g1, g2) + assert_geometries_equal( + shapely.get_geometry(actual1, 0), shapely.multilinestrings([g2]) + ) + + +def test_shared_paths_none(): + assert shapely.shared_paths(line_string, None) is None + assert shapely.shared_paths(None, line_string) is None + assert shapely.shared_paths(None, None) is None + + +def test_shared_paths_non_linestring(): + g1 = shapely.linestrings([(0, 0), (1, 0), (1, 1)]) + g2 = shapely.points(0, 1) + with pytest.raises(shapely.GEOSException): + shapely.shared_paths(g1, g2) + + +def _prepare_input(geometry, prepare): + """Prepare without modifying in-place""" + if prepare: + geometry = shapely.transform(geometry, lambda x: x) # makes a copy + shapely.prepare(geometry) + return geometry + else: + return geometry + + +@pytest.mark.parametrize("prepare", [True, False]) +def test_shortest_line(prepare): + g1 = shapely.linestrings([(0, 0), (1, 0), (1, 1)]) + g2 = shapely.linestrings([(0, 3), (3, 0)]) + actual = shapely.shortest_line(_prepare_input(g1, prepare), g2) + expected = shapely.linestrings([(1, 1), (1.5, 1.5)]) + assert shapely.equals(actual, expected) + + +@pytest.mark.parametrize("prepare", [True, False]) +def test_shortest_line_none(prepare): + assert shapely.shortest_line(_prepare_input(line_string, prepare), None) is None + assert shapely.shortest_line(None, line_string) is None + assert shapely.shortest_line(None, None) is None + + +@pytest.mark.parametrize("prepare", [True, False]) +def test_shortest_line_empty(prepare): + g1 = _prepare_input(line_string, prepare) + assert shapely.shortest_line(g1, empty_line_string) is None + g1_empty = _prepare_input(empty_line_string, prepare) + assert shapely.shortest_line(g1_empty, line_string) is None + assert shapely.shortest_line(g1_empty, empty_line_string) is None diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_measurement.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_measurement.py new file mode 100644 index 0000000000000000000000000000000000000000..2edfbed8fe12c239dd9e22b26e7561b5ecd5ceab --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_measurement.py @@ -0,0 +1,344 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_equal + +import shapely +from shapely import GeometryCollection, LineString, MultiPoint, Point, Polygon +from shapely.tests.common import ( + empty, + geometry_collection, + ignore_invalid, + line_string, + linear_ring, + multi_line_string, + multi_point, + multi_polygon, + point, + point_polygon_testdata, + polygon, + polygon_with_hole, +) + + +@pytest.mark.parametrize( + "geom", + [ + point, + line_string, + linear_ring, + multi_point, + multi_line_string, + geometry_collection, + ], +) +def test_area_non_polygon(geom): + assert shapely.area(geom) == 0.0 + + +def test_area(): + actual = shapely.area([polygon, polygon_with_hole, multi_polygon]) + assert actual.tolist() == [4.0, 96.0, 1.01] + + +def test_distance(): + actual = shapely.distance(*point_polygon_testdata) + expected = [2 * 2**0.5, 2**0.5, 0, 0, 0, 2**0.5] + np.testing.assert_allclose(actual, expected) + + +def test_distance_missing(): + actual = shapely.distance(point, None) + assert np.isnan(actual) + + +def test_distance_duplicated(): + a = Point(1, 2) + b = LineString([(0, 0), (0, 0), (1, 1)]) + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # https://github.com/shapely/shapely/issues/1552 + # GEOS < 3.12 raises "invalid" floating point errors + actual = shapely.distance(a, b) + assert actual == 1.0 + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, [2, 3, 2, 3]), + ([point, multi_point], [[2, 3, 2, 3], [0, 0, 1, 2]]), + (shapely.linestrings([[0, 0], [0, 1]]), [0, 0, 0, 1]), + (shapely.linestrings([[0, 0], [1, 0]]), [0, 0, 1, 0]), + (multi_point, [0, 0, 1, 2]), + (multi_polygon, [0, 0, 2.2, 2.2]), + (geometry_collection, [49, -1, 52, 2]), + (empty, [np.nan, np.nan, np.nan, np.nan]), + (None, [np.nan, np.nan, np.nan, np.nan]), + ], +) +def test_bounds(geom, expected): + assert_array_equal(shapely.bounds(geom), expected) + + +@pytest.mark.parametrize( + "geom,shape", + [ + (point, (4,)), + (None, (4,)), + ([point, multi_point], (2, 4)), + ([[point, multi_point], [polygon, point]], (2, 2, 4)), + ([[[point, multi_point]], [[polygon, point]]], (2, 1, 2, 4)), + ], +) +def test_bounds_dimensions(geom, shape): + assert shapely.bounds(geom).shape == shape + + +@pytest.mark.parametrize( + "geom,expected", + [ + (point, [2, 3, 2, 3]), + (shapely.linestrings([[0, 0], [0, 1]]), [0, 0, 0, 1]), + (shapely.linestrings([[0, 0], [1, 0]]), [0, 0, 1, 0]), + (multi_point, [0, 0, 1, 2]), + (multi_polygon, [0, 0, 2.2, 2.2]), + (geometry_collection, [49, -1, 52, 2]), + (empty, [np.nan, np.nan, np.nan, np.nan]), + (None, [np.nan, np.nan, np.nan, np.nan]), + ([empty, empty, None], [np.nan, np.nan, np.nan, np.nan]), + # mixed missing and non-missing coordinates + ([point, None], [2, 3, 2, 3]), + ([point, empty], [2, 3, 2, 3]), + ([point, empty, None], [2, 3, 2, 3]), + ([point, empty, None, multi_point], [0, 0, 2, 3]), + ], +) +def test_total_bounds(geom, expected): + assert_array_equal(shapely.total_bounds(geom), expected) + + +@pytest.mark.parametrize( + "geom", + [ + point, + None, + [point, multi_point], + [[point, multi_point], [polygon, point]], + [[[point, multi_point]], [[polygon, point]]], + ], +) +def test_total_bounds_dimensions(geom): + assert shapely.total_bounds(geom).shape == (4,) + + +def test_length(): + actual = shapely.length( + [ + point, + line_string, + linear_ring, + polygon, + polygon_with_hole, + multi_point, + multi_polygon, + ] + ) + assert actual.tolist() == [0.0, 2.0, 4.0, 8.0, 48.0, 0.0, 4.4] + + +def test_length_missing(): + actual = shapely.length(None) + assert np.isnan(actual) + + +def test_hausdorff_distance(): + # example from GEOS docs + a = shapely.linestrings([[0, 0], [100, 0], [10, 100], [10, 100]]) + b = shapely.linestrings([[0, 100], [0, 10], [80, 10]]) + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # Hausdorff distance emits "invalid value encountered" + # (see https://github.com/libgeos/geos/issues/515) + actual = shapely.hausdorff_distance(a, b) + assert actual == pytest.approx(22.360679775, abs=1e-7) + + +def test_hausdorff_distance_densify(): + # example from GEOS docs + a = shapely.linestrings([[0, 0], [100, 0], [10, 100], [10, 100]]) + b = shapely.linestrings([[0, 100], [0, 10], [80, 10]]) + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # Hausdorff distance emits "invalid value encountered" + # (see https://github.com/libgeos/geos/issues/515) + actual = shapely.hausdorff_distance(a, b, densify=0.001) + assert actual == pytest.approx(47.8, abs=0.1) + + +def test_hausdorff_distance_missing(): + actual = shapely.hausdorff_distance(point, None) + assert np.isnan(actual) + actual = shapely.hausdorff_distance(point, None, densify=0.001) + assert np.isnan(actual) + + +def test_hausdorff_densify_nan(): + actual = shapely.hausdorff_distance(point, point, densify=np.nan) + assert np.isnan(actual) + + +def test_distance_empty(): + actual = shapely.distance(point, empty) + assert np.isnan(actual) + + +def test_hausdorff_distance_empty(): + actual = shapely.hausdorff_distance(point, empty) + assert np.isnan(actual) + + +def test_hausdorff_distance_densify_empty(): + actual = shapely.hausdorff_distance(point, empty, densify=0.2) + assert np.isnan(actual) + + +@pytest.mark.parametrize( + "geom1, geom2, expected", + [ + # identical geometries should have 0 distance + ( + shapely.linestrings([[0, 0], [100, 0]]), + shapely.linestrings([[0, 0], [100, 0]]), + 0, + ), + # example from GEOS docs + ( + shapely.linestrings([[0, 0], [50, 200], [100, 0], [150, 200], [200, 0]]), + shapely.linestrings([[0, 200], [200, 150], [0, 100], [200, 50], [0, 0]]), + 200, + ), + # same geometries but different curve direction results in maximum + # distance between vertices on the lines. + ( + shapely.linestrings([[0, 0], [50, 200], [100, 0], [150, 200], [200, 0]]), + shapely.linestrings([[200, 0], [150, 200], [100, 0], [50, 200], [0, 0]]), + 200, + ), + # another example from GEOS docs + ( + shapely.linestrings([[0, 0], [50, 200], [100, 0], [150, 200], [200, 0]]), + shapely.linestrings([[0, 0], [200, 50], [0, 100], [200, 150], [0, 200]]), + 282.842712474619, + ), + # example from GEOS tests + ( + shapely.linestrings([[0, 0], [100, 0]]), + shapely.linestrings([[0, 0], [50, 50], [100, 0]]), + 70.7106781186548, + ), + ], +) +def test_frechet_distance(geom1, geom2, expected): + actual = shapely.frechet_distance(geom1, geom2) + assert actual == pytest.approx(expected, abs=1e-12) + + +@pytest.mark.parametrize( + "geom1, geom2, densify, expected", + [ + # example from GEOS tests + ( + shapely.linestrings([[0, 0], [100, 0]]), + shapely.linestrings([[0, 0], [50, 50], [100, 0]]), + 0.002, + 50, + ) + ], +) +def test_frechet_distance_densify(geom1, geom2, densify, expected): + actual = shapely.frechet_distance(geom1, geom2, densify=densify) + assert actual == pytest.approx(expected, abs=1e-12) + + +@pytest.mark.parametrize( + "geom1, geom2", + [ + (line_string, None), + (None, line_string), + (None, None), + (line_string, empty), + (empty, line_string), + (empty, empty), + ], +) +def test_frechet_distance_nan_for_invalid_geometry_inputs(geom1, geom2): + actual = shapely.frechet_distance(geom1, geom2) + assert np.isnan(actual) + + +def test_frechet_densify_ndarray(): + actual = shapely.frechet_distance( + shapely.linestrings([[0, 0], [100, 0]]), + shapely.linestrings([[0, 0], [50, 50], [100, 0]]), + densify=[0.1, 0.2, 1], + ) + expected = np.array([50, 50.99019514, 70.7106781186548]) + np.testing.assert_array_almost_equal(actual, expected) + + +def test_frechet_densify_nan(): + actual = shapely.frechet_distance(line_string, line_string, densify=np.nan) + assert np.isnan(actual) + + +@pytest.mark.parametrize("densify", [0, -1, 2]) +def test_frechet_densify_invalid_values(densify): + with pytest.raises(shapely.GEOSException, match="Fraction is not in range"): + shapely.frechet_distance(line_string, line_string, densify=densify) + + +def test_frechet_distance_densify_empty(): + actual = shapely.frechet_distance(line_string, empty, densify=0.2) + assert np.isnan(actual) + + +def test_minimum_clearance(): + actual = shapely.minimum_clearance([polygon, polygon_with_hole, multi_polygon]) + assert_allclose(actual, [2.0, 2.0, 0.1]) + + +def test_minimum_clearance_nonexistent(): + actual = shapely.minimum_clearance([point, empty]) + assert np.isinf(actual).all() + + +def test_minimum_clearance_missing(): + actual = shapely.minimum_clearance(None) + assert np.isnan(actual) + + +@pytest.mark.parametrize( + "geometry, expected", + [ + ( + Polygon([(0, 5), (5, 10), (10, 5), (5, 0), (0, 5)]), + 5, + ), + ( + LineString([(1, 0), (1, 10)]), + 5, + ), + ( + MultiPoint([(2, 2), (4, 2)]), + 1, + ), + ( + Point(2, 2), + 0, + ), + ( + GeometryCollection(), + 0, + ), + ], +) +def test_minimum_bounding_radius(geometry, expected): + actual = shapely.minimum_bounding_radius(geometry) + assert actual == pytest.approx(expected, abs=1e-12) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_misc.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..0ee2c98ee75b0ef18b4a74cfddf399ee3b8c4c44 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_misc.py @@ -0,0 +1,189 @@ +import os +import sys +from inspect import cleandoc +from itertools import chain +from string import ascii_letters, digits +from unittest import mock + +import numpy as np +import pytest + +import shapely +from shapely.decorators import multithreading_enabled, requires_geos + + +@pytest.fixture +def mocked_geos_version(): + with mock.patch.object(shapely.lib, "geos_version", new=(3, 10, 1)): + yield "3.10.1" + + +@pytest.fixture +def sphinx_doc_build(): + os.environ["SPHINX_DOC_BUILD"] = "1" + yield + del os.environ["SPHINX_DOC_BUILD"] + + +def test_version(): + assert isinstance(shapely.__version__, str) + + +def test_geos_version(): + expected = "{}.{}.{}".format(*shapely.geos_version) + actual = shapely.geos_version_string + + # strip any beta / dev qualifiers + if any(c.isalpha() for c in actual): + if actual[-1].isnumeric(): + actual = actual.rstrip(digits) + actual = actual.rstrip(ascii_letters) + + assert actual == expected + + +def test_geos_capi_version(): + expected = "{}.{}.{}-CAPI-{}.{}.{}".format( + *(shapely.geos_version + shapely.geos_capi_version) + ) + + # split into component parts and strip any beta / dev qualifiers + ( + actual_geos_version, + actual_geos_api_version, + ) = shapely.geos_capi_version_string.split("-CAPI-") + + if any(c.isalpha() for c in actual_geos_version): + if actual_geos_version[-1].isnumeric(): + actual_geos_version = actual_geos_version.rstrip(digits) + actual_geos_version = actual_geos_version.rstrip(ascii_letters) + actual_geos_version = actual_geos_version.rstrip(ascii_letters) + + assert f"{actual_geos_version}-CAPI-{actual_geos_api_version}" == expected + + +def func(): + """Docstring that will be mocked. + A multiline. + + Some description. + """ + + +class SomeClass: + def func(self): + """Docstring that will be mocked. + A multiline. + + Some description. + """ + + +def expected_docstring(**kwds): + doc = """Docstring that will be mocked. +{indent}A multiline. + +{indent}.. note:: 'func' requires at least GEOS {version}. + +{indent}Some description. +{indent}""".format(**kwds) + if sys.version_info[:2] >= (3, 13): + # There are subtle differences between inspect.cleandoc() and + # _PyCompile_CleanDoc(). Most significantly, the latter does not remove + # leading or trailing blank lines. + return cleandoc(doc) + "\n" + return doc + + +@pytest.mark.parametrize("version", ["3.10.0", "3.10.1", "3.9.2"]) +def test_requires_geos_ok(version, mocked_geos_version): + wrapped = requires_geos(version)(func) + wrapped() + assert wrapped is func + + +@pytest.mark.parametrize("version", ["3.10.2", "3.11.0", "3.11.1"]) +def test_requires_geos_not_ok(version, mocked_geos_version): + wrapped = requires_geos(version)(func) + with pytest.raises(shapely.errors.UnsupportedGEOSVersionError): + wrapped() + + assert wrapped.__doc__ == expected_docstring(version=version, indent=" " * 4) + + +@pytest.mark.parametrize("version", ["3.9.0", "3.10.0"]) +def test_requires_geos_doc_build(version, mocked_geos_version, sphinx_doc_build): + """The requires_geos decorator always adapts the docstring.""" + wrapped = requires_geos(version)(func) + + assert wrapped.__doc__ == expected_docstring(version=version, indent=" " * 4) + + +@pytest.mark.parametrize("version", ["3.9.0", "3.10.0"]) +def test_requires_geos_method(version, mocked_geos_version, sphinx_doc_build): + """The requires_geos decorator adjusts methods docstrings correctly""" + wrapped = requires_geos(version)(SomeClass.func) + + assert wrapped.__doc__ == expected_docstring(version=version, indent=" " * 8) + + +@multithreading_enabled +def set_first_element(value, *args, **kwargs): + for arg in chain(args, kwargs.values()): + if hasattr(arg, "__setitem__"): + arg[0] = value + return arg + + +def test_multithreading_enabled_raises_arg(): + arr = np.empty((1,), dtype=object) + + # set_first_element cannot change the input array + with pytest.raises(ValueError): + set_first_element(42, arr) + + # afterwards, we can + arr[0] = 42 + assert arr[0] == 42 + + +def test_multithreading_enabled_raises_kwarg(): + arr = np.empty((1,), dtype=object) + + # set_first_element cannot change the input array + with pytest.raises(ValueError): + set_first_element(42, arr=arr) + + # writable flag goes to original state + assert arr.flags.writeable + + +def test_multithreading_enabled_preserves_flag(): + arr = np.empty((1,), dtype=object) + arr.flags.writeable = False + + # set_first_element cannot change the input array + with pytest.raises(ValueError): + set_first_element(42, arr) + + # writable flag goes to original state + assert not arr.flags.writeable + + +@pytest.mark.parametrize( + "args,kwargs", + [ + ((np.empty((1,), dtype=float),), {}), # float-dtype ndarray is untouched + ((), {"a": np.empty((1,), dtype=float)}), + (([1],), {}), # non-ndarray is untouched + ((), {"a": [1]}), + ((), {"out": np.empty((1,), dtype=object)}), # ufunc kwarg 'out' is untouched + ( + (), + {"where": np.empty((1,), dtype=object)}, + ), # ufunc kwarg 'where' is untouched + ], +) +def test_multithreading_enabled_ok(args, kwargs): + result = set_first_element(42, *args, **kwargs) + assert result[0] == 42 diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_plotting.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_plotting.py new file mode 100644 index 0000000000000000000000000000000000000000..78a4175ee4baaba8030fe127083fb29cbb8fdfa7 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_plotting.py @@ -0,0 +1,121 @@ +import pytest +from numpy.testing import assert_allclose + +from shapely import ( + LineString, + MultiLineString, + MultiPolygon, + Point, + box, + get_coordinates, +) +from shapely.ops import orient +from shapely.plotting import patch_from_polygon, plot_line, plot_points, plot_polygon + +pytest.importorskip("matplotlib") + + +def test_patch_from_polygon(): + poly = box(0, 0, 1, 1) + artist = patch_from_polygon(poly, facecolor="red", edgecolor="blue", linewidth=3) + assert equal_color(artist.get_facecolor(), "red") + assert equal_color(artist.get_edgecolor(), "blue") + assert artist.get_linewidth() == 3 + + +def test_patch_from_polygon_with_interior(): + poly = box(0, 0, 1, 1).difference(box(0.2, 0.2, 0.5, 0.5)) + artist = patch_from_polygon(poly, facecolor="red", edgecolor="blue", linewidth=3) + assert equal_color(artist.get_facecolor(), "red") + assert equal_color(artist.get_edgecolor(), "blue") + assert artist.get_linewidth() == 3 + + +def test_patch_from_multipolygon(): + poly = box(0, 0, 1, 1).union(box(2, 2, 3, 3)) + artist = patch_from_polygon(poly, facecolor="red", edgecolor="blue", linewidth=3) + assert equal_color(artist.get_facecolor(), "red") + assert equal_color(artist.get_edgecolor(), "blue") + assert artist.get_linewidth() == 3 + + +def test_plot_polygon(): + poly = box(0, 0, 1, 1) + artist, _ = plot_polygon(poly) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(poly)) + + # overriding default styling + artist = plot_polygon(poly, add_points=False, color="red", linewidth=3) + assert equal_color(artist.get_facecolor(), "red", alpha=0.3) + assert equal_color(artist.get_edgecolor(), "red", alpha=1.0) + assert artist.get_linewidth() == 3 + + +def test_plot_polygon_with_interior(): + poly = box(0, 0, 1, 1).difference(box(0.2, 0.2, 0.5, 0.5)) + artist, _ = plot_polygon(poly) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(orient(poly))) + + +def test_plot_multipolygon(): + poly = box(0, 0, 1, 1).union(box(2, 2, 3, 3)) + artist, _ = plot_polygon(poly) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(poly)) + + +def test_plot_multipolygon_with_interior(): + poly1 = box(0, 0, 1, 1).difference(box(0.2, 0.2, 0.5, 0.5)) + poly2 = box(3, 3, 6, 6).difference(box(4, 4, 5, 5)) + poly = MultiPolygon([poly1, poly2]) + + artist, _ = plot_polygon(poly) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(orient(poly))) + + +def test_plot_line(): + line = LineString([(0, 0), (1, 0), (1, 1)]) + artist, _ = plot_line(line) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(line)) + + # overriding default styling + artist = plot_line(line, add_points=False, color="red", linewidth=3) + assert equal_color(artist.get_edgecolor(), "red") + assert equal_color(artist.get_facecolor(), "none") + assert artist.get_linewidth() == 3 + + +def test_plot_multilinestring(): + line = MultiLineString( + [LineString([(0, 0), (1, 0), (1, 1)]), LineString([(2, 2), (3, 3)])] + ) + artist, _ = plot_line(line) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(line)) + + +def test_plot_points(): + for geom in [Point(0, 0), LineString([(0, 0), (1, 0), (1, 1)]), box(0, 0, 1, 1)]: + artist = plot_points(geom) + plot_coords = artist.get_path().vertices + assert_allclose(plot_coords, get_coordinates(geom)) + assert artist.get_linestyle() == "None" + + # overriding default styling + geom = Point(0, 0) + artist = plot_points(geom, color="red", marker="+", fillstyle="top") + assert artist.get_color() == "red" + assert artist.get_marker() == "+" + assert artist.get_fillstyle() == "top" + + +def equal_color(actual, expected, alpha=None): + from matplotlib import colors + + conv = colors.colorConverter + + return actual == conv.to_rgba(expected, alpha=alpha) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_predicates.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_predicates.py new file mode 100644 index 0000000000000000000000000000000000000000..a0fbac2358257c9a071995438b1b1594236e5bad --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_predicates.py @@ -0,0 +1,414 @@ +from functools import partial + +import numpy as np +import pytest + +import shapely +from shapely import LinearRing, LineString, Point +from shapely.tests.common import ( + all_types, + all_types_m, + all_types_z, + all_types_zm, + empty, + geometry_collection, + ignore_invalid, + line_string, + linear_ring, + point, + polygon, +) + +UNARY_PREDICATES = ( + shapely.has_z, + pytest.param( + shapely.has_m, + marks=pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12" + ), + ), + shapely.is_empty, + shapely.is_simple, + shapely.is_ring, + shapely.is_closed, + shapely.is_valid, + shapely.is_missing, + shapely.is_geometry, + shapely.is_valid_input, + shapely.is_prepared, + shapely.is_ccw, +) + +BINARY_PREDICATES = ( + shapely.disjoint, + shapely.touches, + shapely.intersects, + shapely.crosses, + shapely.within, + shapely.contains, + shapely.contains_properly, + shapely.overlaps, + shapely.covers, + shapely.covered_by, + pytest.param( + partial(shapely.dwithin, distance=1.0), + marks=pytest.mark.skipif( + shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10" + ), + ), + shapely.equals, + shapely.equals_exact, + shapely.equals_identical, +) + +BINARY_PREPARED_PREDICATES = BINARY_PREDICATES[:-2] + +XY_PREDICATES = ( + (shapely.contains_xy, shapely.contains), + (shapely.intersects_xy, shapely.intersects), +) + + +@pytest.mark.parametrize("geometry", all_types + all_types_z) +@pytest.mark.parametrize("func", UNARY_PREDICATES) +def test_unary_array(geometry, func): + actual = func([geometry, geometry]) + assert actual.shape == (2,) + assert actual.dtype == np.bool_ + + +@pytest.mark.parametrize("func", UNARY_PREDICATES) +def test_unary_with_kwargs(func): + out = np.empty((), dtype=np.uint8) + actual = func(point, out=out) + assert actual is out + assert actual.dtype == np.uint8 + + +@pytest.mark.parametrize("func", UNARY_PREDICATES) +def test_unary_missing(func): + if func in (shapely.is_valid_input, shapely.is_missing): + assert func(None) + else: + assert not func(None) + + +@pytest.mark.parametrize("a", all_types) +@pytest.mark.parametrize("func", BINARY_PREDICATES) +def test_binary_array(a, func): + with ignore_invalid(shapely.is_empty(a) and shapely.geos_version < (3, 12, 0)): + # Empty geometries give 'invalid value encountered' in all predicates + # (see https://github.com/libgeos/geos/issues/515) + actual = func([a, a], point) + assert actual.shape == (2,) + assert actual.dtype == np.bool_ + + +@pytest.mark.parametrize("func", BINARY_PREDICATES) +def test_binary_with_kwargs(func): + out = np.empty((), dtype=np.uint8) + actual = func(point, point, out=out) + assert actual is out + assert actual.dtype == np.uint8 + + +@pytest.mark.parametrize("func", BINARY_PREDICATES) +def test_binary_missing(func): + actual = func(np.array([point, None, None]), np.array([None, point, None])) + assert (~actual).all() + + +def test_binary_empty_result(): + a = LineString([(0, 0), (3, 0), (3, 3), (0, 3)]) + b = LineString([(5, 1), (6, 1)]) + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # Intersection resulting in empty geometries give 'invalid value encountered' + # (https://github.com/shapely/shapely/issues/1345) + assert shapely.intersection(a, b).is_empty + + +@pytest.mark.parametrize("a", all_types) +@pytest.mark.parametrize("func, func_bin", XY_PREDICATES) +def test_xy_array(a, func, func_bin): + with ignore_invalid(shapely.is_empty(a) and shapely.geos_version < (3, 12, 0)): + # Empty geometries give 'invalid value encountered' in all predicates + # (see https://github.com/libgeos/geos/issues/515) + actual = func([a, a], 2, 3) + expected = func_bin([a, a], Point(2, 3)) + assert actual.shape == (2,) + assert actual.dtype == np.bool_ + np.testing.assert_allclose(actual, expected) + + +@pytest.mark.parametrize("a", all_types) +@pytest.mark.parametrize("func, func_bin", XY_PREDICATES) +def test_xy_array_broadcast(a, func, func_bin): + a2 = shapely.transform(a, lambda x: x) # makes a copy + with ignore_invalid(shapely.is_empty(a) and shapely.geos_version < (3, 12, 0)): + # Empty geometries give 'invalid value encountered' in all predicates + # (see https://github.com/libgeos/geos/issues/515) + actual = func(a2, [0, 1, 2], [1, 2, 3]) + expected = func_bin(a, [Point(0, 1), Point(1, 2), Point(2, 3)]) + np.testing.assert_allclose(actual, expected) + + +@pytest.mark.parametrize("func", [funcs[0] for funcs in XY_PREDICATES]) +def test_xy_array_2D(func): + polygon2 = shapely.transform(polygon, lambda x: x) # makes a copy + actual = func(polygon2, [0, 1, 2], [1, 2, 3]) + expected = func(polygon2, [[0, 1], [1, 2], [2, 3]]) + np.testing.assert_allclose(actual, expected) + + +@pytest.mark.parametrize("func, func_bin", XY_PREDICATES) +def test_xy_prepared(func, func_bin): + actual = func(_prepare_with_copy([polygon, line_string]), 2, 3) + expected = func_bin([polygon, line_string], Point(2, 3)) + np.testing.assert_allclose(actual, expected) + + +@pytest.mark.parametrize("func", [funcs[0] for funcs in XY_PREDICATES]) +def test_xy_with_kwargs(func): + out = np.empty((), dtype=np.uint8) + point2 = shapely.transform(point, lambda x: x) # makes a copy + actual = func(point2, point2.x, point2.y, out=out) + assert actual is out + assert actual.dtype == np.uint8 + + +@pytest.mark.parametrize("func", [funcs[0] for funcs in XY_PREDICATES]) +def test_xy_missing(func): + actual = func( + np.array([point, point, point, None]), + np.array([point.x, np.nan, point.x, point.x]), + np.array([point.y, point.y, np.nan, point.y]), + ) + np.testing.assert_allclose(actual, [True, False, False, False]) + + +def test_equals_exact_tolerance(): + # specifying tolerance + p1 = shapely.points(50, 4) + p2 = shapely.points(50.1, 4.1) + actual = shapely.equals_exact([p1, p2, None], p1, tolerance=0.05) + np.testing.assert_allclose(actual, [True, False, False]) + assert actual.dtype == np.bool_ + actual = shapely.equals_exact([p1, p2, None], p1, tolerance=0.2) + np.testing.assert_allclose(actual, [True, True, False]) + assert actual.dtype == np.bool_ + + # default value for tolerance + assert shapely.equals_exact(p1, p1).item() is True + assert shapely.equals_exact(p1, p2).item() is False + + # an array of tolerances + actual = shapely.equals_exact(p1, p2, tolerance=[0.05, 0.2, np.nan]) + np.testing.assert_allclose(actual, [False, True, False]) + + +def test_equals_exact_normalize(): + l1 = LineString([(0, 0), (1, 1)]) + l2 = LineString([(1, 1), (0, 0)]) + # default requires same order of coordinates + assert not shapely.equals_exact(l1, l2) + assert shapely.equals_exact(l1, l2, normalize=True) + + +def test_equals_identical(): + # more elaborate tests are done at the Geometry.__eq__ level + # requires same order of coordinates + l1 = LineString([(0, 0), (1, 1)]) + l2 = LineString([(1, 1), (0, 0)]) + assert not shapely.equals_identical(l1, l2) + + # checks z-dimension (in contrast to equals_exact) + l1 = LineString([(0, 0, 0), (1, 1, 0)]) + l2 = LineString([(0, 0, 1), (1, 1, 1)]) + assert not shapely.equals_identical(l1, l2) + assert shapely.equals_exact(l1, l2) + + # NaNs in same place are equal (in contrast to equals_exact) + with ignore_invalid(): + l1 = LineString([(0, np.nan), (1, 1)]) + l2 = LineString([(0, np.nan), (1, 1)]) + assert shapely.equals_identical(l1, l2) + assert not shapely.equals_exact(l1, l2) + + +@pytest.mark.skipif(shapely.geos_version < (3, 10, 0), reason="GEOS < 3.10") +def test_dwithin(): + p1 = shapely.points(50, 4) + p2 = shapely.points(50.1, 4.1) + actual = shapely.dwithin([p1, p2, None], p1, distance=0.05) + np.testing.assert_equal(actual, [True, False, False]) + assert actual.dtype == np.bool_ + actual = shapely.dwithin([p1, p2, None], p1, distance=0.2) + np.testing.assert_allclose(actual, [True, True, False]) + assert actual.dtype == np.bool_ + + # an array of distances + actual = shapely.dwithin(p1, p2, distance=[0.05, 0.2, np.nan]) + np.testing.assert_allclose(actual, [False, True, False]) + + +@pytest.mark.parametrize("geometry", all_types) +def test_has_z_has_m_all_types(geometry): + assert not shapely.has_z(geometry) + if shapely.geos_version >= (3, 12, 0): + assert not shapely.has_m(geometry) + + +# The next few tests skip has_z/has_m with empty geometries +# See https://github.com/libgeos/geos/issues/888 + + +@pytest.mark.parametrize("geometry", all_types_z) +def test_has_z_has_m_all_types_z(geometry): + if shapely.is_empty(geometry): + pytest.skip("GEOSHasZ with EMPTY geometries is inconsistent") + assert shapely.has_z(geometry) + if shapely.geos_version >= (3, 12, 0): + assert not shapely.has_m(geometry) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geometry", all_types_m) +def test_has_m_all_types_m(geometry): + if shapely.is_empty(geometry): + pytest.skip("GEOSHasM with EMPTY geometries is inconsistent") + assert not shapely.has_z(geometry) + assert shapely.has_m(geometry) + + +@pytest.mark.skipif( + shapely.geos_version < (3, 12, 0), + reason="M coordinates not supported with GEOS < 3.12", +) +@pytest.mark.parametrize("geometry", all_types_zm) +def test_has_z_has_m_all_types_zm(geometry): + if shapely.is_empty(geometry): + pytest.skip("GEOSHasZ with EMPTY geometries is inconsistent") + assert shapely.has_z(geometry) + assert shapely.has_m(geometry) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (point, False), + (line_string, False), + (linear_ring, True), + (empty, False), + ], +) +def test_is_closed(geometry, expected): + assert shapely.is_closed(geometry) == expected + + +def test_relate(): + p1 = shapely.points(0, 0) + p2 = shapely.points(1, 1) + actual = shapely.relate(p1, p2) + assert isinstance(actual, str) + assert actual == "FF0FFF0F2" + + +@pytest.mark.parametrize("g1, g2", [(point, None), (None, point), (None, None)]) +def test_relate_none(g1, g2): + assert shapely.relate(g1, g2) is None + + +def test_relate_pattern(): + g = shapely.linestrings([(0, 0), (1, 0), (1, 1)]) + polygon = shapely.box(0, 0, 2, 2) + assert shapely.relate(g, polygon) == "11F00F212" + assert shapely.relate_pattern(g, polygon, "11F00F212") + assert shapely.relate_pattern(g, polygon, "*********") + assert not shapely.relate_pattern(g, polygon, "F********") + + +def test_relate_pattern_empty(): + with ignore_invalid(shapely.geos_version < (3, 12, 0)): + # Empty geometries give 'invalid value encountered' in all predicates + # (see https://github.com/libgeos/geos/issues/515) + assert shapely.relate_pattern(empty, empty, "*" * 9).item() is True + + +@pytest.mark.parametrize("g1, g2", [(point, None), (None, point), (None, None)]) +def test_relate_pattern_none(g1, g2): + assert shapely.relate_pattern(g1, g2, "*" * 9).item() is False + + +def test_relate_pattern_incorrect_length(): + with pytest.raises(shapely.GEOSException, match="Should be length 9"): + shapely.relate_pattern(point, polygon, "**") + + with pytest.raises(shapely.GEOSException, match="Should be length 9"): + shapely.relate_pattern(point, polygon, "**********") + + +@pytest.mark.parametrize("pattern", [b"*********", 10, None]) +def test_relate_pattern_non_string(pattern): + with pytest.raises(TypeError, match="expected string"): + shapely.relate_pattern(point, polygon, pattern) + + +def test_relate_pattern_non_scalar(): + with pytest.raises(ValueError, match="only supports scalar"): + shapely.relate_pattern([point] * 2, polygon, ["*********"] * 2) + + +@pytest.mark.parametrize( + "geom, expected", + [ + (LinearRing([(0, 0), (0, 1), (1, 1), (0, 0)]), False), + (LinearRing([(0, 0), (1, 1), (0, 1), (0, 0)]), True), + (LineString([(0, 0), (0, 1), (1, 1), (0, 0)]), False), + (LineString([(0, 0), (1, 1), (0, 1), (0, 0)]), True), + (LineString([(0, 0), (1, 1), (0, 1)]), False), + (LineString([(0, 0), (0, 1), (1, 1)]), False), + (point, False), + (polygon, False), + (geometry_collection, False), + (None, False), + ], +) +def test_is_ccw(geom, expected): + assert shapely.is_ccw(geom) == expected + + +def _prepare_with_copy(geometry): + """Prepare without modifying in-place""" + geometry = shapely.transform(geometry, lambda x: x) # makes a copy + shapely.prepare(geometry) + return geometry + + +@pytest.mark.parametrize("a", all_types) +@pytest.mark.parametrize("func", BINARY_PREPARED_PREDICATES) +def test_binary_prepared(a, func): + with ignore_invalid(shapely.is_empty(a) and shapely.geos_version < (3, 12, 0)): + # Empty geometries give 'invalid value encountered' in all predicates + # (see https://github.com/libgeos/geos/issues/515) + actual = func(a, point) + result = func(_prepare_with_copy(a), point) + assert actual == result + + +@pytest.mark.parametrize("geometry", all_types) +def test_is_prepared_true(geometry): + assert shapely.is_prepared(_prepare_with_copy(geometry)) + + +@pytest.mark.parametrize("geometry", all_types + (None,)) +def test_is_prepared_false(geometry): + assert not shapely.is_prepared(geometry) + + +def test_contains_properly(): + # polygon contains itself, but does not properly contains itself + assert shapely.contains(polygon, polygon).item() is True + assert shapely.contains_properly(polygon, polygon).item() is False diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_ragged_array.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_ragged_array.py new file mode 100644 index 0000000000000000000000000000000000000000..8b540923c8669859228542846b3c899070e08417 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_ragged_array.py @@ -0,0 +1,665 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose + +import shapely +from shapely import MultiLineString, MultiPoint, MultiPolygon +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + empty_line_string, + empty_line_string_m, + empty_line_string_z, + empty_line_string_zm, + empty_multi_polygon_m, + empty_multi_polygon_z, + empty_multi_polygon_zm, + geometry_collection, + line_string, + line_string_m, + line_string_z, + line_string_zm, + linear_ring, + multi_line_string, + multi_line_string_m, + multi_line_string_z, + multi_line_string_zm, + multi_point, + multi_point_m, + multi_point_z, + multi_point_zm, + multi_polygon, + multi_polygon_m, + multi_polygon_z, + multi_polygon_zm, + point, + point_m, + point_z, + point_zm, + polygon, + polygon_m, + polygon_z, + polygon_zm, +) + +all_types = ( + point, + line_string, + polygon, + multi_point, + multi_line_string, + multi_polygon, +) + +all_types_z = ( + point_z, + line_string_z, + polygon_z, + multi_point_z, + multi_line_string_z, + multi_polygon_z, +) + +all_types_m = ( + point_m, + line_string_m, + polygon_m, + multi_point_m, + multi_line_string_m, + multi_polygon_m, +) + +all_types_zm = ( + point_zm, + line_string_zm, + polygon_zm, + multi_point_zm, + multi_line_string_zm, + multi_polygon_zm, +) + +all_types_dims_combos = all_types + all_types_z +if shapely.geos_version >= (3, 12, 0): + all_types_dims_combos = all_types_dims_combos + all_types_m + all_types_zm + +all_types_not_supported = ( + linear_ring, + geometry_collection, +) + + +@pytest.mark.parametrize("geom", all_types + all_types_z) +def test_roundtrip(geom): + actual = shapely.from_ragged_array(*shapely.to_ragged_array([geom, geom])) + assert_geometries_equal(actual, [geom, geom]) + + +@pytest.mark.parametrize("include_m", [None, True, False]) +@pytest.mark.parametrize("include_z", [None, True, False]) +@pytest.mark.parametrize("geom", all_types_dims_combos) +def test_to_ragged_array(geom, include_z, include_m): + _, coords, _ = shapely.to_ragged_array( + [geom, geom], include_z=include_z, include_m=include_m + ) + nan_dims = np.all(np.isnan(coords), axis=0).tolist() + expected = [False, False] # XY + has_z = geom.has_z + if include_z or (include_z is None and has_z): + expected.append(not has_z) # XYZ or XYZM + if shapely.geos_version >= (3, 12, 0): + has_m = geom.has_m + else: + has_m = False + if include_m or (include_m is None and has_m): + expected.append(not has_m) # XYM or XYZM + assert nan_dims == expected + + +def test_include_z_default(): + # corner cases for inferring dimensionality + + # mixed XY and XYZ -> XYZ + _, coords, _ = shapely.to_ragged_array([line_string, line_string_z]) + assert coords.shape[1] == 3 + + # only empties -> always 2D + _, coords, _ = shapely.to_ragged_array([empty_line_string]) + assert coords.shape[1] == 2 + _, coords, _ = shapely.to_ragged_array([empty_line_string_z]) + assert coords.shape[1] == 2 + # empty collection -> GEOS indicates 2D + _, coords, _ = shapely.to_ragged_array([empty_multi_polygon_z]) + assert coords.shape[1] == 2 + + +@pytest.mark.skipif(shapely.geos_version < (3, 12, 0), reason="GEOS < 3.12") +def test_include_m_default(): + # a few other corner cases for inferring dimensionality + + # mixed XY and XYM -> XYM + _, coords, _ = shapely.to_ragged_array([line_string, line_string_m]) + assert coords.shape[1] == 3 + + # mixed XY, XYM, and XYZM -> XYZM + _, coords, _ = shapely.to_ragged_array([line_string, line_string_m, line_string_zm]) + assert coords.shape[1] == 4 + + # only empties -> always 2D + _, coords, _ = shapely.to_ragged_array([empty_line_string_m]) + assert coords.shape[1] == 2 + _, coords, _ = shapely.to_ragged_array([empty_line_string_zm]) + assert coords.shape[1] == 2 + # empty collection -> GEOS indicates 2D + _, coords, _ = shapely.to_ragged_array([empty_multi_polygon_m]) + assert coords.shape[1] == 2 + _, coords, _ = shapely.to_ragged_array([empty_multi_polygon_zm]) + assert coords.shape[1] == 2 + + +@pytest.mark.parametrize("geom", all_types) +def test_read_only_arrays(geom): + # https://github.com/shapely/shapely/pull/1744 + typ, coords, offsets = shapely.to_ragged_array([geom, geom]) + coords.flags.writeable = False + for arr in offsets: + arr.flags.writeable = False + result = shapely.from_ragged_array(typ, coords, offsets) + assert_geometries_equal(result, [geom, geom]) + + +@pytest.mark.parametrize("geom", all_types_not_supported) +def test_raise_geometry_type(geom): + with pytest.raises(ValueError): + shapely.to_ragged_array([geom, geom]) + + +def test_points(): + arr = shapely.from_wkt( + [ + "POINT (0 0)", + "POINT (1 1)", + "POINT EMPTY", + "POINT EMPTY", + "POINT (4 4)", + None, + "POINT EMPTY", + ] + ) + typ, result, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [0, 0], + [1, 1], + [np.nan, np.nan], + [np.nan, np.nan], + [4, 4], + [np.nan, np.nan], + [np.nan, np.nan], + ] + ) + assert typ == shapely.GeometryType.POINT + assert len(result) == len(arr) + assert_allclose(result, expected) + assert len(offsets) == 0 + + geoms = shapely.from_ragged_array(typ, result) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("POINT EMPTY") + assert_geometries_equal(geoms, arr) + + +def test_linestrings(): + arr = shapely.from_wkt( + [ + "LINESTRING (30 10, 10 30, 40 40)", + "LINESTRING (40 40, 30 30, 40 20, 30 10)", + "LINESTRING EMPTY", + "LINESTRING EMPTY", + "LINESTRING (10 10, 20 20, 10 40)", + None, + "LINESTRING EMPTY", + ] + ) + typ, coords, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [30.0, 10.0], + [10.0, 30.0], + [40.0, 40.0], + [40.0, 40.0], + [30.0, 30.0], + [40.0, 20.0], + [30.0, 10.0], + [10.0, 10.0], + [20.0, 20.0], + [10.0, 40.0], + ] + ) + expected_offsets = np.array([0, 3, 7, 7, 7, 10, 10, 10], dtype="int32") + assert typ == shapely.GeometryType.LINESTRING + assert_allclose(coords, expected) + assert len(offsets) == 1 + assert offsets[0].dtype == np.int32 + assert_allclose(offsets[0], expected_offsets) + + result = shapely.from_ragged_array(typ, coords, offsets) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("LINESTRING EMPTY") + assert_geometries_equal(result, arr) + + # sliced + offsets_sliced = (offsets[0][1:],) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[1:]) + + offsets_sliced = (offsets[0][:-1],) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[:-1]) + + +def test_polygons(): + arr = shapely.from_wkt( + [ + "POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))", + "POLYGON ((35 10, 45 45, 15 40, 10 20, 35 10), (20 30, 35 35, 30 20, 20 30))", # noqa: E501 + "POLYGON EMPTY", + "POLYGON EMPTY", + "POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))", + None, + "POLYGON EMPTY", + ] + ) + typ, coords, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [30.0, 10.0], + [40.0, 40.0], + [20.0, 40.0], + [10.0, 20.0], + [30.0, 10.0], + [35.0, 10.0], + [45.0, 45.0], + [15.0, 40.0], + [10.0, 20.0], + [35.0, 10.0], + [20.0, 30.0], + [35.0, 35.0], + [30.0, 20.0], + [20.0, 30.0], + [30.0, 10.0], + [40.0, 40.0], + [20.0, 40.0], + [10.0, 20.0], + [30.0, 10.0], + ] + ) + expected_offsets1 = np.array([0, 5, 10, 14, 19]) + expected_offsets2 = np.array([0, 1, 3, 3, 3, 4, 4, 4]) + + assert typ == shapely.GeometryType.POLYGON + assert_allclose(coords, expected) + assert len(offsets) == 2 + assert offsets[0].dtype == np.int32 + assert offsets[1].dtype == np.int32 + assert_allclose(offsets[0], expected_offsets1) + assert_allclose(offsets[1], expected_offsets2) + + result = shapely.from_ragged_array(typ, coords, offsets) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("POLYGON EMPTY") + assert_geometries_equal(result, arr) + + # sliced: + # - indices into the coordinate array for the whole buffer + # - indices into the ring array for *just* the sliced part + offsets_sliced = (offsets[0], offsets[1][1:]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[1:]) + + offsets_sliced = (offsets[0], offsets[1][:-1]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[:-1]) + + +def test_multipoints(): + arr = shapely.from_wkt( + [ + "MULTIPOINT (10 40, 40 30, 20 20, 30 10)", + "MULTIPOINT (30 10)", + "MULTIPOINT EMPTY", + "MULTIPOINT EMPTY", + "MULTIPOINT (30 10, 10 30, 40 40)", + None, + "MULTIPOINT EMPTY", + ] + ) + typ, coords, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [10.0, 40.0], + [40.0, 30.0], + [20.0, 20.0], + [30.0, 10.0], + [30.0, 10.0], + [30.0, 10.0], + [10.0, 30.0], + [40.0, 40.0], + ] + ) + expected_offsets = np.array([0, 4, 5, 5, 5, 8, 8, 8]) + + assert typ == shapely.GeometryType.MULTIPOINT + assert_allclose(coords, expected) + assert len(offsets) == 1 + assert offsets[0].dtype == np.int32 + assert_allclose(offsets[0], expected_offsets) + + result = shapely.from_ragged_array(typ, coords, offsets) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("MULTIPOINT EMPTY") + assert_geometries_equal(result, arr) + + # sliced: + offsets_sliced = (offsets[0][1:],) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[1:]) + + offsets_sliced = (offsets[0][:-1],) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[:-1]) + + +def test_multilinestrings(): + arr = shapely.from_wkt( + [ + "MULTILINESTRING ((30 10, 10 30, 40 40))", + "MULTILINESTRING ((10 10, 20 20, 10 40), (40 40, 30 30, 40 20, 30 10))", + "MULTILINESTRING EMPTY", + "MULTILINESTRING EMPTY", + "MULTILINESTRING ((35 10, 45 45), (15 40, 10 20), (30 10, 10 30, 40 40))", + None, + "MULTILINESTRING EMPTY", + ] + ) + typ, coords, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [30.0, 10.0], + [10.0, 30.0], + [40.0, 40.0], + [10.0, 10.0], + [20.0, 20.0], + [10.0, 40.0], + [40.0, 40.0], + [30.0, 30.0], + [40.0, 20.0], + [30.0, 10.0], + [35.0, 10.0], + [45.0, 45.0], + [15.0, 40.0], + [10.0, 20.0], + [30.0, 10.0], + [10.0, 30.0], + [40.0, 40.0], + ] + ) + expected_offsets1 = np.array([0, 3, 6, 10, 12, 14, 17]) + expected_offsets2 = np.array([0, 1, 3, 3, 3, 6, 6, 6]) + + assert typ == shapely.GeometryType.MULTILINESTRING + assert_allclose(coords, expected) + assert len(offsets) == 2 + assert offsets[0].dtype == np.int32 + assert offsets[1].dtype == np.int32 + assert_allclose(offsets[0], expected_offsets1) + assert_allclose(offsets[1], expected_offsets2) + + result = shapely.from_ragged_array(typ, coords, offsets) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("MULTILINESTRING EMPTY") + assert_geometries_equal(result, arr) + + # sliced: + # - indices into the coordinate array for the whole buffer + # - indices into the line parts for *just* the sliced part + offsets_sliced = (offsets[0], offsets[1][1:]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[1:]) + + offsets_sliced = (offsets[0], offsets[1][:-1]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[:-1]) + + +def test_multipolygons(): + arr = shapely.from_wkt( + [ + "MULTIPOLYGON (((35 10, 45 45, 15 40, 10 20, 35 10), (20 30, 35 35, 30 20, 20 30)))", # noqa: E501 + "MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)), ((20 35, 10 30, 10 10, 30 5, 45 20, 20 35), (30 20, 20 15, 20 25, 30 20)))", # noqa: E501 + "MULTIPOLYGON EMPTY", + "MULTIPOLYGON EMPTY", + "MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)))", + None, + "MULTIPOLYGON EMPTY", + ] + ) + typ, coords, offsets = shapely.to_ragged_array(arr) + expected = np.array( + [ + [35.0, 10.0], + [45.0, 45.0], + [15.0, 40.0], + [10.0, 20.0], + [35.0, 10.0], + [20.0, 30.0], + [35.0, 35.0], + [30.0, 20.0], + [20.0, 30.0], + [40.0, 40.0], + [20.0, 45.0], + [45.0, 30.0], + [40.0, 40.0], + [20.0, 35.0], + [10.0, 30.0], + [10.0, 10.0], + [30.0, 5.0], + [45.0, 20.0], + [20.0, 35.0], + [30.0, 20.0], + [20.0, 15.0], + [20.0, 25.0], + [30.0, 20.0], + [40.0, 40.0], + [20.0, 45.0], + [45.0, 30.0], + [40.0, 40.0], + ] + ) + expected_offsets1 = np.array([0, 5, 9, 13, 19, 23, 27]) + expected_offsets2 = np.array([0, 2, 3, 5, 6]) + expected_offsets3 = np.array([0, 1, 3, 3, 3, 4, 4, 4]) + + assert typ == shapely.GeometryType.MULTIPOLYGON + assert_allclose(coords, expected) + assert len(offsets) == 3 + assert offsets[0].dtype == np.int32 + assert offsets[1].dtype == np.int32 + assert offsets[2].dtype == np.int32 + assert_allclose(offsets[0], expected_offsets1) + assert_allclose(offsets[1], expected_offsets2) + assert_allclose(offsets[2], expected_offsets3) + + result = shapely.from_ragged_array(typ, coords, offsets) + # in a roundtrip, missing geometries come back as empty + arr[-2] = shapely.from_wkt("MULTIPOLYGON EMPTY") + assert_geometries_equal(result, arr) + + # sliced: + offsets_sliced = (offsets[0], offsets[1], offsets[2][1:]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[1:]) + + offsets_sliced = (offsets[0], offsets[1], offsets[2][:-3]) + result = shapely.from_ragged_array(typ, coords, offsets_sliced) + assert_geometries_equal(result, arr[:-3]) + print(result) + + +def test_mixture_point_multipoint(): + typ, coords, offsets = shapely.to_ragged_array([point, multi_point]) + assert typ == shapely.GeometryType.MULTIPOINT + result = shapely.from_ragged_array(typ, coords, offsets) + expected = np.array([MultiPoint([point]), multi_point]) + assert_geometries_equal(result, expected) + + +def test_mixture_linestring_multilinestring(): + typ, coords, offsets = shapely.to_ragged_array([line_string, multi_line_string]) + assert typ == shapely.GeometryType.MULTILINESTRING + result = shapely.from_ragged_array(typ, coords, offsets) + expected = np.array([MultiLineString([line_string]), multi_line_string]) + assert_geometries_equal(result, expected) + + +def test_mixture_polygon_multipolygon(): + typ, coords, offsets = shapely.to_ragged_array([polygon, multi_polygon]) + assert typ == shapely.GeometryType.MULTIPOLYGON + result = shapely.from_ragged_array(typ, coords, offsets) + expected = np.array([MultiPolygon([polygon]), multi_polygon]) + assert_geometries_equal(result, expected) + + +def test_from_ragged_incorrect_rings_short(): + # too few coordinates for linearring + coords = np.array([[0, 0], [1, 1]], dtype="float64") + offsets1 = np.array([0, 2]) + offsets2 = np.array([0, 1]) + offsets3 = np.array([0, 1]) + + with pytest.raises( + ValueError, match="A linearring requires at least 4 coordinates" + ): + shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) + + with pytest.raises( + ValueError, match="A linearring requires at least 4 coordinates" + ): + shapely.from_ragged_array( + shapely.GeometryType.POLYGON, coords, (offsets1, offsets2) + ) + + +def test_from_ragged_incorrect_rings_unclosed(): + # NaNs cause the ring to be unclosed + coords = np.full((4, 2), np.nan) + offsets1 = np.array([0, 4]) + offsets2 = np.array([0, 1]) + offsets3 = np.array([0, 1]) + + with pytest.raises( + shapely.GEOSException, + match="Points of LinearRing do not form a closed linestring", + ): + shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) + + with pytest.raises( + shapely.GEOSException, + match="Points of LinearRing do not form a closed linestring", + ): + shapely.from_ragged_array( + shapely.GeometryType.POLYGON, coords, (offsets1, offsets2) + ) + + +def test_from_ragged_wrong_offsets(): + with pytest.raises(ValueError, match="'offsets' must be provided"): + shapely.from_ragged_array( + shapely.GeometryType.LINESTRING, np.array([[0, 0], [0, 1]]) + ) + + with pytest.raises(ValueError, match="'offsets' should not be provided"): + shapely.from_ragged_array( + shapely.GeometryType.POINT, + np.array([[0, 0], [0, 1]]), + offsets=(np.array([0, 1]),), + ) + + +def test_from_ragged_crash_2284(): + # caused segfault in shapely 2.1.0 + # https://github.com/shapely/shapely/discussions/2284 + + # one of the geometries has more rings than the total number of geometries + coords = np.random.default_rng().random(120).reshape((60, 2)) + offsets1 = np.array([0, 10, 20, 30, 40, 50, 60]) + offsets2 = np.array([0, 1, 5, 6]) + + for _ in range(10): + polygons = shapely.from_ragged_array( + shapely.GeometryType.POLYGON, coords, (offsets1, offsets2) + ) + # just ensure it didn't crash + assert len(polygons) == 3 + + offsets3 = np.array([0, 3]) + for _ in range(10): + polygons = shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) + # just ensure it didn't crash + assert len(polygons) == 1 + + +def test_from_ragged_wrong_offsets_values(): + # caused segfault in shapely 2.1.0 + + # outer offsets indicates more rings than the shape of the ring offsets + coords = np.random.default_rng().random(70).reshape((35, 2)) + offsets1 = np.array([0, 10, 20], dtype=np.uint32) + offsets2 = np.array([0, 1, 5], dtype=np.uint32) + offsets3 = np.array([0, 2]) + + with pytest.raises( + ValueError, match="Number of rings indicated by the geometry offsets" + ): + shapely.from_ragged_array( + shapely.GeometryType.POLYGON, coords, (offsets1, offsets2) + ) + + with pytest.raises( + ValueError, match="Number of rings indicated by the part offsets" + ): + shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) + + # inner offsets indicating more coordinats that the shape of the coordinates + coords = np.random.default_rng().random(70).reshape((35, 2)) + offsets1 = np.array([0, 10, 40], dtype=np.uint32) + offsets2 = np.array([0, 1, 2], dtype=np.uint32) + + with pytest.raises( + ValueError, match="Number of coordinates indicated by the linear offsets" + ): + shapely.from_ragged_array( + shapely.GeometryType.POLYGON, coords, (offsets1, offsets2) + ) + + with pytest.raises( + ValueError, match="Number of coordinates indicated by the linear offsets" + ): + shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) + + # outer multipolygon offsets indicating too many parts + offsets3 = np.array([0, 3]) + with pytest.raises( + ValueError, match="Number of geometry parts indicated by the geometry offsets" + ): + shapely.from_ragged_array( + shapely.GeometryType.MULTIPOLYGON, coords, (offsets1, offsets2, offsets3) + ) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_set_operations.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_set_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..09144fdf816993efea196b8002f363ae2db2c2cd --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_set_operations.py @@ -0,0 +1,481 @@ +import numpy as np +import pytest + +import shapely +from shapely import Geometry, GeometryCollection, Polygon +from shapely.testing import assert_geometries_equal +from shapely.tests.common import all_types, empty, ignore_invalid, point, polygon + +pytestmark = pytest.mark.filterwarnings( + "ignore:The symmetric_difference_all function:DeprecationWarning" +) + +# fixed-precision operations raise GEOS exceptions on mixed dimension geometry +# collections +all_single_types = np.array(all_types)[ + ~shapely.is_empty(all_types) + & (shapely.get_type_id(all_types) != shapely.GeometryType.GEOMETRYCOLLECTION) +] + +SET_OPERATIONS = ( + shapely.difference, + shapely.intersection, + shapely.symmetric_difference, + shapely.union, + # shapely.coverage_union is tested separately +) + +REDUCE_SET_OPERATIONS = ( + (shapely.intersection_all, shapely.intersection), + (shapely.symmetric_difference_all, shapely.symmetric_difference), + (shapely.union_all, shapely.union), + # shapely.coverage_union_all, shapely.coverage_union) is tested separately +) + +# operations that support fixed precision +REDUCE_SET_OPERATIONS_PREC = ((shapely.union_all, shapely.union),) + +if shapely.geos_version >= (3, 12, 0): + SET_OPERATIONS += (shapely.disjoint_subset_union,) + REDUCE_SET_OPERATIONS += ( + (shapely.disjoint_subset_union_all, shapely.disjoint_subset_union), + ) + +reduce_test_data = [ + shapely.box(0, 0, 5, 5), + shapely.box(2, 2, 7, 7), + shapely.box(4, 4, 9, 9), + shapely.box(5, 5, 10, 10), +] + +non_polygon_types = np.array(all_types)[ + ~shapely.is_empty(all_types) & (shapely.get_dimensions(all_types) != 2) +] + + +@pytest.mark.parametrize("a", all_types) +@pytest.mark.parametrize("func", SET_OPERATIONS) +def test_set_operation_array(a, func): + if ( + func is shapely.difference + and a.geom_type == "GeometryCollection" + and shapely.get_num_geometries(a) == 2 + and shapely.geos_version == (3, 9, 5) + ): + pytest.xfail("GEOS 3.9.5 crashes with mixed collection") + actual = func(a, point) + assert isinstance(actual, Geometry) + + actual = func([a, a], point) + assert actual.shape == (2,) + assert isinstance(actual[0], Geometry) + + +@pytest.mark.parametrize("func", SET_OPERATIONS) +def test_set_operation_prec_nonscalar_grid_size(func): + if func is shapely.disjoint_subset_union: + pytest.skip("disjoint_subset_union does not support grid_size") + with pytest.raises( + ValueError, match="grid_size parameter only accepts scalar values" + ): + func(point, point, grid_size=[1]) + + +@pytest.mark.parametrize("a", all_single_types) +@pytest.mark.parametrize("func", SET_OPERATIONS) +@pytest.mark.parametrize("grid_size", [0, 1, 2]) +def test_set_operation_prec_array(a, func, grid_size): + if func is shapely.disjoint_subset_union: + pytest.skip("disjoint_subset_union does not support grid_size") + actual = func([a, a], point, grid_size=grid_size) + assert actual.shape == (2,) + assert isinstance(actual[0], Geometry) + + # results should match the operation when the precision is previously set + # to same grid_size + b = shapely.set_precision(a, grid_size=grid_size) + point2 = shapely.set_precision(point, grid_size=grid_size) + expected = func([b, b], point2) + + assert shapely.equals(shapely.normalize(actual), shapely.normalize(expected)).all() + + +@pytest.mark.parametrize("n", range(1, 5)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_1dim(n, func, related_func): + actual = func(reduce_test_data[:n]) + # perform the reduction in a python loop and compare + expected = reduce_test_data[0] + for i in range(1, n): + expected = related_func(expected, reduce_test_data[i]) + assert shapely.equals(actual, expected) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_single_geom(func, related_func): + geom = shapely.Point(1, 1) + actual = func([geom, None, None]) + assert shapely.equals(actual, geom) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_axis(func, related_func): + data = [[point] * 2] * 3 # shape = (3, 2) + actual = func(data, axis=None) # default + assert isinstance(actual, Geometry) # scalar output + actual = func(data, axis=0) + assert actual.shape == (2,) + actual = func(data, axis=1) + assert actual.shape == (3,) + actual = func(data, axis=-1) + assert actual.shape == (3,) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_empty(func, related_func): + assert func(np.empty((0,), dtype=object)) == empty + arr_empty_2D = np.empty((0, 2), dtype=object) + assert func(arr_empty_2D) == empty + assert func(arr_empty_2D, axis=0).tolist() == [empty] * 2 + assert func(arr_empty_2D, axis=1).tolist() == [] + + +@pytest.mark.parametrize("none_position", range(3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_one_none(func, related_func, none_position): + # API change: before, intersection_all and symmetric_difference_all returned + # None if any input geometry was None. + # The new behaviour is to ignore None values. + test_data = reduce_test_data[:2] + test_data.insert(none_position, None) + actual = func(test_data) + expected = related_func(reduce_test_data[0], reduce_test_data[1]) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("none_position", range(3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_two_none(func, related_func, none_position): + test_data = reduce_test_data[:2] + test_data.insert(none_position, None) + test_data.insert(none_position, None) + actual = func(test_data) + expected = related_func(reduce_test_data[0], reduce_test_data[1]) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_some_none_len2(func, related_func): + # in a previous implementation, this would take a different code path + # and return wrong result + assert func([empty, None]) == empty + + +@pytest.mark.parametrize("n", range(1, 3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_all_none(n, func, related_func): + assert_geometries_equal(func([None] * n), GeometryCollection([])) + + +@pytest.mark.parametrize("n", range(1, 3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS) +def test_set_operation_reduce_all_none_arr(n, func, related_func): + assert func([[None] * n] * 2, axis=1).tolist() == [empty, empty] + assert func([[None] * 2] * n, axis=0).tolist() == [empty, empty] + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_nonscalar_grid_size(func, related_func): + with pytest.raises( + ValueError, match="grid_size parameter only accepts scalar values" + ): + func([point, point], grid_size=[1]) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_grid_size_nan(func, related_func): + actual = func([point, point], grid_size=np.nan) + assert actual is None + + +@pytest.mark.parametrize("n", range(1, 5)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +@pytest.mark.parametrize("grid_size", [0, 1]) +def test_set_operation_prec_reduce_1dim(n, func, related_func, grid_size): + actual = func(reduce_test_data[:n], grid_size=grid_size) + # perform the reduction in a python loop and compare + expected = reduce_test_data[0] + for i in range(1, n): + expected = related_func(expected, reduce_test_data[i], grid_size=grid_size) + + assert shapely.equals(actual, expected) + + +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_axis(func, related_func): + data = [[point] * 2] * 3 # shape = (3, 2) + actual = func(data, grid_size=1, axis=None) # default + assert isinstance(actual, Geometry) # scalar output + actual = func(data, grid_size=1, axis=0) + assert actual.shape == (2,) + actual = func(data, grid_size=1, axis=1) + assert actual.shape == (3,) + actual = func(data, grid_size=1, axis=-1) + assert actual.shape == (3,) + + +@pytest.mark.parametrize("none_position", range(3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_one_none(func, related_func, none_position): + test_data = reduce_test_data[:2] + test_data.insert(none_position, None) + actual = func(test_data, grid_size=1) + expected = related_func(reduce_test_data[0], reduce_test_data[1], grid_size=1) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("none_position", range(3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_two_none(func, related_func, none_position): + test_data = reduce_test_data[:2] + test_data.insert(none_position, None) + test_data.insert(none_position, None) + actual = func(test_data, grid_size=1) + expected = related_func(reduce_test_data[0], reduce_test_data[1], grid_size=1) + assert_geometries_equal(actual, expected) + + +@pytest.mark.parametrize("n", range(1, 3)) +@pytest.mark.parametrize("func, related_func", REDUCE_SET_OPERATIONS_PREC) +def test_set_operation_prec_reduce_all_none(n, func, related_func): + assert_geometries_equal(func([None] * n, grid_size=1), GeometryCollection([])) + + +@pytest.mark.parametrize("n", range(1, 4)) +def test_coverage_union_reduce_1dim(n): + """ + This is tested separately from other set operations as it expects only + non-overlapping polygons + """ + test_data = [ + shapely.box(0, 0, 1, 1), + shapely.box(1, 0, 2, 1), + shapely.box(2, 0, 3, 1), + ] + actual = shapely.coverage_union_all(test_data[:n]) + # perform the reduction in a python loop and compare + expected = test_data[0] + for i in range(1, n): + expected = shapely.coverage_union(expected, test_data[i]) + assert_geometries_equal(actual, expected, normalize=True) + + +def test_coverage_union_reduce_axis(): + # shape = (3, 2), all polygons - none of them overlapping + data = [[shapely.box(i, j, i + 1, j + 1) for i in range(2)] for j in range(3)] + actual = shapely.coverage_union_all(data, axis=None) # default + assert isinstance(actual, Geometry) + actual = shapely.coverage_union_all(data, axis=0) + assert actual.shape == (2,) + actual = shapely.coverage_union_all(data, axis=1) + assert actual.shape == (3,) + actual = shapely.coverage_union_all(data, axis=-1) + assert actual.shape == (3,) + + +def test_coverage_union_overlapping_inputs(): + polygon = Polygon([(1, 1), (1, 0), (0, 0), (0, 1), (1, 1)]) + other = Polygon([(1, 0), (0.9, 1), (2, 1), (2, 0), (1, 0)]) + + if shapely.geos_version >= (3, 14, 0): + # Overlapping polygons raise an error again + with pytest.raises(shapely.GEOSException, match="TopologyException"): + shapely.coverage_union(polygon, other) + elif shapely.geos_version >= (3, 12, 0): + # Return mostly unchanged output + result = shapely.coverage_union(polygon, other) + expected = shapely.multipolygons([polygon, other]) + assert_geometries_equal(result, expected, normalize=True) + else: + # Overlapping polygons raise an error + with pytest.raises( + shapely.GEOSException, + match="CoverageUnion cannot process incorrectly noded inputs.", + ): + shapely.coverage_union(polygon, other) + + +@pytest.mark.parametrize( + "geom_1, geom_2", + # All possible polygon, non_polygon combinations + [[polygon, non_polygon] for non_polygon in non_polygon_types] + # All possible non_polygon, non_polygon combinations + + [ + [non_polygon_1, non_polygon_2] + for non_polygon_1 in non_polygon_types + for non_polygon_2 in non_polygon_types + ], +) +def test_coverage_union_non_polygon_inputs(geom_1, geom_2): + if shapely.geos_version >= (3, 12, 0): + + def effective_geom_types(geom): + if hasattr(geom, "geoms") and not geom.is_empty: + gts = set() + for part in geom.geoms: + gts |= effective_geom_types(part) + return gts + return {geom.geom_type.lstrip("Multi").replace("LinearRing", "LineString")} + + geom_types_1 = effective_geom_types(geom_1) + geom_types_2 = effective_geom_types(geom_2) + if len(geom_types_1) == 1 and geom_types_1 == geom_types_2: + with ignore_invalid(): + # these show "invalid value encountered in coverage_union" + result = shapely.coverage_union(geom_1, geom_2) + assert geom_types_1 == effective_geom_types(result) + else: + with pytest.raises( + shapely.GEOSException, match="Overlay input is mixed-dimension" + ): + shapely.coverage_union(geom_1, geom_2) + else: + # Non polygon geometries raise an error + with pytest.raises( + shapely.GEOSException, match="Unhandled geometry type in CoverageUnion." + ): + shapely.coverage_union(geom_1, geom_2) + + +@pytest.mark.parametrize( + "geom,grid_size,expected", + [ + # floating point precision, expect no change + ( + [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)], + 0, + Polygon( + ( + (0, 0.2), + (0, 10), + (5.1, 10), + (5.1, 0.2), + (5, 0.2), + (5, 0.1), + (0.1, 0.1), + (0.1, 0.2), + (0, 0.2), + ) + ), + ), + # grid_size is at effective precision, expect no change + ( + [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)], + 0.1, + Polygon( + ( + (0, 0.2), + (0, 10), + (5.1, 10), + (5.1, 0.2), + (5, 0.2), + (5, 0.1), + (0.1, 0.1), + (0.1, 0.2), + (0, 0.2), + ) + ), + ), + # grid_size forces rounding to nearest integer + ( + [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)], + 1, + Polygon([(0, 5), (0, 10), (5, 10), (5, 5), (5, 0), (0, 0), (0, 5)]), + ), + # grid_size much larger than effective precision causes rounding to nearest + # multiple of 10 + ( + [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)], + 10, + Polygon([(0, 10), (10, 10), (10, 0), (0, 0), (0, 10)]), + ), + # grid_size is so large that polygons collapse to empty + ( + [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)], + 100, + Polygon(), + ), + ], +) +def test_union_all_prec(geom, grid_size, expected): + actual = shapely.union_all(geom, grid_size=grid_size) + assert shapely.equals(actual, expected) + + +def test_uary_union_alias(): + geoms = [shapely.box(0.1, 0.1, 5, 5), shapely.box(0, 0.2, 5.1, 10)] + actual = shapely.unary_union(geoms, grid_size=1) + expected = shapely.union_all(geoms, grid_size=1) + assert shapely.equals(actual, expected) + + +def test_difference_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `grid_size` for `difference` is deprecated" + ): + shapely.difference(point, point, None) + + +def test_intersection_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `grid_size` for `intersection` is deprecated" + ): + shapely.intersection(point, point, None) + + +def test_intersection_all_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `axis` for `intersection_all` is deprecated" + ): + shapely.intersection_all([point, point], None) + + +def test_symmetric_difference_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `grid_size` for `symmetric_difference` is deprecated" + ): + shapely.symmetric_difference(point, point, None) + + +def test_symmetric_difference_all_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `axis` for `symmetric_difference_all` is deprecated" + ): + shapely.symmetric_difference_all([point, point], None) + + +def test_union_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `grid_size` for `union` is deprecated" + ): + shapely.union(point, point, None) + + +def test_union_all_deprecate_positional(): + with pytest.deprecated_call( + match="positional argument `grid_size` for `union_all` is deprecated" + ): + shapely.union_all([point, point], None) + with pytest.deprecated_call( + match="positional arguments `grid_size` and `axis` for `union_all` " + "are deprecated" + ): + shapely.union_all([point, point], None, None) + + +def test_coverage_union_all_deprecate_positional(): + data = [shapely.box(0, 0, 1, 1), shapely.box(1, 0, 2, 1)] + with pytest.deprecated_call( + match="positional argument `axis` for `coverage_union_all` is deprecated" + ): + shapely.coverage_union_all(data, None) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_strtree.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_strtree.py new file mode 100644 index 0000000000000000000000000000000000000000..991191717bad108dc3fa77d684b76cbe580288bf --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_strtree.py @@ -0,0 +1,1964 @@ +import itertools +import math +import pickle +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +import shapely +from shapely import LineString, MultiPoint, Point, STRtree, box, geos_version +from shapely.errors import UnsupportedGEOSVersionError +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + empty, + empty_line_string, + empty_point, + ignore_invalid, + point, +) + +# the distance between 2 points spaced at whole numbers along a diagonal +HALF_UNIT_DIAG = math.sqrt(2) / 2 +EPS = 1e-9 + + +@pytest.fixture(scope="session") +def tree(): + geoms = shapely.points(np.arange(10), np.arange(10)) + yield STRtree(geoms) + + +@pytest.fixture(scope="session") +def line_tree(): + x = np.arange(10) + y = np.arange(10) + offset = 1 + geoms = shapely.linestrings(np.array([[x, x + offset], [y, y + offset]]).T) + yield STRtree(geoms) + + +@pytest.fixture(scope="session") +def poly_tree(): + # create buffers so that midpoint between two buffers intersects + # each buffer. NOTE: add EPS to help mitigate rounding errors at midpoint. + geoms = shapely.buffer( + shapely.points(np.arange(10), np.arange(10)), HALF_UNIT_DIAG + EPS, quad_segs=32 + ) + yield STRtree(geoms) + + +@pytest.mark.parametrize( + "geometry,count, hits", + [ + # Empty array produces empty tree + ([], 0, 0), + ([point], 1, 1), + # None geometries are ignored when creating tree + ([None], 0, 0), + ([point, None], 1, 1), + # empty geometries are ignored when creating tree + ([empty, empty_point, empty_line_string], 0, 0), + # only the valid geometry should have a hit + ([empty, point, empty_point, empty_line_string], 1, 1), + ], +) +def test_init(geometry, count, hits): + tree = STRtree(geometry) + assert len(tree) == count + assert tree.query(box(0, 0, 100, 100)).size == hits + + +def test_init_with_invalid_geometry(): + with pytest.raises(TypeError): + STRtree(["Not a geometry"]) + + +def test_references(): + point1 = Point() + point2 = Point(0, 1) + + geoms = [point1, point2] + tree = STRtree(geoms) + + point1 = None + point2 = None + + import gc + + gc.collect() + + # query after freeing geometries does not lead to segfault + assert tree.query(box(0, 0, 1, 1)).tolist() == [1] + + +def test_flush_geometries(): + arr = shapely.points(np.arange(10), np.arange(10)) + tree = STRtree(arr) + + # Dereference geometries + arr[:] = None + import gc + + gc.collect() + # Still it does not lead to a segfault + tree.query(point) + + +def test_geometries_property(): + arr = np.array([point]) + tree = STRtree(arr) + assert_geometries_equal(arr, tree.geometries) + + # modifying elements of input should not modify tree.geometries + arr[0] = shapely.Point(0, 0) + assert_geometries_equal(point, tree.geometries[0]) + + +def test_pickle_persistence(tmp_path): + # write the pickeled tree to another process; the process should not crash + tree = STRtree([Point(i, i).buffer(0.1) for i in range(3)]) + + pickled_strtree = pickle.dumps(tree) + unpickle_script = """ +import pickle +import sys + +from shapely import Point + +pickled_strtree = sys.stdin.buffer.read() +print("received pickled strtree:", repr(pickled_strtree)) +tree = pickle.loads(pickled_strtree) + +tree.query(Point(0, 0)) +tree.nearest(Point(0, 0)) +print("done") +""" + + filename = tmp_path / "unpickle-strtree.py" + with open(filename, "w") as out: + out.write(unpickle_script) + + proc = subprocess.Popen( + [sys.executable, str(filename)], + stdin=subprocess.PIPE, + ) + proc.communicate(input=pickled_strtree) + proc.wait() + assert proc.returncode == 0 + + +@pytest.mark.parametrize( + "geometry", + [ + "I am not a geometry", + ["I am not a geometry"], + [Point(0, 0), "still not a geometry"], + [[], "in a mixed array", 1], + ], +) +@pytest.mark.filterwarnings("ignore:Creating an ndarray from ragged nested sequences:") +def test_query_invalid_geometry(tree, geometry): + with pytest.raises((TypeError, ValueError)): + tree.query(geometry) + + +def test_query_invalid_dimension(tree): + with pytest.raises(TypeError, match="Array should be one dimensional"): + tree.query([[Point(0.5, 0.5)]]) + + +@pytest.mark.parametrize( + "tree_geometry, geometry,expected", + [ + # Empty tree returns no results + ([], point, []), + ([], [point], [[], []]), + ([], None, []), + ([], [None], [[], []]), + # Tree with only None returns no results + ([None], point, []), + ([None], [point], [[], []]), + ([None], None, []), + ([None], [None], [[], []]), + # querying with None returns no results + ([point], None, []), + ([point], [None], [[], []]), + # Empty is included in the tree, but ignored when querying the tree + ([empty], empty, []), + ([empty], [empty], [[], []]), + ([empty], point, []), + ([empty], [point], [[], []]), + ([point, empty], empty, []), + ([point, empty], [empty], [[], []]), + # None and empty are ignored in the tree, but the index of the valid + # geometry should be retained. + ([None, point], box(0, 0, 10, 10), [1]), + ([None, point], [box(0, 0, 10, 10)], [[0], [1]]), + ([None, empty, point], box(0, 0, 10, 10), [2]), + ([point, None, point], box(0, 0, 10, 10), [0, 2]), + ([point, None, point], [box(0, 0, 10, 10)], [[0, 0], [0, 2]]), + # Only the non-empty query geometry gets hits + ([empty, point], [empty, point], [[1], [1]]), + ( + [empty, empty_point, empty_line_string, point], + [empty, empty_point, empty_line_string, point], + [[3], [3]], + ), + ], +) +def test_query_with_none_and_empty(tree_geometry, geometry, expected): + tree = STRtree(tree_geometry) + assert_array_equal(tree.query(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # first and last points intersect + ( + [Point(1, 1), Point(-1, -1), Point(2, 2)], + [[0, 2], [1, 2]], + ), + # box contains points + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # bigger box contains more points + (box(5, 5, 15, 15), [5, 6, 7, 8, 9]), + ([box(5, 5, 15, 15)], [[0, 0, 0, 0, 0], [5, 6, 7, 8, 9]]), + # first and last boxes contains points + ( + [box(0, 0, 1, 1), box(100, 100, 110, 110), box(5, 5, 15, 15)], + [[0, 0, 2, 2, 2, 2, 2], [0, 1, 5, 6, 7, 8, 9]], + ), + # envelope of buffer contains points + (shapely.buffer(Point(3, 3), 1), [2, 3, 4]), + ([shapely.buffer(Point(3, 3), 1)], [[0, 0, 0], [2, 3, 4]]), + # envelope of points contains points + (MultiPoint([[5, 7], [7, 5]]), [5, 6, 7]), + ([MultiPoint([[5, 7], [7, 5]])], [[0, 0, 0], [5, 6, 7]]), + ], +) +def test_query_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects first line + (Point(0, 0), [0]), + ([Point(0, 0)], [[0], [0]]), + (Point(0.5, 0.5), [0]), + ([Point(0.5, 0.5)], [[0], [0]]), + # point within envelope of first line + (Point(0, 0.5), [0]), + ([Point(0, 0.5)], [[0], [0]]), + # point at shared vertex between 2 lines + (Point(1, 1), [0, 1]), + ([Point(1, 1)], [[0, 0], [0, 1]]), + # box overlaps envelope of first 2 lines (touches edge of 1) + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # envelope of buffer overlaps envelope of 2 lines + (shapely.buffer(Point(3, 3), 0.5), [2, 3]), + ([shapely.buffer(Point(3, 3), 0.5)], [[0, 0], [2, 3]]), + # envelope of points overlaps 5 lines (touches edge of 2 envelopes) + (MultiPoint([[5, 7], [7, 5]]), [4, 5, 6, 7]), + ([MultiPoint([[5, 7], [7, 5]])], [[0, 0, 0, 0], [4, 5, 6, 7]]), + ], +) +def test_query_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects edge of envelopes of 2 polygons + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + # point intersects single polygon + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box overlaps envelope of 2 polygons + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # larger box overlaps envelope of 3 polygons + (box(0, 0, 1.5, 1.5), [0, 1, 2]), + ([box(0, 0, 1.5, 1.5)], [[0, 0, 0], [0, 1, 2]]), + # first and last boxes overlap envelope of 2 polyons + ( + [box(0, 0, 1, 1), box(100, 100, 110, 110), box(2, 2, 3, 3)], + [[0, 0, 2, 2], [0, 1, 2, 3]], + ), + # envelope of buffer overlaps envelope of 3 polygons + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 3, 4]), + ( + [shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], + [[0, 0, 0], [2, 3, 4]], + ), + # envelope of larger buffer overlaps envelope of 6 polygons + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [1, 2, 3, 4, 5]), + ( + [shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], + [[0, 0, 0, 0, 0], [1, 2, 3, 4, 5]], + ), + # envelope of points overlaps 3 polygons + (MultiPoint([[5, 7], [7, 5]]), [5, 6, 7]), + ([MultiPoint([[5, 7], [7, 5]])], [[0, 0, 0], [5, 6, 7]]), + ], +) +def test_query_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry), expected) + + +@pytest.mark.parametrize( + "predicate", + [ + "bad_predicate", + # disjoint is a valid GEOS binary predicate, but not supported for query + "disjoint", + ], +) +def test_query_invalid_predicate(tree, predicate): + with pytest.raises(ValueError, match="is not a valid option"): + tree.query(Point(1, 1), predicate=predicate) + + +@pytest.mark.parametrize( + "predicate,expected", + [ + ("intersects", [0, 1, 2]), + ("within", []), + ("contains", [1]), + ("overlaps", []), + ("crosses", []), + ("covers", [0, 1, 2]), + ("covered_by", []), + ("contains_properly", [1]), + ], +) +def test_query_prepared_inputs(tree, predicate, expected): + geom = box(0, 0, 2, 2) + shapely.prepare(geom) + assert_array_equal(tree.query(geom, predicate=predicate), expected) + + +def test_query_with_partially_prepared_inputs(tree): + geom = np.array([box(0, 0, 1, 1), box(3, 3, 5, 5)]) + expected = tree.query(geom, predicate="intersects") + + # test with array of partially prepared geometries + shapely.prepare(geom[0]) + assert_array_equal(expected, tree.query(geom, predicate="intersects")) + + +@pytest.mark.parametrize( + "predicate,expected", + [ + pytest.param( + "intersects", + [1], + marks=pytest.mark.xfail(geos_version < (3, 13, 0), reason="GEOS < 3.13"), + ), + ("within", []), + ("contains", []), + ("overlaps", []), + ("crosses", [1]), + ("touches", []), + ("covers", []), + ("covered_by", []), + ("contains_properly", []), + ], +) +def test_query_predicate_errors(tree, predicate, expected): + with ignore_invalid(): + line_nan = shapely.linestrings([1, 1], [1, float("nan")]) + if geos_version < (3, 13, 0): + with pytest.raises(shapely.GEOSException): + tree.query(line_nan, predicate=predicate) + else: + assert_array_equal(tree.query(line_nan, predicate=predicate), expected) + + +### predicate == 'intersects' + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box contains points + (box(3, 3, 6, 6), [3, 4, 5, 6]), + ([box(3, 3, 6, 6)], [[0, 0, 0, 0], [3, 4, 5, 6]]), + # first and last boxes contain points + ( + [box(0, 0, 1, 1), box(100, 100, 110, 110), box(3, 3, 6, 6)], + [[0, 0, 2, 2, 2, 2], [0, 1, 3, 4, 5, 6]], + ), + # envelope of buffer contains more points than intersect buffer + # due to diagonal distance + (shapely.buffer(Point(3, 3), 1), [3]), + ([shapely.buffer(Point(3, 3), 1)], [[0], [3]]), + # envelope of buffer with 1/2 distance between points should intersect + # same points as envelope + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [2, 3, 4]), + ( + [shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], + [[0, 0, 0], [2, 3, 4]], + ), + # multipoints intersect + ( + MultiPoint([[5, 5], [7, 7]]), + [5, 7], + ), + ( + [MultiPoint([[5, 5], [7, 7]])], + [[0, 0], [5, 7]], + ), + # envelope of points contains points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + ( + MultiPoint([[5, 7], [7, 7]]), + [7], + ), + ( + [MultiPoint([[5, 7], [7, 7]])], + [[0], [7]], + ), + ], +) +def test_query_intersects_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="intersects"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects first line + (Point(0, 0), [0]), + ([Point(0, 0)], [[0], [0]]), + (Point(0.5, 0.5), [0]), + ([Point(0.5, 0.5)], [[0], [0]]), + # point within envelope of first line but does not intersect + (Point(0, 0.5), []), + ([Point(0, 0.5)], [[], []]), + # point at shared vertex between 2 lines + (Point(1, 1), [0, 1]), + ([Point(1, 1)], [[0, 0], [0, 1]]), + # box overlaps envelope of first 2 lines (touches edge of 1) + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # first and last boxes overlap multiple lines each + ( + [box(0, 0, 1, 1), box(100, 100, 110, 110), box(2, 2, 3, 3)], + [[0, 0, 2, 2, 2], [0, 1, 1, 2, 3]], + ), + # buffer intersects 2 lines + (shapely.buffer(Point(3, 3), 0.5), [2, 3]), + ([shapely.buffer(Point(3, 3), 0.5)], [[0, 0], [2, 3]]), + # buffer intersects midpoint of line at tangent + (shapely.buffer(Point(2, 1), HALF_UNIT_DIAG), [1]), + ([shapely.buffer(Point(2, 1), HALF_UNIT_DIAG)], [[0], [1]]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), [6, 7]), + ([MultiPoint([[5, 7], [7, 7]])], [[0, 0], [6, 7]]), + ], +) +def test_query_intersects_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="intersects"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point within first polygon + (Point(0, 0.5), [0]), + ([Point(0, 0.5)], [[0], [0]]), + (Point(0.5, 0), [0]), + ([Point(0.5, 0)], [[0], [0]]), + # midpoint between two polygons intersects both + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + # point intersects single polygon + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box overlaps envelope of 2 polygons + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # larger box intersects 3 polygons + (box(0, 0, 1.5, 1.5), [0, 1, 2]), + ([box(0, 0, 1.5, 1.5)], [[0, 0, 0], [0, 1, 2]]), + # first and last boxes overlap + ( + [box(0, 0, 1, 1), box(100, 100, 110, 110), box(2, 2, 3, 3)], + [[0, 0, 2, 2], [0, 1, 2, 3]], + ), + # buffer overlaps 3 polygons + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 3, 4]), + ( + [shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], + [[0, 0, 0], [2, 3, 4]], + ), + # larger buffer overlaps 6 polygons (touches midpoints) + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [1, 2, 3, 4, 5]), + ( + [shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], + [[0, 0, 0, 0, 0], [1, 2, 3, 4, 5]], + ), + # envelope of points overlaps polygons, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint within polygon + (MultiPoint([[5, 7], [7, 7]]), [7]), + ([MultiPoint([[5, 7], [7, 7]])], [[0], [7]]), + ], +) +def test_query_intersects_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="intersects"), expected) + + +### predicate == 'within' +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box not within points + (box(3, 3, 6, 6), []), + ([box(3, 3, 6, 6)], [[], []]), + # envelope of buffer not within points + (shapely.buffer(Point(3, 3), 1), []), + ([shapely.buffer(Point(3, 3), 1)], [[], []]), + # multipoints intersect but are not within points in tree + (MultiPoint([[5, 5], [7, 7]]), []), + ([MultiPoint([[5, 5], [7, 7]])], [[], []]), + # only one point of multipoint intersects, but multipoints are not + # within any points in tree + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # envelope of points contains points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + ], +) +def test_query_within_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="within"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # endpoint not within first line + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # point within first line + (Point(0.5, 0.5), [0]), + ([Point(0.5, 0.5)], [[0], [0]]), + # point within envelope of first line but does not intersect + (Point(0, 0.5), []), + ([Point(0, 0.5)], [[], []]), + # point at shared vertex between 2 lines (but within neither) + (Point(1, 1), []), + ([Point(1, 1)], [[], []]), + # box not within line + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # buffer intersects 2 lines but not within either + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects, but both are not within line + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + (MultiPoint([[6.5, 6.5], [7, 7]]), [6]), + ([MultiPoint([[6.5, 6.5], [7, 7]])], [[0], [6]]), + ], +) +def test_query_within_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="within"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point within first polygon + (Point(0, 0.5), [0]), + ([Point(0, 0.5)], [[0], [0]]), + (Point(0.5, 0), [0]), + ([Point(0.5, 0)], [[0], [0]]), + # midpoint between two polygons intersects both + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + # point intersects single polygon + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box overlaps envelope of 2 polygons but within neither + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # box within polygon + (box(0, 0, 0.5, 0.5), [0]), + ([box(0, 0, 0.5, 0.5)], [[0], [0]]), + # larger box intersects 3 polygons but within none + (box(0, 0, 1.5, 1.5), []), + ([box(0, 0, 1.5, 1.5)], [[], []]), + # buffer intersects 3 polygons but only within one + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [3]), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[0], [3]]), + # larger buffer overlaps 6 polygons (touches midpoints) but within none + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[], []]), + # envelope of points overlaps polygons, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint within polygon + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points in multipoint within polygon + (MultiPoint([[5.25, 5.5], [5.25, 5.0]]), [5]), + ([MultiPoint([[5.25, 5.5], [5.25, 5.0]])], [[0], [5]]), + ], +) +def test_query_within_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="within"), expected) + + +### predicate == 'contains' +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box contains points (2 are at edges and not contained) + (box(3, 3, 6, 6), [4, 5]), + ([box(3, 3, 6, 6)], [[0, 0], [4, 5]]), + # envelope of buffer contains more points than within buffer + # due to diagonal distance + (shapely.buffer(Point(3, 3), 1), [3]), + ([shapely.buffer(Point(3, 3), 1)], [[0], [3]]), + # envelope of buffer with 1/2 distance between points should intersect + # same points as envelope + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [2, 3, 4]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0, 0, 0], [2, 3, 4]]), + # multipoints intersect + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0], [5, 7]]), + # envelope of points contains points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), [7]), + ([MultiPoint([[5, 7], [7, 7]])], [[0], [7]]), + ], +) +def test_query_contains_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="contains"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not contain any lines (not valid relation) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box contains first line (touches edge of 1 but does not contain it) + (box(0, 0, 1, 1), [0]), + ([box(0, 0, 1, 1)], [[0], [0]]), + # buffer intersects 2 lines but contains neither + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points intersect but do not contain any lines (not valid relation) + (MultiPoint([[5, 5], [6, 6]]), []), + ([MultiPoint([[5, 5], [6, 6]])], [[], []]), + ], +) +def test_query_contains_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="contains"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not contain any polygons (not valid relation) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box overlaps envelope of 2 polygons but contains neither + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # larger box intersects 3 polygons but contains only one + (box(0, 0, 2, 2), [1]), + ([box(0, 0, 2, 2)], [[0], [1]]), + # buffer overlaps 3 polygons but contains none + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[], []]), + # larger buffer overlaps 6 polygons (touches midpoints) but contains one + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [3]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0], [3]]), + # envelope of points overlaps polygons, but points do not intersect + # (not valid relation) + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + ], +) +def test_query_contains_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="contains"), expected) + + +### predicate == 'overlaps' +# Overlaps only returns results where geometries are of same dimensions +# and do not completely contain each other. +# See: https://postgis.net/docs/ST_Overlaps.html +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect but do not overlap + (Point(1, 1), []), + ([Point(1, 1)], [[], []]), + # box overlaps points including those at edge but does not overlap + # (completely contains all points) + (box(3, 3, 6, 6), []), + ([box(3, 3, 6, 6)], [[], []]), + # envelope of buffer contains points, but does not overlap + (shapely.buffer(Point(3, 3), 1), []), + ([shapely.buffer(Point(3, 3), 1)], [[], []]), + # multipoints intersect but do not overlap (both completely contain each other) + (MultiPoint([[5, 5], [7, 7]]), []), + ([MultiPoint([[5, 5], [7, 7]])], [[], []]), + # envelope of points contains points in tree, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects but does not overlap + # the intersecting point from multipoint completely contains point in tree + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + ], +) +def test_query_overlaps_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="overlaps"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects line but is completely contained by it + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box overlaps second line (contains first line) + # but of different dimensions so does not overlap + (box(0, 0, 1.5, 1.5), []), + ([box(0, 0, 1.5, 1.5)], [[], []]), + # buffer intersects 2 lines but of different dimensions so does not overlap + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points intersect but different dimensions + (MultiPoint([[5, 5], [6, 6]]), []), + ([MultiPoint([[5, 5], [6, 6]])], [[], []]), + ], +) +def test_query_overlaps_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="overlaps"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not overlap any polygons (different dimensions) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box overlaps 2 polygons + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # larger box intersects 3 polygons and contains one + (box(0, 0, 2, 2), [0, 2]), + ([box(0, 0, 2, 2)], [[0, 0], [0, 2]]), + # buffer overlaps 3 polygons and contains 1 + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 4]), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[0, 0], [2, 4]]), + # larger buffer overlaps 6 polygons (touches midpoints) but contains one + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [1, 2, 4, 5]), + ( + [shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], + [[0, 0, 0, 0], [1, 2, 4, 5]], + ), + # one of two points intersects but different dimensions + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + ], +) +def test_query_overlaps_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="overlaps"), expected) + + +### predicate == 'crosses' +# Only valid for certain geometry combinations +# See: https://postgis.net/docs/ST_Crosses.html +@pytest.mark.parametrize( + "geometry,expected", + [ + # points intersect but not valid relation + (Point(1, 1), []), + # all points of result from tree are in common with box + (box(3, 3, 6, 6), []), + # all points of result from tree are in common with buffer + (shapely.buffer(Point(3, 3), 1), []), + # only one point of multipoint intersects but not valid relation + (MultiPoint([[5, 7], [7, 7]]), []), + ], +) +def test_query_crosses_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="crosses"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects first line but is completely in common with line + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box overlaps envelope of first 2 lines, contains first and crosses second + (box(0, 0, 1.5, 1.5), [1]), + ([box(0, 0, 1.5, 1.5)], [[0], [1]]), + # buffer intersects 2 lines + (shapely.buffer(Point(3, 3), 0.5), [2, 3]), + ([shapely.buffer(Point(3, 3), 0.5)], [[0, 0], [2, 3]]), + # line crosses line + (shapely.linestrings([(1, 0), (0, 1)]), [0]), + ([shapely.linestrings([(1, 0), (0, 1)])], [[0], [0]]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7], [7, 8]]), []), + ([MultiPoint([[5, 7], [7, 7], [7, 8]])], [[], []]), + ], +) +def test_query_crosses_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="crosses"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point within first polygon but not valid relation + (Point(0, 0.5), []), + ([Point(0, 0.5)], [[], []]), + # box overlaps 2 polygons but not valid relation + (box(0, 0, 1.5, 1.5), []), + ([box(0, 0, 1.5, 1.5)], [[], []]), + # buffer overlaps 3 polygons but not valid relation + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[], []]), + # only one point of multipoint within + (MultiPoint([[5, 7], [7, 7], [7, 8]]), [7]), + ([MultiPoint([[5, 7], [7, 7], [7, 8]])], [[0], [7]]), + ], +) +def test_query_crosses_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="crosses"), expected) + + +### predicate == 'touches' +# See: https://postgis.net/docs/ST_Touches.html +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect but not valid relation + (Point(1, 1), []), + ([Point(1, 1)], [[], []]), + # box contains points but touches only those at edges + (box(3, 3, 6, 6), [3, 6]), + ([box(3, 3, 6, 6)], [[0, 0], [3, 6]]), + # polygon completely contains point in tree + (shapely.buffer(Point(3, 3), 1), []), + ([shapely.buffer(Point(3, 3), 1)], [[], []]), + # linestring intersects 2 points but touches only one + (LineString([(-1, -1), (1, 1)]), [1]), + ([LineString([(-1, -1), (1, 1)])], [[0], [1]]), + # multipoints intersect but not valid relation + (MultiPoint([[5, 5], [7, 7]]), []), + ([MultiPoint([[5, 5], [7, 7]])], [[], []]), + ], +) +def test_query_touches_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="touches"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point intersects first line + (Point(0, 0), [0]), + ([Point(0, 0)], [[0], [0]]), + # point is within line + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # point at shared vertex between 2 lines + (Point(1, 1), [0, 1]), + ([Point(1, 1)], [[0, 0], [0, 1]]), + # box overlaps envelope of first 2 lines (touches edge of 1) + (box(0, 0, 1, 1), [1]), + ([box(0, 0, 1, 1)], [[0], [1]]), + # buffer intersects 2 lines but does not touch edges of either + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # buffer intersects midpoint of line at tangent but there is a little overlap + # due to precision issues + (shapely.buffer(Point(2, 1), HALF_UNIT_DIAG + 1e-7), []), + ([shapely.buffer(Point(2, 1), HALF_UNIT_DIAG + 1e-7)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects at vertex between lines + (MultiPoint([[5, 7], [7, 7], [7, 8]]), [6, 7]), + ([MultiPoint([[5, 7], [7, 7], [7, 8]])], [[0, 0], [6, 7]]), + ], +) +def test_query_touches_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="touches"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point within first polygon + (Point(0, 0.5), []), + ([Point(0, 0.5)], [[], []]), + # point is at edge of first polygon + (Point(HALF_UNIT_DIAG + EPS, 0), [0]), + ([Point(HALF_UNIT_DIAG + EPS, 0)], [[0], [0]]), + # box overlaps envelope of 2 polygons does not touch any at edge + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # box overlaps 2 polygons and touches edge of first + (box(HALF_UNIT_DIAG + EPS, 0, 2, 2), [0]), + ([box(HALF_UNIT_DIAG + EPS, 0, 2, 2)], [[0], [0]]), + # buffer overlaps 3 polygons but does not touch any at edge + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG + EPS), []), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG + EPS)], [[], []]), + # only one point of multipoint within polygon but does not touch + (MultiPoint([[0, 0], [7, 7], [7, 8]]), []), + ([MultiPoint([[0, 0], [7, 7], [7, 8]])], [[], []]), + ], +) +def test_query_touches_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="touches"), expected) + + +### predicate == 'covers' +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect and thus no point is outside the other + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box covers any points that intersect or are within + (box(3, 3, 6, 6), [3, 4, 5, 6]), + ([box(3, 3, 6, 6)], [[0, 0, 0, 0], [3, 4, 5, 6]]), + # envelope of buffer covers more points than are covered by buffer + # due to diagonal distance + (shapely.buffer(Point(3, 3), 1), [3]), + ([shapely.buffer(Point(3, 3), 1)], [[0], [3]]), + # envelope of buffer with 1/2 distance between points should intersect + # same points as envelope + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [2, 3, 4]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0, 0, 0], [2, 3, 4]]), + # multipoints intersect and thus no point is outside the other + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0], [5, 7]]), + # envelope of points contains points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), [7]), + ([MultiPoint([[5, 7], [7, 7]])], [[0], [7]]), + ], +) +def test_query_covers_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="covers"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not cover any lines (not valid relation) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box covers first line (intersects another does not contain it) + (box(0, 0, 1.5, 1.5), [0]), + ([box(0, 0, 1.5, 1.5)], [[0], [0]]), + # box completely covers 2 lines (touches edges of 2 others) + (box(1, 1, 3, 3), [1, 2]), + ([box(1, 1, 3, 3)], [[0, 0], [1, 2]]), + # buffer intersects 2 lines but does not completely cover either + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects a line, but does not completely cover + # it + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points intersect but do not cover any lines (not valid relation) + (MultiPoint([[5, 5], [6, 6]]), []), + ([MultiPoint([[5, 5], [6, 6]])], [[], []]), + ], +) +def test_query_covers_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="covers"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not cover any polygons (not valid relation) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # box overlaps envelope of 2 polygons but does not completely cover either + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # larger box intersects 3 polygons but covers only one + (box(0, 0, 2, 2), [1]), + ([box(0, 0, 2, 2)], [[0], [1]]), + # buffer overlaps 3 polygons but does not completely cover any + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[], []]), + # larger buffer overlaps 6 polygons (touches midpoints) but covers only one + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [3]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0], [3]]), + # envelope of points overlaps polygons, but points do not intersect + # (not valid relation) + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + ], +) +def test_query_covers_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="covers"), expected) + + +### predicate == 'covered_by' +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # box not covered by points + (box(3, 3, 6, 6), []), + ([box(3, 3, 6, 6)], [[], []]), + # envelope of buffer not covered by points + (shapely.buffer(Point(3, 3), 1), []), + ([shapely.buffer(Point(3, 3), 1)], [[], []]), + # multipoints intersect but are not covered by points in tree + (MultiPoint([[5, 5], [7, 7]]), []), + ([MultiPoint([[5, 5], [7, 7]])], [[], []]), + # only one point of multipoint intersects, but multipoints are not + # covered by any points in tree + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # envelope of points overlaps points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + ], +) +def test_query_covered_by_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="covered_by"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # endpoint is covered by first line + (Point(0, 0), [0]), + ([Point(0, 0)], [[0], [0]]), + # point covered by first line + (Point(0.5, 0.5), [0]), + ([Point(0.5, 0.5)], [[0], [0]]), + # point within envelope of first line but does not intersect + (Point(0, 0.5), []), + ([Point(0, 0.5)], [[], []]), + # point at shared vertex between 2 lines and is covered by both + (Point(1, 1), [0, 1]), + ([Point(1, 1)], [[0, 0], [0, 1]]), + # line intersects 3 lines, but is covered by only one + (shapely.linestrings([[1, 1], [2, 2]]), [1]), + ([shapely.linestrings([[1, 1], [2, 2]])], [[0], [1]]), + # line intersects 2 lines, but is covered by neither + (shapely.linestrings([[1.5, 1.5], [2.5, 2.5]]), []), + ([shapely.linestrings([[1.5, 1.5], [2.5, 2.5]])], [[], []]), + # box not covered by line (not valid geometric relation) + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # buffer intersects 2 lines but not within either (not valid geometric relation) + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + # envelope of points overlaps lines but intersects none + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects, but both are not covered by line + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points are covered by a line + (MultiPoint([[6.5, 6.5], [7, 7]]), [6]), + ([MultiPoint([[6.5, 6.5], [7, 7]])], [[0], [6]]), + ], +) +def test_query_covered_by_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query(geometry, predicate="covered_by"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point covered by polygon + (Point(0, 0.5), [0]), + ([Point(0, 0.5)], [[0], [0]]), + (Point(0.5, 0), [0]), + ([Point(0.5, 0)], [[0], [0]]), + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # midpoint between two polygons is covered by both + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + # line intersects multiple polygons but is not covered by any + (shapely.linestrings([[0, 0], [2, 2]]), []), + ([shapely.linestrings([[0, 0], [2, 2]])], [[], []]), + # line intersects multiple polygons but is covered by only one + (shapely.linestrings([[1.5, 1.5], [2.5, 2.5]]), [2]), + ([shapely.linestrings([[1.5, 1.5], [2.5, 2.5]])], [[0], [2]]), + # box overlaps envelope of 2 polygons but not covered by either + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # box covered by polygon + (box(0, 0, 0.5, 0.5), [0]), + ([box(0, 0, 0.5, 0.5)], [[0], [0]]), + # larger box intersects 3 polygons but not covered by any + (box(0, 0, 1.5, 1.5), []), + ([box(0, 0, 1.5, 1.5)], [[], []]), + # buffer intersects 3 polygons but only within one + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [3]), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[0], [3]]), + # larger buffer overlaps 6 polygons (touches midpoints) but within none + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[], []]), + # envelope of points overlaps polygons, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint within polygon + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + # both points in multipoint within polygon + (MultiPoint([[5.25, 5.5], [5.25, 5.0]]), [5]), + ([MultiPoint([[5.25, 5.5], [5.25, 5.0]])], [[0], [5]]), + ], +) +def test_query_covered_by_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query(geometry, predicate="covered_by"), expected) + + +### predicate == 'contains_properly' +@pytest.mark.parametrize( + "geometry,expected", + [ + # points do not intersect + (Point(0.5, 0.5), []), + ([Point(0.5, 0.5)], [[], []]), + # points intersect + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # line contains every point that is not on its first or last coordinate + # these are on the "exterior" of the line + (shapely.linestrings([[0, 0], [2, 2]]), [1]), + ([shapely.linestrings([[0, 0], [2, 2]])], [[0], [1]]), + # slightly longer line contains multiple points + (shapely.linestrings([[0.5, 0.5], [2.5, 2.5]]), [1, 2]), + ([shapely.linestrings([[0.5, 0.5], [2.5, 2.5]])], [[0, 0], [1, 2]]), + # line intersects and contains one point + (shapely.linestrings([[0, 2], [2, 0]]), [1]), + ([shapely.linestrings([[0, 2], [2, 0]])], [[0], [1]]), + # box contains points (2 are at edges and not contained) + (box(3, 3, 6, 6), [4, 5]), + ([box(3, 3, 6, 6)], [[0, 0], [4, 5]]), + # envelope of buffer contains more points than within buffer + # due to diagonal distance + (shapely.buffer(Point(3, 3), 1), [3]), + ([shapely.buffer(Point(3, 3), 1)], [[0], [3]]), + # envelope of buffer with 1/2 distance between points should intersect + # same points as envelope + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [2, 3, 4]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0, 0, 0], [2, 3, 4]]), + # multipoints intersect + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0], [5, 7]]), + # envelope of points contains points, but points do not intersect + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + # only one point of multipoint intersects + (MultiPoint([[5, 7], [7, 7]]), [7]), + ([MultiPoint([[5, 7], [7, 7]])], [[0], [7]]), + ], +) +def test_query_contains_properly_points(tree, geometry, expected): + assert_array_equal(tree.query(geometry, predicate="contains_properly"), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # None of the following conditions satisfy the relation for linestrings + # because they have no interior: + # "a contains b if no points of b lie in the exterior of a, and at least one + # point of the interior of b lies in the interior of a" + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + (shapely.linestrings([[0, 0], [1, 1]]), []), + ([shapely.linestrings([[0, 0], [1, 1]])], [[], []]), + (shapely.linestrings([[0, 0], [2, 2]]), []), + ([shapely.linestrings([[0, 0], [2, 2]])], [[], []]), + (shapely.linestrings([[0, 2], [2, 0]]), []), + ([shapely.linestrings([[0, 2], [2, 0]])], [[], []]), + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + (MultiPoint([[5, 7], [7, 7]]), []), + ([MultiPoint([[5, 7], [7, 7]])], [[], []]), + (MultiPoint([[5, 5], [6, 6]]), []), + ([MultiPoint([[5, 5], [6, 6]])], [[], []]), + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + (box(0, 0, 2, 2), []), + ([box(0, 0, 2, 2)], [[], []]), + (shapely.buffer(Point(3, 3), 0.5), []), + ([shapely.buffer(Point(3, 3), 0.5)], [[], []]), + ], +) +def test_query_contains_properly_lines(line_tree, geometry, expected): + assert_array_equal( + line_tree.query(geometry, predicate="contains_properly"), expected + ) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # point does not contain any polygons (not valid relation) + (Point(0, 0), []), + ([Point(0, 0)], [[], []]), + # line intersects multiple polygons but does not contain any (not valid + # relation) + (shapely.linestrings([[0, 0], [2, 2]]), []), + ([shapely.linestrings([[0, 0], [2, 2]])], [[], []]), + # box overlaps envelope of 2 polygons but contains neither + (box(0, 0, 1, 1), []), + ([box(0, 0, 1, 1)], [[], []]), + # larger box intersects 3 polygons but contains only one + (box(0, 0, 2, 2), [1]), + ([box(0, 0, 2, 2)], [[0], [1]]), + # buffer overlaps 3 polygons but contains none + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), []), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[], []]), + # larger buffer overlaps 6 polygons (touches midpoints) but contains one + (shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG), [3]), + ([shapely.buffer(Point(3, 3), 3 * HALF_UNIT_DIAG)], [[0], [3]]), + # envelope of points overlaps polygons, but points do not intersect + # (not valid relation) + (MultiPoint([[5, 7], [7, 5]]), []), + ([MultiPoint([[5, 7], [7, 5]])], [[], []]), + ], +) +def test_query_contains_properly_polygons(poly_tree, geometry, expected): + assert_array_equal( + poly_tree.query(geometry, predicate="contains_properly"), expected + ) + + +### predicate = 'dwithin' + + +@pytest.mark.skipif(geos_version >= (3, 10, 0), reason="GEOS >= 3.10") +@pytest.mark.parametrize( + "geometry", [Point(0, 0), [Point(0, 0)], None, [None], empty, [empty]] +) +def test_query_dwithin_geos_version(tree, geometry): + with pytest.raises(UnsupportedGEOSVersionError, match="requires GEOS >= 3.10"): + tree.query(geometry, predicate="dwithin", distance=1) + + +@pytest.mark.skipif(geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry,distance,match", + [ + (Point(0, 0), None, "distance parameter must be provided"), + ([Point(0, 0)], None, "distance parameter must be provided"), + (Point(0, 0), "foo", "could not convert string to float"), + ([Point(0, 0)], "foo", "could not convert string to float"), + ([Point(0, 0)], ["foo"], "could not convert string to float"), + (Point(0, 0), [0, 1], "Could not broadcast distance to match geometry"), + ([Point(0, 0)], [0, 1], "Could not broadcast distance to match geometry"), + (Point(0, 0), [[1.0]], "should be one dimensional"), + ([Point(0, 0)], [[1.0]], "should be one dimensional"), + ], +) +def test_query_dwithin_invalid_distance(tree, geometry, distance, match): + with pytest.raises(ValueError, match=match): + tree.query(geometry, predicate="dwithin", distance=distance) + + +@pytest.mark.skipif(geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry,distance,expected", + [ + (None, 1.0, []), + ([None], 1.0, [[], []]), + (Point(0.25, 0.25), 0, []), + ([Point(0.25, 0.25)], 0, [[], []]), + (Point(0.25, 0.25), -1, []), + ([Point(0.25, 0.25)], -1, [[], []]), + (Point(0.25, 0.25), np.nan, []), + ([Point(0.25, 0.25)], np.nan, [[], []]), + (Point(), 1, []), + ([Point()], 1, [[], []]), + (Point(0.25, 0.25), 0.5, [0]), + ([Point(0.25, 0.25)], 0.5, [[0], [0]]), + (Point(0.25, 0.25), 2.5, [0, 1, 2]), + ([Point(0.25, 0.25)], 2.5, [[0, 0, 0], [0, 1, 2]]), + (Point(3, 3), 1.5, [2, 3, 4]), + ([Point(3, 3)], 1.5, [[0, 0, 0], [2, 3, 4]]), + # 2 equidistant points in tree + (Point(0.5, 0.5), 0.75, [0, 1]), + ([Point(0.5, 0.5)], 0.75, [[0, 0], [0, 1]]), + ( + [None, Point(0.5, 0.5)], + 0.75, + [ + [ + 1, + 1, + ], + [0, 1], + ], + ), + ( + [Point(0.5, 0.5), Point(0.25, 0.25)], + 0.75, + [[0, 0, 1], [0, 1, 0]], + ), + ( + [Point(0, 0.2), Point(1.75, 1.75)], + [0.25, 2], + [[0, 1, 1, 1], [0, 1, 2, 3]], + ), + # all points intersect box + (box(0, 0, 3, 3), 0, [0, 1, 2, 3]), + ([box(0, 0, 3, 3)], 0, [[0, 0, 0, 0], [0, 1, 2, 3]]), + (box(0, 0, 3, 3), 0.25, [0, 1, 2, 3]), + ([box(0, 0, 3, 3)], 0.25, [[0, 0, 0, 0], [0, 1, 2, 3]]), + # intersecting and nearby points + (box(1, 1, 2, 2), 1.5, [0, 1, 2, 3]), + ([box(1, 1, 2, 2)], 1.5, [[0, 0, 0, 0], [0, 1, 2, 3]]), + # # return nearest point in tree for each point in multipoint + (MultiPoint([[0.25, 0.25], [1.5, 1.5]]), 0.75, [0, 1, 2]), + ([MultiPoint([[0.25, 0.25], [1.5, 1.5]])], 0.75, [[0, 0, 0], [0, 1, 2]]), + # 2 equidistant points per point in multipoint + ( + MultiPoint([[0.5, 0.5], [3.5, 3.5]]), + 0.75, + [0, 1, 3, 4], + ), + ( + [MultiPoint([[0.5, 0.5], [3.5, 3.5]])], + 0.75, + [[0, 0, 0, 0], [0, 1, 3, 4]], + ), + ], +) +def test_query_dwithin_points(tree, geometry, distance, expected): + assert_array_equal( + tree.query(geometry, predicate="dwithin", distance=distance), expected + ) + + +@pytest.mark.skipif(geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry,distance,expected", + [ + (None, 1.0, []), + ([None], 1.0, [[], []]), + (Point(0.5, 0.5), 0, [0]), + ([Point(0.5, 0.5)], 0, [[0], [0]]), + (Point(0.5, 0.5), 1.0, [0, 1]), + ([Point(0.5, 0.5)], 1.0, [[0, 0], [0, 1]]), + (Point(2, 2), 0.5, [1, 2]), + ([Point(2, 2)], 0.5, [[0, 0], [1, 2]]), + (box(0, 0, 1, 1), 0.5, [0, 1]), + ([box(0, 0, 1, 1)], 0.5, [[0, 0], [0, 1]]), + (box(0.5, 0.5, 1.5, 1.5), 0.5, [0, 1]), + ([box(0.5, 0.5, 1.5, 1.5)], 0.5, [[0, 0], [0, 1]]), + # multipoints at endpoints of 2 lines each + (MultiPoint([[5, 5], [7, 7]]), 0.5, [4, 5, 6, 7]), + ([MultiPoint([[5, 5], [7, 7]])], 0.5, [[0, 0, 0, 0], [4, 5, 6, 7]]), + # multipoints are equidistant from 2 lines + (MultiPoint([[5, 7], [7, 5]]), 1.5, [5, 6]), + ([MultiPoint([[5, 7], [7, 5]])], 1.5, [[0, 0], [5, 6]]), + ], +) +def test_query_dwithin_lines(line_tree, geometry, distance, expected): + assert_array_equal( + line_tree.query(geometry, predicate="dwithin", distance=distance), + expected, + ) + + +@pytest.mark.skipif(geos_version < (3, 10, 0), reason="GEOS < 3.10") +@pytest.mark.parametrize( + "geometry,distance,expected", + [ + (Point(0, 0), 0, [0]), + ([Point(0, 0)], 0, [[0], [0]]), + (Point(0, 0), 0.5, [0]), + ([Point(0, 0)], 0.5, [[0], [0]]), + (Point(0, 0), 1.5, [0, 1]), + ([Point(0, 0)], 1.5, [[0, 0], [0, 1]]), + (Point(0.5, 0.5), 1, [0, 1]), + ([Point(0.5, 0.5)], 1, [[0, 0], [0, 1]]), + (Point(0.5, 0.5), 0.5, [0, 1]), + ([Point(0.5, 0.5)], 0.5, [[0, 0], [0, 1]]), + (box(0, 0, 1, 1), 0, [0, 1]), + ([box(0, 0, 1, 1)], 0, [[0, 0], [0, 1]]), + (box(0, 0, 1, 1), 2, [0, 1, 2]), + ([box(0, 0, 1, 1)], 2, [[0, 0, 0], [0, 1, 2]]), + (MultiPoint([[5, 5], [7, 7]]), 0.5, [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], 0.5, [[0, 0], [5, 7]]), + ( + MultiPoint([[5, 5], [7, 7]]), + 2.5, + [3, 4, 5, 6, 7, 8, 9], + ), + ( + [MultiPoint([[5, 5], [7, 7]])], + 2.5, + [[0, 0, 0, 0, 0, 0, 0], [3, 4, 5, 6, 7, 8, 9]], + ), + ], +) +def test_query_dwithin_polygons(poly_tree, geometry, distance, expected): + assert_array_equal( + poly_tree.query(geometry, predicate="dwithin", distance=distance), + expected, + ) + + +### STRtree nearest + + +def test_nearest_empty_tree(): + tree = STRtree([]) + assert tree.nearest(point) is None + + +@pytest.mark.parametrize("geometry", ["I am not a geometry"]) +def test_nearest_invalid_geom(tree, geometry): + with pytest.raises(TypeError): + tree.nearest(geometry) + + +@pytest.mark.parametrize("geometry", [None, [None], [Point(1, 1), None]]) +def test_nearest_none(tree, geometry): + with pytest.raises(ValueError): + tree.nearest(geometry) + + +@pytest.mark.parametrize( + "geometry", [empty_point, [empty_point], [Point(1, 1), empty_point]] +) +def test_nearest_empty(tree, geometry): + with pytest.raises(ValueError): + tree.nearest(geometry) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0.25, 0.25), 0), + (Point(0.75, 0.75), 1), + (Point(1, 1), 1), + ([Point(1, 1), Point(0, 0)], [1, 0]), + ([Point(1, 1), Point(0.25, 1)], [1, 1]), + ([Point(-10, -10), Point(100, 100)], [0, 9]), + (box(0.5, 0.5, 0.75, 0.75), 1), + (shapely.buffer(Point(2.5, 2.5), HALF_UNIT_DIAG), 2), + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), 3), + (MultiPoint([[5.5, 5], [7, 7]]), 7), + (MultiPoint([[5, 7], [7, 5]]), 6), + ], +) +def test_nearest_points(tree, geometry, expected): + assert_array_equal(tree.nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # 2 equidistant points in tree + (Point(0.5, 0.5), [0, 1]), + # multiple points in box + (box(0, 0, 3, 3), [0, 1, 2, 3]), + # return nearest point in tree for each point in multipoint + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ], +) +def test_nearest_points_equidistant(tree, geometry, expected): + # results are returned in order they are traversed when searching the tree, + # which can vary between GEOS versions, so we test that one of the valid + # results is present + result = tree.nearest(geometry) + assert result in expected + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0.5, 0.5), 0), + (Point(1.5, 0.5), 0), + (shapely.box(0.5, 1.5, 1, 2), 1), + (shapely.linestrings([[0, 0.5], [1, 2.5]]), 0), + ], +) +def test_nearest_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # at junction between 2 lines + (Point(2, 2), [1, 2]), + # contains one line, intersects with another + (box(0, 0, 1, 1), [0, 1]), + # overlaps 2 lines + (box(0.5, 0.5, 1.5, 1.5), [0, 1]), + # box overlaps 2 lines and intersects endpoints of 2 more + (box(3, 3, 5, 5), [2, 3, 4, 5]), + (shapely.buffer(Point(2.5, 2.5), HALF_UNIT_DIAG), [1, 2]), + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 3]), + # multipoints at endpoints of 2 lines each + (MultiPoint([[5, 5], [7, 7]]), [4, 5, 6, 7]), + # second point in multipoint at endpoints of 2 lines + (MultiPoint([[5.5, 5], [7, 7]]), [6, 7]), + # multipoints are equidistant from 2 lines + (MultiPoint([[5, 7], [7, 5]]), [5, 6]), + ], +) +def test_nearest_lines_equidistant(line_tree, geometry, expected): + # results are returned in order they are traversed when searching the tree, + # which can vary between GEOS versions, so we test that one of the valid + # results is present + result = line_tree.nearest(geometry) + assert result in expected + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0, 0), 0), + (Point(2, 2), 2), + (shapely.box(0, 5, 1, 6), 3), + (MultiPoint([[5, 7], [7, 5]]), 6), + ], +) +def test_nearest_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + # 2 polygons in tree overlap point + (Point(0.5, 0.5), [0, 1]), + # box overlaps multiple polygons + (box(0, 0, 1, 1), [0, 1]), + (box(0.5, 0.5, 1.5, 1.5), [0, 1, 2]), + (box(3, 3, 5, 5), [3, 4, 5]), + (shapely.buffer(Point(2.5, 2.5), HALF_UNIT_DIAG), [2, 3]), + # completely overlaps one polygon, touches 2 others + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 3, 4]), + # each point in multi point intersects a polygon in tree + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + (MultiPoint([[5.5, 5], [7, 7]]), [5, 7]), + ], +) +def test_nearest_polygons_equidistant(poly_tree, geometry, expected): + # results are returned in order they are traversed when searching the tree, + # which can vary between GEOS versions, so we test that one of the valid + # results is present + result = poly_tree.nearest(geometry) + assert result in expected + + +def test_query_nearest_empty_tree(): + tree = STRtree([]) + assert_array_equal(tree.query_nearest(point), []) + assert_array_equal(tree.query_nearest([point]), [[], []]) + + +@pytest.mark.parametrize("geometry", ["I am not a geometry", ["still not a geometry"]]) +def test_query_nearest_invalid_geom(tree, geometry): + with pytest.raises(TypeError): + tree.query_nearest(geometry) + + +@pytest.mark.parametrize( + "geometry,return_distance,expected", + [ + (None, False, []), + ([None], False, [[], []]), + (None, True, ([], [])), + ([None], True, ([[], []], [])), + ], +) +def test_query_nearest_none(tree, geometry, return_distance, expected): + if return_distance: + index, distance = tree.query_nearest(geometry, return_distance=True) + assert_array_equal(index, expected[0]) + assert_array_equal(distance, expected[1]) + + else: + assert_array_equal(tree.query_nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [(empty, []), ([empty], [[], []]), ([empty, point], [[1, 1], [2, 3]])], +) +def test_query_nearest_empty_geom(tree, geometry, expected): + assert_array_equal(tree.query_nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0.25, 0.25), [0]), + ([Point(0.25, 0.25)], [[0], [0]]), + (Point(0.75, 0.75), [1]), + ([Point(0.75, 0.75)], [[0], [1]]), + (Point(1, 1), [1]), + ([Point(1, 1)], [[0], [1]]), + # 2 equidistant points in tree + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + ([Point(1, 1), Point(0, 0)], [[0, 1], [1, 0]]), + ([Point(1, 1), Point(0.25, 1)], [[0, 1], [1, 1]]), + ([Point(-10, -10), Point(100, 100)], [[0, 1], [0, 9]]), + (box(0.5, 0.5, 0.75, 0.75), [1]), + ([box(0.5, 0.5, 0.75, 0.75)], [[0], [1]]), + # multiple points in box + (box(0, 0, 3, 3), [0, 1, 2, 3]), + ([box(0, 0, 3, 3)], [[0, 0, 0, 0], [0, 1, 2, 3]]), + (shapely.buffer(Point(2.5, 2.5), 1), [2, 3]), + ([shapely.buffer(Point(2.5, 2.5), 1)], [[0, 0], [2, 3]]), + (shapely.buffer(Point(3, 3), 0.5), [3]), + ([shapely.buffer(Point(3, 3), 0.5)], [[0], [3]]), + (MultiPoint([[5.5, 5], [7, 7]]), [7]), + ([MultiPoint([[5.5, 5], [7, 7]])], [[0], [7]]), + (MultiPoint([[5, 7], [7, 5]]), [6]), + ([MultiPoint([[5, 7], [7, 5]])], [[0], [6]]), + # return nearest point in tree for each point in multipoint + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0], [5, 7]]), + # 2 equidistant points per point in multipoint + (MultiPoint([[0.5, 0.5], [3.5, 3.5]]), [0, 1, 3, 4]), + ([MultiPoint([[0.5, 0.5], [3.5, 3.5]])], [[0, 0, 0, 0], [0, 1, 3, 4]]), + ], +) +def test_query_nearest_points(tree, geometry, expected): + assert_array_equal(tree.query_nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0.5, 0.5), [0]), + ([Point(0.5, 0.5)], [[0], [0]]), + # at junction between 2 lines, will return both + (Point(2, 2), [1, 2]), + ([Point(2, 2)], [[0, 0], [1, 2]]), + # contains one line, intersects with another + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + # overlaps 2 lines + (box(0.5, 0.5, 1.5, 1.5), [0, 1]), + ([box(0.5, 0.5, 1.5, 1.5)], [[0, 0], [0, 1]]), + # second box overlaps 2 lines and intersects endpoints of 2 more + ([box(0, 0, 0.5, 0.5), box(3, 3, 5, 5)], [[0, 1, 1, 1, 1], [0, 2, 3, 4, 5]]), + (shapely.buffer(Point(2.5, 2.5), 1), [1, 2, 3]), + ([shapely.buffer(Point(2.5, 2.5), 1)], [[0, 0, 0], [1, 2, 3]]), + (shapely.buffer(Point(3, 3), 0.5), [2, 3]), + ([shapely.buffer(Point(3, 3), 0.5)], [[0, 0], [2, 3]]), + # multipoints at endpoints of 2 lines each + (MultiPoint([[5, 5], [7, 7]]), [4, 5, 6, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0, 0, 0], [4, 5, 6, 7]]), + # second point in multipoint at endpoints of 2 lines + (MultiPoint([[5.5, 5], [7, 7]]), [6, 7]), + ([MultiPoint([[5.5, 5], [7, 7]])], [[0, 0], [6, 7]]), + # multipoints are equidistant from 2 lines + (MultiPoint([[5, 7], [7, 5]]), [5, 6]), + ([MultiPoint([[5, 7], [7, 5]])], [[0, 0], [5, 6]]), + ], +) +def test_query_nearest_lines(line_tree, geometry, expected): + assert_array_equal(line_tree.query_nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0, 0), [0]), + ([Point(0, 0)], [[0], [0]]), + (Point(2, 2), [2]), + ([Point(2, 2)], [[0], [2]]), + # 2 polygons in tree overlap point + (Point(0.5, 0.5), [0, 1]), + ([Point(0.5, 0.5)], [[0, 0], [0, 1]]), + # box overlaps multiple polygons + (box(0, 0, 1, 1), [0, 1]), + ([box(0, 0, 1, 1)], [[0, 0], [0, 1]]), + (box(0.5, 0.5, 1.5, 1.5), [0, 1, 2]), + ([box(0.5, 0.5, 1.5, 1.5)], [[0, 0, 0], [0, 1, 2]]), + ([box(0, 0, 1, 1), box(3, 3, 5, 5)], [[0, 0, 1, 1, 1], [0, 1, 3, 4, 5]]), + (shapely.buffer(Point(2.5, 2.5), HALF_UNIT_DIAG), [2, 3]), + ([shapely.buffer(Point(2.5, 2.5), HALF_UNIT_DIAG)], [[0, 0], [2, 3]]), + # completely overlaps one polygon, touches 2 others + (shapely.buffer(Point(3, 3), HALF_UNIT_DIAG), [2, 3, 4]), + ([shapely.buffer(Point(3, 3), HALF_UNIT_DIAG)], [[0, 0, 0], [2, 3, 4]]), + # each point in multi point intersects a polygon in tree + (MultiPoint([[5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5, 5], [7, 7]])], [[0, 0], [5, 7]]), + (MultiPoint([[5.5, 5], [7, 7]]), [5, 7]), + ([MultiPoint([[5.5, 5], [7, 7]])], [[0, 0], [5, 7]]), + (MultiPoint([[5, 7], [7, 5]]), [6]), + ([MultiPoint([[5, 7], [7, 5]])], [[0], [6]]), + ], +) +def test_query_nearest_polygons(poly_tree, geometry, expected): + assert_array_equal(poly_tree.query_nearest(geometry), expected) + + +@pytest.mark.parametrize( + "geometry,max_distance,expected", + [ + # using unset max_distance should return all nearest + (Point(0.5, 0.5), None, [0, 1]), + ([Point(0.5, 0.5)], None, [[0, 0], [0, 1]]), + # using large max_distance should return all nearest + (Point(0.5, 0.5), 10, [0, 1]), + ([Point(0.5, 0.5)], 10, [[0, 0], [0, 1]]), + # using small max_distance should return no results + (Point(0.5, 0.5), 0.1, []), + ([Point(0.5, 0.5)], 0.1, [[], []]), + # using small max_distance should only return results in that distance + ([Point(0.5, 0.5), Point(0, 0)], 0.1, [[1], [0]]), + ], +) +def test_query_nearest_max_distance(tree, geometry, max_distance, expected): + assert_array_equal( + tree.query_nearest(geometry, max_distance=max_distance), expected + ) + + +@pytest.mark.parametrize( + "geometry,max_distance", + [ + (Point(0.5, 0.5), 0), + ([Point(0.5, 0.5)], 0), + (Point(0.5, 0.5), -1), + ([Point(0.5, 0.5)], -1), + ], +) +def test_query_nearest_invalid_max_distance(tree, geometry, max_distance): + with pytest.raises(ValueError, match="max_distance must be greater than 0"): + tree.query_nearest(geometry, max_distance=max_distance) + + +def test_query_nearest_nonscalar_max_distance(tree): + with pytest.raises(ValueError, match="parameter only accepts scalar values"): + tree.query_nearest(Point(0.5, 0.5), max_distance=[1]) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(0, 0), ([0], [0.0])), + ([Point(0, 0)], ([[0], [0]], [0.0])), + (Point(0.5, 0.5), ([0, 1], [0.7071, 0.7071])), + ([Point(0.5, 0.5)], ([[0, 0], [0, 1]], [0.7071, 0.7071])), + (box(0, 0, 1, 1), ([0, 1], [0.0, 0.0])), + ([box(0, 0, 1, 1)], ([[0, 0], [0, 1]], [0.0, 0.0])), + ], +) +def test_query_nearest_return_distance(tree, geometry, expected): + expected_indices, expected_dist = expected + + actual_indices, actual_dist = tree.query_nearest(geometry, return_distance=True) + + assert_array_equal(actual_indices, expected_indices) + assert_array_equal(np.round(actual_dist, 4), expected_dist) + + +@pytest.mark.parametrize( + "geometry,exclusive,expected", + [ + (Point(1, 1), False, [1]), + ([Point(1, 1)], False, [[0], [1]]), + (Point(1, 1), True, [0, 2]), + ([Point(1, 1)], True, [[0, 0], [0, 2]]), + ([Point(1, 1), Point(2, 2)], True, [[0, 0, 1, 1], [0, 2, 1, 3]]), + ], +) +def test_query_nearest_exclusive(tree, geometry, exclusive, expected): + assert_array_equal(tree.query_nearest(geometry, exclusive=exclusive), expected) + + +@pytest.mark.parametrize( + "geometry,expected", + [ + (Point(1, 1), []), + ([Point(1, 1)], [[], []]), + ], +) +def test_query_nearest_exclusive_no_results(tree, geometry, expected): + tree = STRtree([Point(1, 1)]) + assert_array_equal(tree.query_nearest(geometry, exclusive=True), expected) + + +@pytest.mark.parametrize( + "geometry,exclusive", + [ + (Point(1, 1), "invalid"), + # non-scalar exclusive parameter not allowed + (Point(1, 1), ["also invalid"]), + ([Point(1, 1)], []), + ([Point(1, 1)], [False]), + ], +) +def test_query_nearest_invalid_exclusive(tree, geometry, exclusive): + with pytest.raises(ValueError): + tree.query_nearest(geometry, exclusive=exclusive) + + +@pytest.mark.parametrize( + "geometry,all_matches", + [ + (Point(1, 1), "invalid"), + # non-scalar all_matches parameter not allowed + (Point(1, 1), ["also invalid"]), + ([Point(1, 1)], []), + ([Point(1, 1)], [False]), + ], +) +def test_query_nearest_invalid_all_matches(tree, geometry, all_matches): + with pytest.raises(ValueError): + tree.query_nearest(geometry, all_matches=all_matches) + + +def test_query_nearest_all_matches(tree): + point = Point(0.5, 0.5) + assert_array_equal(tree.query_nearest(point, all_matches=True), [0, 1]) + + indices = tree.query_nearest(point, all_matches=False) + # result is dependent on tree traversal order; may vary across test runs + assert np.array_equal(indices, [0]) or np.array_equal(indices, [1]) + + +def test_strtree_threaded_query(): + ## Create data + polygons = shapely.polygons(np.random.randn(1000, 3, 2)) + # needs to be big enough to trigger the segfault + N = 100_000 + points = shapely.points(4 * np.random.random(N) - 2, 4 * np.random.random(N) - 2) + + ## Slice parts of the arrays -> 4x4 => 16 combinations + n = int(len(polygons) / 4) + polygons_parts = [ + polygons[:n], + polygons[n : 2 * n], + polygons[2 * n : 3 * n], + polygons[3 * n :], + ] + n = int(len(points) / 4) + points_parts = [ + points[:n], + points[n : 2 * n], + points[2 * n : 3 * n], + points[3 * n :], + ] + + ## Creating the trees in advance + trees = [] + for i in range(4): + left = points_parts[i] + tree = STRtree(left) + trees.append(tree) + + ## The function querying the trees in parallel + + def thread_func(idxs): + i, j = idxs + tree = trees[i] + right = polygons_parts[j] + return tree.query(right, predicate="contains") + + with ThreadPoolExecutor() as pool: + list(pool.map(thread_func, itertools.product(range(4), range(4)))) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_testing.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..5def4fb9f3cb87f59516ac13debb95841e0df1d5 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/tests/test_testing.py @@ -0,0 +1,97 @@ +import numpy as np +import pytest + +import shapely +from shapely.testing import assert_geometries_equal +from shapely.tests.common import ( + all_types, + empty, + empty_line_string, + empty_line_string_z, + empty_point, + empty_point_z, + empty_polygon, + line_string, + line_string_nan, + line_string_z, + point, +) + +EMPTY_GEOMS = ( + empty_point, + empty_point_z, + empty_line_string, + empty_line_string_z, + empty_polygon, + empty, +) + +line_string_reversed = shapely.linestrings([(0, 0), (1, 0), (1, 1)][::-1]) + + +def make_array(left, right, use_array): + if use_array in ("left", "both"): + left = np.array([left] * 3, dtype=object) + if use_array in ("right", "both"): + right = np.array([right] * 3, dtype=object) + return left, right + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +@pytest.mark.parametrize("geom", all_types + EMPTY_GEOMS) +def test_assert_geometries_equal(geom, use_array): + assert_geometries_equal(*make_array(geom, geom, use_array)) + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +@pytest.mark.parametrize( + "geom1,geom2", + [ + (point, line_string), + (line_string, line_string_z), + (empty_point, empty_polygon), + (empty_point, empty_point_z), + (empty_line_string, empty_line_string_z), + ], +) +def test_assert_geometries_not_equal(geom1, geom2, use_array): + with pytest.raises(AssertionError): + assert_geometries_equal(*make_array(geom1, geom2, use_array)) + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +def test_assert_none_equal(use_array): + assert_geometries_equal(*make_array(None, None, use_array)) + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +def test_assert_none_not_equal(use_array): + with pytest.raises(AssertionError): + assert_geometries_equal(*make_array(None, None, use_array), equal_none=False) + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +def test_assert_nan_equal(use_array): + assert_geometries_equal(*make_array(line_string_nan, line_string_nan, use_array)) + + +@pytest.mark.parametrize("use_array", ["none", "left", "right", "both"]) +def test_assert_nan_not_equal(use_array): + with pytest.raises(AssertionError): + assert_geometries_equal( + *make_array(line_string_nan, line_string_nan, use_array), equal_nan=False + ) + + +def test_normalize_true(): + assert_geometries_equal(line_string_reversed, line_string, normalize=True) + + +def test_normalize_default(): + with pytest.raises(AssertionError): + assert_geometries_equal(line_string_reversed, line_string) + + +def test_normalize_false(): + with pytest.raises(AssertionError): + assert_geometries_equal(line_string_reversed, line_string, normalize=False) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/vectorized/__init__.py b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/vectorized/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..49462c2e11bf5d1360560cc84c68694ff70eef68 --- /dev/null +++ b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/vectorized/__init__.py @@ -0,0 +1,91 @@ +"""Provides multi-point element-wise operations such as ``contains``.""" + +import warnings + +import numpy as np + +import shapely +from shapely.prepared import PreparedGeometry + + +def _construct_points(x, y): + x, y = np.asanyarray(x), np.asanyarray(y) + if x.shape != y.shape: + raise ValueError("X and Y shapes must be equivalent.") + + if x.dtype != np.float64: + x = x.astype(np.float64) + if y.dtype != np.float64: + y = y.astype(np.float64) + + return shapely.points(x, y) + + +def contains(geometry, x, y): + """Check whether multiple points are contained by a single geometry. + + Vectorized (element-wise) version of `contains`. + + Parameters + ---------- + geometry : PreparedGeometry or subclass of BaseGeometry + The geometry which is to be checked to see whether each point is + contained within. The geometry will be "prepared" if it is not already + a PreparedGeometry instance. + x : array + The x coordinates of the points to check. + y : array + The y coordinates of the points to check. + + Returns + ------- + Mask of points contained by the given `geometry`. + + """ + warnings.warn( + "The 'shapely.vectorized.contains' function is deprecated and will be " + "removed a future version. Use 'shapely.contains_xy' instead (available " + "since shapely 2.0.0).", + DeprecationWarning, + stacklevel=2, + ) + if isinstance(geometry, PreparedGeometry): + geometry = geometry.context + shapely.prepare(geometry) + return shapely.contains_xy(geometry, x, y) + + +def touches(geometry, x, y): + """Check whether multiple points touch the exterior of a single geometry. + + Vectorized (element-wise) version of `touches`. + + Parameters + ---------- + geometry : PreparedGeometry or subclass of BaseGeometry + The geometry which is to be checked to see whether each point is + contained within. The geometry will be "prepared" if it is not already + a PreparedGeometry instance. + x : array + The x coordinates of the points to check. + y : array + The y coordinates of the points to check. + + Returns + ------- + Mask of points which touch the exterior of the given `geometry`. + + """ + warnings.warn( + "The 'shapely.vectorized.touches' function is deprecated and will be " + "removed a future version. Use 'shapely.intersects_xy(geometry.boundary, x, y)'" + " instead (available since shapely 2.0.0).", + DeprecationWarning, + stacklevel=2, + ) + if isinstance(geometry, PreparedGeometry): + geometry = geometry.context + # Touches(geom, point) == Intersects(Boundary(geom), point) + boundary = geometry.boundary + shapely.prepare(boundary) + return shapely.intersects_xy(boundary, x, y) diff --git a/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/vectorized/__pycache__/__init__.cpython-311.pyc b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/vectorized/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dff5e6feb7a327504bd76a5e59cac0d99768b7e2 Binary files /dev/null and b/data/miniconda3/envs/catiagent/lib/python3.11/site-packages/shapely/vectorized/__pycache__/__init__.cpython-311.pyc differ