Skip to content

Commit

Permalink
fix get_dimensions()
Browse files Browse the repository at this point in the history
Return values that are consistent with shapely for collections.
  • Loading branch information
benbovy committed Dec 10, 2024
1 parent 8fa60ae commit 627c714
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/geography.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <s2/s2point.h>
#include <s2/s2polygon.h>
#include <s2/util/coding/coder.h>
#include <s2geography/accessors.h>
#include <s2geography/geography.h>
#include <s2geography/predicates.h>
#include <s2geography/wkt-writer.h>
Expand Down Expand Up @@ -228,7 +229,11 @@ std::int8_t get_type_id(PyObjectGeography obj) {
}

int get_dimensions(PyObjectGeography obj) {
return obj.as_geog_ptr()->dimension();
// note: in case of a collection with features of different dimensions:
// - Geography::dimension() returns -1
// - s2geography::s2_dimension(geog) returns the max value found in collection
// => we want the latter here.
return s2geog::s2_dimension(obj.as_geog_ptr()->geog());
}

/*
Expand Down Expand Up @@ -340,15 +345,18 @@ void init_geography(py::module &m) {
m.def("get_dimensions", py::vectorize(&get_dimensions), py::arg("geography"), R"pbdoc(
Returns the inherent dimensionality of a geography.
The inherent dimension is 0 for points, 1 for linestrings and 2 for
polygons. For geometrycollections it is the max of the containing elements.
Empty collections and None values return -1.
Parameters
----------
geography : :py:class:`Geography` or array_like
Geography object(s)
Returns
-------
dimensions : int or array
The inherent dimension is 0 for points, 1 for linestrings and 2 for
polygons. For geometrycollections it is either the max of the containing
elements or -1 for empty collections.
)pbdoc");

// Geography utils
Expand Down
20 changes: 20 additions & 0 deletions tests/test_geography.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,26 @@ def test_get_dimensions() -> None:
assert spherely.get_dimensions(spherely.create_point(5, 40)) == 0


@pytest.mark.parametrize(
"empty_geog, expected",
[
(spherely.create_point(), 0),
(spherely.create_linestring(), 1),
(spherely.create_polygon(), 2),
(spherely.create_collection([]), -1),
],
)
def test_get_dimensions_empty(empty_geog, expected) -> None:
assert spherely.get_dimensions(empty_geog) == expected


def test_get_dimensions_collection() -> None:
geog = spherely.create_collection(
[spherely.create_point(0, 0), spherely.create_polygon([(0, 0), (1, 1), (2, 0)])]
)
assert spherely.get_dimensions(geog) == 2


def test_prepare() -> None:
# test array
geog = np.array(
Expand Down

0 comments on commit 627c714

Please sign in to comment.