python节点/分段线性幂律发生器

时间:2014-08-02 12:51:04

标签: python numpy scipy

我需要有效的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内置插件。

有点相关:Fitting piecewise function in 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增加,这必须变慢。将列表理解或其他任何东西加速循环?

谢谢!

1 个答案:

答案 0 :(得分:0)

最后,我选择了优秀的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.
"""

好像在游泳。