将函数作为参数传递给类

时间:2014-05-30 16:26:40

标签: python python-2.7 numpy scipy

我有一个函数由:

import scipy.special
def p(z):
    z0=1./3.;eta=1.0
    value=eta*(z**2)*numpy.exp(-1*(z/z0)**eta)/scipy.special.gamma(3./eta)/z0**3 
    return value

我想将此函数传递给以下类,该类位于名为redshift_probability.py的文件中作为参数p

import pylab
import numpy
import pylab
import numpy

class GeneralRandom:
  """This class enables us to generate random numbers with an arbitrary 
  distribution."""

  def __init__(self, x = pylab.arange(-1.0, 1.0, .01), p = None, Nrl = 1000):
    """Initialize the lookup table (with default values if necessary)
    Inputs:
    x = random number values
    p = probability density profile at that point
    Nrl = number of reverse look up values between 0 and 1"""  
    if p == None:
      p = pylab.exp(-10*x**2.0)
    self.set_pdf(x, p, Nrl)

  def set_pdf(self, x, p, Nrl = 1000):
    """Generate the lookup tables. 
    x is the value of the random variate
    pdf is its probability density
    cdf is the cumulative pdf
    inversecdf is the inverse look up table

    """

    self.x = x
    self.pdf = p/p.sum() #normalize it
    self.cdf = self.pdf.cumsum()
    self.inversecdfbins = Nrl
    self.Nrl = Nrl
    y = pylab.arange(Nrl)/float(Nrl)
    delta = 1.0/Nrl
    self.inversecdf = pylab.zeros(Nrl)    
    self.inversecdf[0] = self.x[0]
    cdf_idx = 0
    for n in xrange(1,self.inversecdfbins):
      while self.cdf[cdf_idx] < y[n] and cdf_idx < Nrl:
        cdf_idx += 1
      self.inversecdf[n] = self.x[cdf_idx-1] + (self.x[cdf_idx] - self.x[cdf_idx-1]) * (y[n] - self.cdf[cdf_idx-1])/(self.cdf[cdf_idx] - self.cdf[cdf_idx-1]) 
      if cdf_idx >= Nrl:
        break
    self.delta_inversecdf = pylab.concatenate((pylab.diff(self.inversecdf), [0]))

  def random(self, N = 1000):
    """Give us N random numbers with the requested distribution"""

    idx_f = numpy.random.uniform(size = N, high = self.Nrl-1)
    idx = pylab.array([idx_f],'i')
    y = self.inversecdf[idx] + (idx_f - idx)*self.delta_inversecdf[idx]

    return y

当我调用类时,我不知道如何将输入参数x作为输入参数传递给函数p(z)

 from redshift_probability import GeneralRandom
 z_pdf=GeneralRandom()

如果我这样做,我会收到错误:

 z_pdf.set_pdf( x=numpy.arange(0, 1.5, .001),p(x),N=1000000)

如何修改它?

1 个答案:

答案 0 :(得分:1)

我认为您希望将GeneralRandom.__init__更改为:

  def __init__(self, x = pylab.arange(-1.0, 1.0, .01), p_func=None, Nrl = 1000):
    """Initialize the lookup table (with default values if necessary)
    Inputs:
    x = random number values
    p_func = function to compute probability density profile at that point
    Nrl = number of reverse look up values between 0 and 1"""  
    if p_func is None:
        self.p_val = pylab.exp(-10*x**2.0)
    else:
        self.p_val = p_func(x)

然后这样称呼:

GeneralRandom(p_func=p)

这样,如果您提供p_func,它将以x作为参数进行调用,但如果未提供,则会将其设置为与之前相同的默认值。无需明确调用set_pdf,因为它在__init__结束时被调用。