Python节点/分段线性幂律生成器



我需要有效的python代码,它返回(不适合)一个分段线性(或者,实际上,分段幂律)连续函数,用于任意数量的节点(/极点/控制点),这些节点(/极点/控制点)由它们的位置加上(最好)斜率而不是振幅定义。例如,对于三个部分(四个节点),我有:

def powerLawFuncTriple(x,C,alpha,beta,gamma,xmin,xmax,x0,x1):
    """
    Extension of the two-power-law version described at
       http://en.wikipedia.org/wiki/Power_law#Broken_power_law
    """
    if x <= xmin or x > xmax:
        return 0.0
    elif xmin < x <= x0:
        n = C * (x ** alpha)
    elif x0 < x <= x1:
        n = C * x0**(alpha-beta) * (x ** beta)
    elif x1 < x <= xmax:
        n = C  * x0**(alpha-beta) * x1**(beta-gamma) * (x ** gamma)
    return n

有任何有用的函数已经存在,否则什么是一个有效的方式来编写代码来生成这些函数?也许这相当于评估而不是拟合一个scipy内置函数。

有点相关:Python中的分段拟合函数

一个可能的答案是:

def piecewise(x,n0,posns=[1.0,2.0,3.0],alpha=[-2.0,-1.5]):
    if x <= posns[0] or x > posns[-1]: return 0.0
    n=n0*x**alpha[0]
    np=len(posns)
    for ip in range(np):
        if posns[ip] < x <= posns[ip+1]: return n
        n *= (posns[ip+1]/float(x))**(alpha[ip]-alpha[ip+1])
    return n

但是随着x的增加,这一定会变慢。列表理解或其他东西会加速循环吗?

谢谢!

最后我选择了优秀的CosmoloPy模块:

http://pydoc.net/Python/CosmoloPy/0.1.103/cosmolopy.utils

class PiecewisePowerlaw()
"""
You can specify the intervals and power indices, and this class
will figure out the coefficients needed to make the function
continuous and normalized to unit integral.
"""

最新更新