Friday, 26 February 2021

calculate area intersected between ellipses - python

I'm aiming to calculate the area that intersects between two ellipses. The following computes the area between two fixed coordinates but I'm hoping iterate this process using moving coordinates for one ellipse, while keeping the second ellipse fixed.

Using below, ellipse1 will remain constant and ellipse2 will use the coordinates from X and Y in the df.

The intended output will hopefully return the area at each point in time rounded to 2 decimal places as a separate column labelled 'Area'.

df = pd.DataFrame({        
    'Time' : [1,2,3,4,5],                               
    'X' : [3.0,4.5,5.0,10.0,3.0],
    'Y' : [1.0,0.0,-1.0,-2.0,-3.0],         
    })

from matplotlib import pyplot as plt
from shapely.geometry.point import Point
from shapely import affinity
from matplotlib.patches import Polygon
import numpy as np

def create_ellipse(center, lengths, angle = 0):

    """
    create a shapely ellipse. adapted from
    https://gis.stackexchange.com/a/243462
    """
    circ = Point(center).buffer(1)
    ell = affinity.scale(circ, int(lengths[0]), int(lengths[1]))
    ellr = affinity.rotate(ell, angle)

    return ellr

fig,ax = plt.subplots(figsize = (6,6))

ax.set_xlim([-20,20])
ax.set_ylim([-20,20])

ellipse1 = create_ellipse((0,0),(5,10),0)
verts1 = np.array(ellipse1.exterior.coords.xy)
patch1 = Polygon(verts1.T,color = 'red', alpha = 0.5)
ax.add_patch(patch1)

ellipse2 = create_ellipse((3.0,1.0),(5,5),0)
verts2 = np.array(ellipse2.exterior.coords.xy)
patch2 = Polygon(verts2.T,color = 'blue', alpha = 0.5)
ax.add_patch(patch2)

##compute intersect 
intersect = ellipse1.intersection(ellipse2)
verts3 = np.array(intersect.exterior.coords.xy)
patch3 = Polygon(verts3.T, facecolor = 'none', edgecolor = 'black')
ax.add_patch(patch3)

##compute intersected area
print(intersect.area)

intended output:

   Time     X    Y   Area
0     1   3.0  1.0  56.51
1     2   4.5  0.0  46.99
2     3   5.0 -1.0  36.75
3     4  10.0 -2.0   0.00
4     5   3.0 -3.0  54.03


from calculate area intersected between ellipses - python

No comments:

Post a Comment