2017-08-17 38 views
0

我想实现从部分“简化的语法”这里的SciPy的脚本SciPy的拟合脚本:http://scipy-cookbook.readthedocs.io/items/FittingData.htmlPython的 - 无法实现

我的代码是很长,所以我只张贴似乎零件成为问题。

我收到以下错误信息:TypeError: unsupported operand type(s) for *: 'int' and 'Parameter',我明白为什么会发生:它在这部分产品:return self.amplitude() * np.exp(-1*self.decay_const()*x)

class Plot(): 

    def __init__(self,slice_and_echo,first_plot,right_frame): 

     self.slice_and_echo = slice_and_echo 
     self.first_plot  = first_plot 
     self.right_frame = right_frame 

     self.amplitude = Parameter(1) 
     self.decay_const = Parameter(1) 

    def function(self,x): 
     print(self.amplitude) 
     print(self.amplitude()) 
     return self.amplitude() * np.exp(-1*self.decay_const()*x) 

    def create_plot(self): 
     plot_figure = Figure(figsize=(10,10), dpi=100) 
     self.the_plot = plot_figure.add_subplot(111) 

     self.the_plot.plot(self.echoes,self.average,'ro') 

     print(self.amplitude()) 

     self.fit_parameters = self.fit(self.function,[self.amplitude,self.decay_const],self.average) 
     print(self.fit_parameters) 


    def fit(self,function, parameters, y, x=None): 

     def f(params): 
      i = 0 
      for p in parameters: 
       p.set(params[i]) 
       i += 1 
      return y - function(x) 

     if x is None: x = np.arange(y.shape[0]) 

     p = [param for param in parameters] 

     return optimize.leastsq(f, p) 

和参数()类是相同的链接:

class Parameter: 
    def __init__(self, value): 
      self.value = value 

    def set(self, value): 
      self.value = value 

    def __call__(self): 
      return self.value 

这个问题似乎是,当我打电话self.amplitude()create_plot(self):方法里面,它返回的值是一个整数(这是我想要的!)。但是,当我在function(self,x)方法中调用它时不会发生这种情况;当我用这种方法打印时,我得到:<__main__.Parameter object at 0x1162845c0>而不是整数1.

为什么在同一个类的不同方法中调用时会返回不同的值?我在这里错过了什么?

谢谢!

回答

1

您在列表理解中遇到了拼写错误。您的代码规定:

p = [param for param in parameters] 

和示例代码状态:

p = [param() for param in parameters] 

注意,在你的情况,你正在生成Parameter类型,而不是号码列表的对象的列表。

顺便问一下,检查出的模块调用lmfit - 它通过大量的简化了安装程序。

+0

忍不住注意到熟悉的方程式。前段时间,我正在处理光子回波衰减曲线,所以这些代码可能会有所帮助:拟合衰减曲线:https://github.com/9dogs/edp/blob/1b9d6629922db404ed397e150f9d1482be0b376e/main.py#L474拟合峰值曲线: https://github.com/9dogs/edp/blob/1b9d6629922db404ed397e150f9d1482be0b376e/fitting/fit.py#L41 – 9dogs

+0

非常感谢。我尝试了很多东西来实现它,可能忘记在某个时刻放回括号。 并感谢代码!我会看看它! –

+0

我设法实现了lmfit!谢谢!但有一个问题:我们是否需要提取参数并自己创建拟合曲线?或者我们可以从最小化方法输出中提取曲线吗? –