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

Optimisation of points_within_polygon #74

Merged
merged 3 commits into from
Nov 21, 2020
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
1 change: 1 addition & 0 deletions measurements.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,7 @@ square(bbox)
| ------- | ---------------------------------------------------------- | ---------------------------------------------- |
| `points` | Feature/FeatureCollection of Points | FeatureCollection of Points to find |
| `polygons` | Feature/FeatureCollection of Polygon(s)/MultiPolygon(s) | FeatureCollection of Polygon(s)/MultiPolygon(s)|
| `chunk_size` | int | Number of chunks each process to handle. The default value is 1, for a large number of features please use `chunk_size` greater than 1 to get better results in terms of performance.|

| Return | Type | Description |
| ----------- | ------------------ | ----------------------------------------------------------------- |
Expand Down
14 changes: 9 additions & 5 deletions turfpy/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,15 @@ def get_coord(coord):
raise Exception("coord is required")

if not isinstance(coord, list):
if coord.type == "Feature" and coord.geometry and coord.geometry.type == "Point":
return coord.geometry.coordinates

if coord.type == "Point":
return coord.coordinates
if (
coord["type"] == "Feature"
and coord["geometry"]
and coord["geometry"]["type"] == "Point"
):
return coord["geometry"]["coordinates"]

if coord["type"] == "Point":
return coord["coordinates"]

if (
isinstance(coord, list)
Expand Down
61 changes: 43 additions & 18 deletions turfpy/measurement.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
This is mainly inspired by turf.js.
link: http://turfjs.org/
"""
import concurrent.futures
from functools import partial
from math import asin, atan2, cos, degrees, log, pi, pow, radians, sin, sqrt, tan
from typing import Optional, Union
from multiprocessing import Manager
from typing import List, Optional, Union

from geojson import (
Feature,
Expand Down Expand Up @@ -1294,7 +1297,9 @@ def square(bbox: list):


def points_within_polygon(
points: Union[Feature, FeatureCollection], polygons: Union[Feature, FeatureCollection]
points: Union[Feature, FeatureCollection],
polygons: Union[Feature, FeatureCollection],
chunk_size: int = 1,
) -> FeatureCollection:
"""Find Point(s) that fall within (Multi)Polygon(s).

Expand All @@ -1308,26 +1313,46 @@ def points_within_polygon(
:param points: A single GeoJSON ``Point`` feature or FeatureCollection of Points.
:param polygons: A Single GeoJSON Polygon/MultiPolygon or FeatureCollection of
Polygons/MultiPolygons.
:param chunk_size: Number of chunks each process to handle. The default value is
1, for a large number of features please use `chunk_size` greater than 1
to get better results in terms of performance.
:return: A :class:`geojson.FeatureCollection` of Points.
"""
results = []
if not points:
raise Exception("Points cannot be empty")

def __callback_feature_each(feature, feature_index):
contained = False
if points["type"] == "Point":
points = FeatureCollection([Feature(geometry=points)])

def __callback_geom_each(
current_geometry, feature_index, feature_properties, feature_bbox, feature_id
):
if boolean_point_in_polygon(feature, current_geometry):
nonlocal contained
contained = True
if points["type"] == "Feature":
points = FeatureCollection([points])

manager = Manager()
results: List[dict] = manager.list()

part_func = partial(
check_each_point,
polygons=polygons,
results=results,
)

if contained:
nonlocal results
results.append(feature)
with concurrent.futures.ProcessPoolExecutor() as executor:
for _ in executor.map(part_func, points["features"], chunksize=chunk_size):
pass

return FeatureCollection(list(results))


def check_each_point(point, polygons, results):
def __callback_geom_each(
current_geometry, feature_index, feature_properties, feature_bbox, feature_id
):
contained = False
if boolean_point_in_polygon(point, current_geometry):
contained = True

geom_each(polygons, __callback_geom_each)
return True
if contained:
nonlocal results
results.append(point)

feature_each(points, __callback_feature_each)
return FeatureCollection(results)
geom_each(polygons, __callback_geom_each)
5 changes: 4 additions & 1 deletion turfpy/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -814,7 +814,10 @@ def tesselate(poly: Feature) -> FeatureCollection:
... [21, 15], [11, 11], [11, 0]]], "type": "Polygon"})
>>> tesselate(polygon)
"""
if poly.geometry.type != "Polygon" and poly.geometry.type != "MultiPolygon":
if (
poly["geometry"]["type"] != "Polygon"
and poly["geometry"]["type"] != "MultiPolygon"
):
raise ValueError("Geometry must be Polygon or MultiPolygon")

fc = FeatureCollection([])
Expand Down