2017-08-17 34 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!謝謝!但有一個問題:我們是否需要提取參數並自己創建擬合曲線?或者我們可以從最小化方法輸出中提取曲線嗎? –