[英]How do you generate a backlash signal for simple sine wave input using python?
I am using the below python codes so as to generate the backlash signal for a simple sine wave input.The generated output is not as per the requirement.The output should be similar to that of backlash block used in Simulink.我正在使用下面的 python 代码,以便为简单的正弦波输入生成反冲信号。生成的输出不符合要求。输出应该类似于 Simulink 中使用的反冲块的输出。
#Importing libraries
import matplotlib.pyplot as plt
import numpy as np
#Setting upper limit and lower limit
LL = -0.5
UL = 0.5
#Generating the sine wave
x=np.linspace(0,10,1000)
y=(np.sin(x))
#phase shift of y1 by -pi/2
y1=(np.sin(x-1.571))
# plot original sine
plt.plot(x,y)
#setting the thresholds
y1[(y1>UL)] = UL
y1[(y1<LL)] = LL
#Initializing at the input
y1[(y==0)] = 0
y1[(y1>UL)] -= UL
y1[(y1<LL)] -= LL
#Plotting both the waves
plt.plot(x,y)
plt.plot(x,y1)
plt.grid()
plt.show()
I don't think there is a simple vectorized implementation for the backlash process.我认为没有针对反弹过程的简单矢量化实现。 The k-th output depends on the previous values in a nontrivial way.第 k 个输出以一种非平凡的方式取决于先前的值。 A concise way to write the process (assuming x
is the input array and y
is the output array) is编写该过程的简洁方法(假设x
是输入数组, y
是输出数组)是
y[k] = min(max(y[k-1], x[k] - h), x[k] + h)
where h
is half the deadband.其中h
是死区的一半。
The following script includes a backlash
function that uses a Python for-loop.以下脚本包含一个使用 Python for 循环的backlash
函数。 (The function uses if
statements instead of the min
and max
functions.) It is simple, but it won't be very fast. (该函数使用if
语句而不是min
和max
函数。)它很简单,但速度不会很快。 If high performance is important, you might consider reimplementing the function in Cython or numba .如果高性能很重要,您可以考虑在Cython或numba 中重新实现该功能。
import numpy as np
def backlash(x, deadband=1.0, initial=0.0):
"""
Backlash process.
This function emulates the Backlash block of Simulink
(https://www.mathworks.com/help/simulink/slref/backlash.html).
x must be a one-dimensional numpy array (or array-like).
deadband must be a nonnegative scalar.
initial must be a scalar.
"""
halfband = 0.5*deadband
y = np.empty_like(x, dtype=np.float64)
current_y = initial
for k in range(len(x)):
current_x = x[k]
xminus = current_x - halfband
if xminus > current_y:
current_y = xminus
else:
xplus = current_x + halfband
if xplus < current_y:
current_y = xplus
y[k] = current_y
return y
if __name__ == "__main__":
import matplotlib.pyplot as plt
t = np.linspace(0, 10, 500)
x = np.sin(t)
deadband = 1
y = backlash(x, deadband=deadband)
plt.plot(t, x, label='x(t)')
plt.plot(t, y, '--', label='backlash(x(t))')
plt.xlabel('t')
plt.legend(framealpha=1, shadow=True)
plt.grid(alpha=0.5)
plt.show()
Update: I implemented the backlash
function as a NumPy gufunc in my ufunclab repository .更新:我在我的ufunclab 存储库中将backlash
函数实现为 NumPy gufunc 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.