Skip to content

Commit

Permalink
Merge pull request perrygeo#193 from giplessis/master
Browse files Browse the repository at this point in the history
Accessing geometry properties for user-defined stats
  • Loading branch information
perrygeo authored Jun 17, 2019
2 parents 55ed2c4 + 92dc9de commit 8a960e2
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
14 changes: 14 additions & 0 deletions docs/manual.rst
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,20 @@ then use it in your ``zonal_stats`` call like so::
... add_stats={'mymean':mymean})
[{'count': 75, 'mymean': 14.660084635416666}, {'count': 50, 'mymean': 56.605761718750003}]

To have access to geometry properties, a dictionnary can be passed to the user-defined function::

>>> def mymean_prop(x,prop):
... return np.ma.mean(x) * prop['id']

then use it in your ``zonal_stats`` call like so::

>>> zonal_stats("tests/data/polygons.shp",
... "tests/data/slope.tif",
... stats="count",
... add_stats={'mymean_prop':mymean_prop},
... properties=['id'])
[{'count': 75, 'mymean_prop': 14.660084635416666}, {'count': 50, 'mymean_prop': 113.2115234375}]


GeoJSON output
^^^^^^^^^^^^^^
Expand Down
7 changes: 6 additions & 1 deletion src/rasterstats/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ def gen_zonal_stats(
with zonal stats appended as additional properties.
Use with `prefix` to ensure unique and meaningful property names.
Returns
-------
generator of dicts (if geojson_out is False)
Expand Down Expand Up @@ -258,7 +259,11 @@ def gen_zonal_stats(

if add_stats is not None:
for stat_name, stat_func in add_stats.items():
feature_stats[stat_name] = stat_func(masked)
try:
feature_stats[stat_name] = stat_func(masked, feat['properties'])
except TypeError:
# backwards compatible with single-argument function
feature_stats[stat_name] = stat_func(masked)

if raster_out:
feature_stats['mini_raster_array'] = masked
Expand Down
11 changes: 11 additions & 0 deletions tests/test_zonal.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,17 @@ def mymean(x):
assert stats[i]['mean'] == stats[i]['mymean']


def test_add_stats_prop():
polygons = os.path.join(DATA, 'polygons.shp')

def mymean_prop(x, prop):
return np.ma.mean(x) * prop['id']

stats = zonal_stats(polygons, raster, add_stats={'mymean_prop': mymean_prop})
for i in range(len(stats)):
assert stats[i]['mymean_prop'] == stats[i]['mean'] * (i+1)


def test_mini_raster():
polygons = os.path.join(DATA, 'polygons.shp')
stats = zonal_stats(polygons, raster, raster_out=True)
Expand Down

0 comments on commit 8a960e2

Please sign in to comment.