Skip to content Skip to sidebar Skip to footer

How To Find Number Of Self Intersection Points On 2d Plot?

I have two numpy arrays x and y: x = [-256.70946838 -188.26946838 -83.86946838 29.81053162 131.89053162 213.67053162 271.09053162 315.17053162 310.53053162 296.03053162

Solution 1:

Just find the intersections between any two line segments:

x = [-256.70946838, -188.26946838,  -83.86946838,   29.81053162,  131.89053162,
  213.67053162,  271.09053162,  315.17053162,  310.53053162,  296.03053162,
  252.53053162,  184.67053162,   82.59053162,  -33.40946838, -139.54946838,
 -213.78946838, -271.20946838, -317.02946838, -310.64946838, -298.46946838,
 -256.70946838]

y = [ 9.71224758e-02, -3.19097822e-02, -4.80388145e-02,  6.48644113e-02,
 -3.19097822e-02,  9.71224758e-02, -1.57807500e-02,  6.48644113e-02,
 -4.02877524e-01, -1.93200105e-01,  6.48644113e-02,  1.64773146e-02,
  3.48282294e-04, -1.44813008e-01,  6.48644113e-02, -1.57807500e-02,
  3.48282294e-04, -8.02968790e-02,  2.10025702e-01,  1.77767637e-01,
  9.71224758e-02]

defintersection(x1,x2,x3,x4,y1,y2,y3,y4):
    d = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)
    if d:
        xs = ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)) / d
        ys = ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)) / d
        if (xs >= min(x1,x2) and xs <= max(x1,x2) and
            xs >= min(x3,x4) and xs <= max(x3,x4)):
            return xs, ys

xs, ys = [], []
for i inrange(len(x)-1):
    for j inrange(i-1):
        if xs_ys := intersection(x[i],x[i+1],x[j],x[j+1],y[i],y[i+1],y[j],y[j+1]):
            xs.append(xs_ys[0])
            ys.append(xs_ys[1])

from matplotlib import pyplot as plt
plt.plot(x, y)
plt.scatter(xs, ys, color='r')
plt.show()

enter image description here

This is a straightforward implementation of the wikipedia formula which surely can be optimized if needed.

Post a Comment for "How To Find Number Of Self Intersection Points On 2d Plot?"