Sandy.Arv
Sandy.Arv

Reputation: 605

Interpolation of curve

I have a code where a curve is generated using random values. and a Horizontal line which runs through it. The code is as follows.

import numpy as np
import matplotlib.pylab as pl

data = np.random.uniform(low=-1600, high=-550, size=(288,))
line = [-1290] * 288

pl.figure(figsize = (10,5))
pl.plot(data)
pl.plot(line)

Now I need to find the the coordinates for the all the points of intersections of the curve (data) and the line. The curve is made of linear segments that join neighboring points . And there are a lot of intersection points where the curve meets the line. any help would be appreciated. thank you!

Upvotes: 4

Views: 549

Answers (3)

Matt Hall
Matt Hall

Reputation: 8152

I like the Shapely answer because Shapely is awesome, but you might not want that dependency. Here's a version of some code I use in signal processing adapted from this Gist by @endolith. It basically implements kazemakase's suggestion.

from matplotlib import mlab

def find_crossings(a, value):
    # Normalize the 'signal' to zero.
    sig = a - value

    # Find all indices right before any crossing.
    indices = mlab.find((sig[1:] >= 0) & (sig[:-1] < 0) | (sig[1:] < 0) & (sig[:-1] >= 0))

    # Use linear interpolation to find intersample crossings.
    return [i - sig[i] / (sig[i+1] - sig[i]) for i in indices]

This returns the indices (your x values) of where the curve crosses the value (-1290 in your case). You would call it like this:

find_crossings(data, -1290)

Here's what I get for 100 points:

x = find_crossings(data, -1290)
plt.figure(figsize=(10,5))
plt.plot(data)
plt.plot(line)
plt.scatter(x, [-1290 for p in x], color='red')
plt.show()

Random function zero crossings

Upvotes: 3

HYRY
HYRY

Reputation: 97331

Here is a solution that use shapely:

import numpy as np
import matplotlib.pylab as pl
np.random.seed(0)
data = np.random.uniform(low=-1600, high=-550, size=(50,))
line = [-1290] * len(data)

pl.figure(figsize = (10,5))
pl.plot(data)
pl.plot(line)

from shapely import geometry

line = geometry.LineString(np.c_[np.arange(len(data)), data])
hline = geometry.LineString([[-100, -1290], [1000, -1290]])

points = line.intersection(hline)

x = [p.x for p in points]
y = [p.y for p in points]

pl.plot(x, y, "o")

the output:

enter image description here

Upvotes: 2

MB-F
MB-F

Reputation: 23647

I think the curve, as you interpret it, does in fact follow an equation. In particular, it is made of linear segments that join neighboring points.

Here is what you can do:

  1. find all pairs of neighbors where one lies above and the other below the line
  2. for each pair find the intersection of the horizontal line with the line joining the points

Upvotes: 2

Related Questions