Skip to content

Commit 5dac003

Browse files
authored
Merge pull request #290 from ericboucher/augment-custom-functions
Add rv_array to custom functions
2 parents 8086a35 + 12d5169 commit 5dac003

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/rasterstats/main.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import inspect
12
import sys
23
import warnings
34

@@ -283,10 +284,14 @@ def gen_zonal_stats(
283284

284285
if add_stats is not None:
285286
for stat_name, stat_func in add_stats.items():
286-
try:
287+
n_params = len(inspect.signature(stat_func).parameters.keys())
288+
if n_params == 3:
289+
feature_stats[stat_name] = stat_func(masked, feat["properties"], rv_array)
290+
# backwards compatible with two-argument function
291+
elif n_params == 2:
287292
feature_stats[stat_name] = stat_func(masked, feat["properties"])
288-
except TypeError:
289-
# backwards compatible with single-argument function
293+
# backwards compatible with single-argument function
294+
else:
290295
feature_stats[stat_name] = stat_func(masked)
291296

292297
if raster_out:

tests/test_zonal.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,18 @@ def mymean_prop(x, prop):
315315
for i in range(len(stats)):
316316
assert stats[i]["mymean_prop"] == stats[i]["mean"] * (i + 1)
317317

318+
def test_add_stats_prop_and_array():
319+
polygons = os.path.join(DATA, "polygons.shp")
320+
321+
def mymean_prop_and_array(x, prop, rv_array):
322+
# confirm that the object exists and is accessible.
323+
assert rv_array is not None
324+
return np.ma.mean(x) * prop["id"]
325+
326+
stats = zonal_stats(polygons, raster, add_stats={"mymean_prop_and_array": mymean_prop_and_array})
327+
for i in range(len(stats)):
328+
assert stats[i]["mymean_prop_and_array"] == stats[i]["mean"] * (i + 1)
329+
318330

319331
def test_mini_raster():
320332
polygons = os.path.join(DATA, "polygons.shp")

0 commit comments

Comments
 (0)