I have some data points with errors in both the x and y coordinates on these data points. I therefore need to use python’s scipy.odr.ODR
tool to compute the best-fit slope and the error on this slope. However, when I try to add in error, the ODR fails and just returns the initial guess parameters.
I have tried running it without errors and it works as expected:
# Import statements
import numpy as np
import matplotlib.pyplot as plt
from scipy.odr import ODR, Model, Data, RealData
# Model function - linear fit
def model_func(params, x):
m, c = params
return m * x + c
#Model object - linear fit
model = Model(model_func)
# example data
n = 50
x = np.linspace(0, 50, n)
y = 2.0 * x + 1.0
x_err = np.abs(np.random.normal(0,2.5,n))
y_err = np.abs(np.random.normal(0,2.5,n))
x_data = np.random.normal(x,x_err,n)
y_data = np.random.normal(y,y_err,n)
# Data object with errors
data1 = Data(x_data, y_data, wd=1./x_err, we=1./y_err)
# Data object without errors
data2 = Data(x_data, y_data)
# odr object, and parameters for data1
odr1 = ODR(data1, model, beta0=[1., 1.])
odr1.set_job(fit_type=0)
output1 = odr1.run()
params1 = output1.beta
param_errors1 = output1.sd_beta
# odr object, and parameters for data1
odr2 = ODR(data2, model, beta0=[1., 1.])
odr2.set_job(fit_type=0)
output2 = odr2.run()
params2 = output2.beta
param_errors2 = output2.sd_beta
print("Fitted parameters with err:", params1)
print("Parameter errors with err:", param_errors1)
print("Fitted parameters without err:", params2)
print("Parameter errors without err:", param_errors2)
# Draw plots
fig, ax = plt.subplots()
plt.errorbar(x_data, y_data, yerr=y_err, xerr=x_err, linestyle="", marker="o", label="data")
plt.axline((x_data[0],model_func(params1,x_data[0])),slope=params1[0], color="k", label="Fit without errors")
plt.axline((x_data[0],model_func(params2,x_data[0])),slope=params2[0], color="r", label="Fit with errors")
plt.legend()
plt.show()
The print statements give:
Fitted parameters with err: [1. 1.]
Parameter errors with err: [0. 0.]
Fitted parameters without err: [1.94789948 2.92857792]
Parameter errors without err: [0.05371152 1.5487141 ]
And this is the image: Data and lines of best fit
What is going wrong when I add the error parameters?
ReplacementAd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.