简体   繁体   English

两个预定义函数的组合(分段)function

[英]Combination (piecewise) function of two pre-defined functions

I'm currently making a custom function that I will eventually feed into scipy.optimize.curve_fit() for a custom curve fit.我目前正在制作一个自定义 function ,我最终将输入 scipy.optimize.curve_fit() 以进行自定义曲线拟合。 My curve fit will be shaped like a bump.我的曲线合身将像一个凹凸。 Gaussian rise and exponential fall, pieced together at the highest point of the gaussian.高斯上升和指数下降,拼凑在高斯的最高点。 I have defined a Gaussian and an exponential function and currently trying to define a combo() function.我已经定义了一个高斯和一个指数 function,目前正在尝试定义一个组合() function。 Here's what I have so far:这是我到目前为止所拥有的:

    def exp(x, a, b, c):
          return a * np.exp((-b * x) + c)
    def gauss(x,d,e,f):
          return d * np.exp(-((x-e)**2)/(2*(f**2)))
    def combo(x,a,b,c,d,e,f):
          ex = exp(x,a,b,c)
          ga = gauss(x,d,e,f)
    num = np.arange(0,1000,1)
    test =combo(num,1,2,3,10,4,3)

I've tried to use if statements in my combo function (if x<d: return ga) but I get the error message: "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()".我尝试在组合 function 中使用 if 语句(如果 x<d: return ga),但我收到错误消息:“具有多个元素的数组的真值不明确。使用 a.any() 或a.all()”。 Maybe this is the solution but I'm not sure how to employ it.也许这是解决方案,但我不确定如何使用它。

def combo(x,a,b,c,d,e,f, dtype=np.float64):
    def gauss(x,d,e,f):
        return d * np.exp(-((x-e)**2)/(2*(f**2)))
    def exp(x, a, b, c):
        return a * np.exp((-b * x) + c)
    result = np.piecewise(
        x,
        [x <= e,x > e],
        [lambda x: gauss(x,d,e,f), lambda x: exp(x,a,b,c)],
    )
    return result

I think the best way to do this using numpy is to use array slicing.我认为使用numpy执行此操作的最佳方法是使用数组切片。 First, create the test array as a Gaussian, then find the index where it reaches its max value, and then replace the array from that point on with the value calculated using the exponential function:首先,将test数组创建为高斯数组,然后找到它达到最大值的索引,然后用指数 function 计算的值替换从该点开始的数组:

def exp(x, a, b, c):
      return a * np.exp(-c * (x-b))
def gauss(x, a, b, d):
      return a * np.exp(-((x-b)**2)/(2*(d**2)))
def combo(x, a, b, c, d):
    y = gauss(x, a, b, d)
    g_max_ind = y.argmax()
    y[g_max_ind+1:] = exp(x[g_max_ind+1:], a, b, c)
    return y
num = np.arange(-50, 50, 0.5)
test = combo(num, 10, 4, 3, 3)

I assume that you want this function to be continuous, so I changed your parameters so that the values input into exp and gauss are consistent with each other, and I changed the arange parameters so the plot is more meaningful.我假设你希望这个 function 是连续的,所以我改变了你的参数,使输入到expgauss的值彼此一致,我改变了arange参数,所以 plot 更有意义。 Please let me know if I misunderstood and I can correct.如果我误解了,请告诉我,我可以纠正。

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM