Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose recursive_round function #390

Merged
merged 3 commits into from
Jan 26, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 24 additions & 12 deletions src/stactools/core/utils/round.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,13 @@ def round_coordinates(stac_object: S, precision: int = DEFAULT_PRECISION) -> S:
"""Rounds Item geometry and bbox coordinates or Collection spatial extent
bbox coordinates to specified precision.

Any tuples encountered will be converted to lists.

Args:
stac_object (S): A pystac Item or Collection.
precision (int): Number of decimal places for rounding.

Returns:
S: The original PySTAC Item or Collection, with rounded coordinates.
"""

def recursive_round(coordinates: List[Any], precision: int) -> List[Any]:
for idx, value in enumerate(coordinates):
if isinstance(value, (int, float)):
coordinates[idx] = round(value, precision)
else:
coordinates[idx] = list(value) # handle any tuples
coordinates[idx] = recursive_round(coordinates[idx], precision)
return coordinates

if isinstance(stac_object, Item):
if stac_object.geometry is not None:
stac_object.geometry["coordinates"] = recursive_round(
Expand All @@ -46,3 +34,27 @@ def recursive_round(coordinates: List[Any], precision: int) -> List[Any]:
)

return stac_object


def recursive_round(coordinates: List[Any], precision: int) -> List[Any]:
"""Rounds a list of numbers. The list can contain additional nested lists or
tuples of numbers.

Any tuples encountered will be converted to lists.

Args:
coordinates (List[Any]): A list of numbers, possibly containing nested
lists or tuples of numbers.
precision (int): Number of decimal places to use for rounding.

Returns:
List[Any]: a list (possibly nested) of numbers rounded to the given
precision.
"""
for idx, value in enumerate(coordinates):
if isinstance(value, (int, float)):
coordinates[idx] = round(value, precision)
else:
coordinates[idx] = list(value) # handle any tuples
coordinates[idx] = recursive_round(coordinates[idx], precision)
return coordinates