2014-07-10 332 views
1

所以我的目標是讓我自己的數據點適合黑體曲線,但是我有困難。曲線擬合普朗克曲線

的我在做什麼的輪廓上

http://python4esac.github.io/fitting/example_blackbody.html

但他們使用的隨機數據,我想用我自己的CSV數據。

這個數據是:

Wavelength 
0.7, 
0.865, 
1.24, 
1.61, 
3.7, 
4.05, 

Radiance 
0, 
0.106718, 
0.227031, 
0.373527, 
0.240927, 
0.293215, 

反正是有讓Python將進入文件,並使用這兩列呢?我迄今爲止嘗試過的所有東西都失敗了。

我的代碼如下

import csv 
with open('PythonCode1.csv', 'rb') as f: 
    reader = csv.reader(f, delimiter=',') 
    for row in reader: 

     from scipy.optimize import curve_fit 
import pylab as plt 
from pylab import plotfile, show, gca 
fid=open('PythonCode1.csv','r') 
import numpy as np 
import matplotlib.cbook as cbook   
def blackbody_lam(lam, T): 
    """ Blackbody as a function of wavelength (um) and temperature (K). 

    """ 
    from scipy.constants import h,k,c 
    lam = 1e-6 * lam # convert to metres 
    return 2*h*c**2/(lam**5 * (np.exp(h*c/(lam*k*T)) - 1)) 

    wa = np.linspace(0.1, 6, 100) # wavelengths in um 
T1 = 1000. 
T2 = 2500. 
y1 = blackbody_lam(wa, T1) 
y2 = blackbody_lam(wa, T2) 
ytot = y1 + y2 

sigma = np.ones(len(wa)) * 1 * np.median(ytot) 
ydata = ytot + csv.row[1].randn(len(wa)) * sigma 


and returns 

%run "d:\temp\k1339544\tmpskczzu.py" 
--------------------------------------------------------------------------- 
AttributeError       Traceback (most recent call last) 
R:\Canpy103.001\Canopy32\App\appdata\canopy-1.0.3.1262.win-x86\lib\site- packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc) 
    174    else: 
    175     filename = fname 
--> 176    exec compile(scripttext, filename, 'exec') in glob, loc 
    177  else: 
    178   def execfile(fname, *where): 

d:\temp\k1339544\tmpskczzu.py in <module>() 
    27 
    28 sigma = np.ones(len(wa)) * 1 * np.median(ytot) 
---> 29 ydata = ytot + csv.rows[1].randn(len(wa)) * sigma 
    30 
    31 # plot the input model and synthetic data 

AttributeError: 'module' object has no attribute 'rows' 

回答

1

而不是設置waydata人工數據,如示例中做,你要提供你自己的數據。

如果格式化數據,兩列:

Wavelength,Radiance 
0.7,0 
0.865,0.106718 
1.24,0.227031 
1.61,0.373527 
3.7,0.240927 
4.05,0.293215 

那麼你就可以

data = np.loadtxt("PythonCode1.csv", delimiter=",", skiprows=1) 
wa = data[:,0] 
ydata = data[:,1] 

這攝取它並不能保證該功能可滿足您的數據(它不能,黑體功能缺少可調整的比例參數)或者擬合會收斂,但這是獲取數據的最簡單方法。

+0

非常感謝!我知道這應該工作,但Python不斷回來 ValueError:x和y必須具有相同的第一維 我已檢查列的長度相等,但仍不知道python試圖讓我改變。 – user3825343

+0

哪一行給你ValueError,你確定'wa.shape == ydata.shape'? – wltrimbl