-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpower_law_fit_weighted_uncertainties.py
72 lines (57 loc) · 1.84 KB
/
power_law_fit_weighted_uncertainties.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import numpy as np
import matplotlib.pyplot as plt
# generating fake data to test power fit (you would just use your own x, y and dy values)
# Parameters for the power law y = a * x^b
a_true = 2.0
b_true = 1.5
# Generate synthetic data
np.random.seed(42)
x = np.linspace(1, 10, 20)
y_true = a_true * x**b_true
# Adding noise to the data (uncertainty)
dy = np.abs(0.2 * y_true * np.random.normal(size=x.size)) # 20% noise, ensuring positive uncertainties
y = y_true + dy
# linearizing data
Y = np.log(y)
X = np.log(x)
Y_uncertainty = (dy)/(y)
weights = 1/Y_uncertainty**2
# then follows least linear weighted squares method
# For solving normal equations
weight_sum = np.sum(weights)
S_x = np.sum(weights*X)
S_xx = np.sum(weights*(X**2))
S_xy = np.sum(weights*X*Y)
S_y = np.sum(weights*Y)
# Finding cool fit parameters
delta = S_xx*weight_sum - (S_x**2)
A = (weight_sum*S_xy - S_x*S_y)/delta
B = (S_xx*S_y - S_x*S_xy)/delta
A_uncertainty = np.sqrt(weight_sum/delta)
B_uncertainty = np.sqrt(S_xx/delta)
# Convert back to original space
a_fit = np.exp(B)
b_fit = A
uncertainty_b_fit = A_uncertainty
uncertainty_a_fit = a_fit*B_uncertainty
# Recalculate the fit in original space
y_fit = a_fit * x**b_fit
# Calculate residuals and chi-squared
residuals = Y - (A * X + B)
chi_squared = np.sum(weights * residuals**2)
print("Chi^2 value is: ", chi_squared)
print("a (coefficient) is: ", a_fit, "+/- ", uncertainty_a_fit)
print("b (exponent) is: ", b_fit, "+/- ", uncertainty_b_fit)
# Plotting the fit function
plt.errorbar(x, y, yerr=dy, fmt='o', label='Data with uncertainties', color='blue', ecolor='gray', capsize=5)
plt.plot(x, y_fit, label=f'Fit: y = {a_fit:.2f} * x^{b_fit:.2f}', color='red')
# Add axis labels
plt.xlabel('x-axis')
plt.ylabel('y-axis')
# Add a title
plt.title('Graph of Power-Law Fit')
# Add a legend
plt.legend()
# Show the plot
plt.grid(True)
plt.show()