Skip to content

Commit 60689cb

Browse files
committed
Add BoundingBox.buffer()
related to #406
1 parent 80c4893 commit 60689cb

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

openeo_driver/util/geometry.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -585,3 +585,13 @@ def round_to_resolution(self, res_x: float, res_y: float) -> "BoundingBox":
585585
north=res_y * math.ceil(self.north / res_y) if math.isfinite(self.north) else self.north,
586586
crs=self.crs,
587587
)
588+
589+
def buffer(self, dx: float, dy: Union[float, None] = None) -> "BoundingBox":
590+
"""Buffer the bounding box by given distance (in units of the bounding box CRS)"""
591+
# TODO: what to do with negative buffering that overshoots the bbox width or height? Assert here or in main constructor?
592+
# TODO: also support 4-component buffering (left, bottom, right, top)?
593+
if dy is None:
594+
dy = dx
595+
return BoundingBox(
596+
west=self.west - dx, south=self.south - dy, east=self.east + dx, north=self.north + dy, crs=self.crs
597+
)

tests/util/test_geometry.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -796,6 +796,19 @@ def test_round_to_resolution_nodata(self):
796796
rounded = bbox.round_to_resolution(10, 20)
797797
assert rounded.as_tuple() == (500430, 5649820, 507680, float("inf"), None)
798798

799+
def test_buffer(self):
800+
bbox = BoundingBox(1, 2, 3, 4, crs=4326)
801+
802+
assert bbox.buffer(1).as_tuple() == (0, 1, 4, 5, "EPSG:4326")
803+
assert bbox.buffer(0.1).as_tuple() == (0.9, 1.9, 3.1, 4.1, "EPSG:4326")
804+
assert bbox.buffer(-0.1).as_tuple() == (1.1, 2.1, 2.9, 3.9, "EPSG:4326")
805+
806+
assert bbox.buffer(0.5, 0.1).as_tuple() == (0.5, 1.9, 3.5, 4.1, "EPSG:4326")
807+
assert bbox.buffer(0.5, -0.1).as_tuple() == (0.5, 2.1, 3.5, 3.9, "EPSG:4326")
808+
809+
# TODO: instead of this nonsense result, should this fail, or result in some special empty case?
810+
assert bbox.buffer(-10).as_tuple() == (11, 12, -7, -6, "EPSG:4326")
811+
799812

800813
class TestValidateGeoJSON:
801814
@staticmethod

0 commit comments

Comments
 (0)