# numpy – Implementation of a threshold detection function in Python

I want to implement the following activation function in Python:

Entry:

• time vector t [n dimensional numpy vector]
• data vector and [n dimensional numpy vector] (the values ​​correspond to the vector t)
• threshold tr [float]
• Threshold type vector tr_type [m dimensional list of int values]

Exit:

• Threshold time vector tr_time [m dimensional list of float values]

Function:

I would like to return tr_time, which consists of the exact time values ​​(preferred also interpolated that are not yet in the code below) in which y is crossing tr (crossing means less then greater or vice versa). The different values ​​in tr_time correspond to the vector tr_type: the elements of tr_type indicate the number of the crossing and if this is an upward or downward crossing. For example, 1 means that the first time and less then tr to greater than tr, -3 means that the third time and goes greater than tr unless tr (third time means along the time vector t)

At the moment I have the following code:

``````import numpy as np
import matplotlib.pyplot as plt

activator of def (t, y, tr, tr_type):
triggermarker = np.diff (1 * (and> tr))
positive indices = [i for i, x in enumerate(triggermarker) if x == 1]
negative indices = [i for i, x in enumerate(triggermarker) if x == -1]
triggertime = []
for i in tr_type:
if i> = 0:
triggertime.append (t[positiveindices[i - 1]])
elif i <0
triggertime.append (t[negativeindices[i - 1]])
return triggertime

t = np.linspace (0, 20, 1000)
y = np.sin (t)
tr = 0.5
tr_type = [1, 2, -2]
print (trigger (t, y, tr, tr_type))
plt.plot (t, y)
plt.grid ()
``````

Now I'm quite new to Python, so I was wondering if there is a more python and more efficient way to implement this. For example, without loops or without the need to write separate code for ascending or descending crossings.

Thank you!