Following exercise comes from Hogg, Bovy, and Lang (2010). The link is http://adsabs.harvard.edu/abs/2010arXiv1008.4686H.
In [1]:
from astropy.io import ascii
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
In [2]:
dat = ascii.read("../data/hogg-et-al-2010-table1.csv")
print(dat)
In [3]:
A = np.ones((len(dat["x"]), 2))
A[:, 1] = dat["x"]
C = np.zeros((len(dat["ey"]), len(dat["ey"])))
np.fill_diagonal(C, pow(dat["ey"], 2.))
In [4]:
term1 = np.linalg.inv(np.matmul(np.matmul(A.T, np.linalg.inv(C)), A))
term2 = np.matmul(np.matmul(A.T, np.linalg.inv(C)), dat["y"])
b, m = np.matmul(term1, term2)
In [5]:
eb, em = np.sqrt(term1[0, 0]), np.sqrt(term1[1, 1])
In [6]:
plt.errorbar(dat["x"], dat["y"], dat["ey"], marker=".", ls="none")
plt.plot(dat["x"], m * dat["x"] + b)
plt.xlabel("x-coordinate")
plt.ylabel("y-coordinate")
pf = "y = ({:.2f}$\pm${:.2f})x + ({:.2f}$\pm${:.2f})".format(m, em, b, eb)
plt.text(s=pf, x=50, y=200, color="C1", size=16)
plt.show();
In [ ]: