Skip to content

Commit a9906c1

Browse files
fix(cvfdutil): polygon area and centroid calculations sometimes imprecise
* Changed area_of_polygon and centroid_of_polygon to use shapely calculations * Close #2150
1 parent 43cbe47 commit a9906c1

File tree

1 file changed

+8
-28
lines changed

1 file changed

+8
-28
lines changed

flopy/utils/cvfdutil.py

Lines changed: 8 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,18 @@
1+
from shapely.geometry import Polygon
12
import numpy as np
3+
from .utl_import import import_optional_dependency
24

35

46
def area_of_polygon(x, y):
5-
"""Calculates the signed area of an arbitrary polygon given its vertices
6-
https://stackoverflow.com/a/4682656/ (Joe Kington)
7-
http://softsurfer.com/Archive/algorithm_0101/algorithm_0101.htm#2D%20Polygons
8-
"""
9-
area = 0.0
10-
for i in range(-1, len(x) - 1):
11-
area += x[i] * (y[i + 1] - y[i - 1])
12-
return area / 2.0
7+
shapely = import_optional_dependency("shapely")
8+
pgon = shapely.geometry.Polygon(zip(x, y))
9+
return pgon.area
1310

1411

1512
def centroid_of_polygon(points):
16-
"""
17-
https://stackoverflow.com/a/14115494/ (mgamba)
18-
"""
19-
import itertools as IT
20-
21-
area = area_of_polygon(*zip(*points))
22-
result_x = 0
23-
result_y = 0
24-
N = len(points)
25-
points = IT.cycle(points)
26-
x1, y1 = next(points)
27-
for i in range(N):
28-
x0, y0 = x1, y1
29-
x1, y1 = next(points)
30-
cross = (x0 * y1) - (x1 * y0)
31-
result_x += (x0 + x1) * cross
32-
result_y += (y0 + y1) * cross
33-
result_x /= area * 6.0
34-
result_y /= area * 6.0
35-
return (result_x, result_y)
13+
shapely = import_optional_dependency("shapely")
14+
pgon = shapely.geometry.Polygon(points)
15+
return pgon.centroid.x, pgon.centroid.y
3616

3717

3818
class Point:

0 commit comments

Comments
 (0)