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

Fix issue #774: Use coverage array for calculation of valid_percent #775

Merged
merged 1 commit into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 3 additions & 1 deletion rio_tiler/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ def get_array_statistics(
else:
coverage = numpy.ones((data.shape[1], data.shape[2]))

coverage_pixels = numpy.count_nonzero(coverage)

# Avoid non masked nan/inf values
numpy.ma.fix_invalid(data, copy=False)

Expand All @@ -143,7 +145,7 @@ def get_array_statistics(

valid_pixels = float(numpy.ma.count(data[b]))
masked_pixels = float(numpy.ma.count_masked(data[b]))
valid_percent = round((valid_pixels / data[b].size) * 100, 2)
valid_percent = round(min(valid_pixels / coverage_pixels, 1) * 100, 2)

if categorical:
out_dict = dict(zip(keys.tolist(), counts.tolist()))
Expand Down
10 changes: 10 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,13 +645,15 @@ def test_get_array_statistics_coverage():
assert stats[0]["count"] == 1.75
assert stats[0]["median"] == 3 # 2 in exactextract
assert round(stats[0]["std"], 2) == 1.05
assert stats[0]["valid_percent"] == 100

stats = utils.get_array_statistics(data)
assert len(stats) == 1
assert stats[0]["min"] == 1
assert stats[0]["max"] == 4
assert stats[0]["mean"] == 2.5
assert stats[0]["count"] == 4
assert stats[0]["valid_percent"] == 100

# same test as https://github.com/isciences/exactextract/blob/0883cd585d9c7b6b4e936aeca4aa84a15adf82d2/python/tests/test_exact_extract.py#L48-L110
data = np.ma.arange(1, 10, dtype=np.int32).reshape(3, 3)
Expand All @@ -670,6 +672,14 @@ def test_get_array_statistics_coverage():
assert stats[0]["percentile_75"] == 6
assert stats[0]["std"] == math.sqrt(5)

# test correct calculation of valid percent with masked array and coverage array
data = np.ma.array(
[[[0, 1], [0, 5]]], mask=[[[True, False], [True, False]]], fill_value=0
)
coverage = np.array([[0, 0.5], [0.75, 1]])
stats = utils.get_array_statistics(data, coverage=coverage)
assert stats[0]["valid_percent"] == 66.67


def test_get_vrt_transform_world_file(dataset_fixture):
"""Should return correct transform and size."""
Expand Down
Loading