-
Notifications
You must be signed in to change notification settings - Fork 1
/
Magnetometer_Calibration_Code.py
164 lines (123 loc) · 4.34 KB
/
Magnetometer_Calibration_Code.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#The following code is courtesy of The Poor Engineer website and can be found at https://thepoorengineer.com/en/calibrating-the-magnetometer/
#Compared to the original file, minor changes were made in order to meet this project's needs.
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy import linalg
import csv, os
# In[2]:
def fitEllipsoid(magX, magY, magZ):
a1 = magX ** 2
a2 = magY ** 2
a3 = magZ ** 2
a4 = 2 * np.multiply(magY, magZ)
a5 = 2 * np.multiply(magX, magZ)
a6 = 2 * np.multiply(magX, magY)
a7 = 2 * magX
a8 = 2 * magY
a9 = 2 * magZ
a10 = np.ones(len(magX)).T
D = np.array([a1, a2, a3, a4, a5, a6, a7, a8, a9, a10])
# Eqn 7, k = 4
C1 = np.array([[-1, 1, 1, 0, 0, 0],
[1, -1, 1, 0, 0, 0],
[1, 1, -1, 0, 0, 0],
[0, 0, 0, -4, 0, 0],
[0, 0, 0, 0, -4, 0],
[0, 0, 0, 0, 0, -4]])
# Eqn 11
S = np.matmul(D, D.T)
S11 = S[:6, :6]
S12 = S[:6, 6:]
S21 = S[6:, :6]
S22 = S[6:, 6:]
# Eqn 15, find eigenvalue and vector
# Since S is symmetric, S12.T = S21
tmp = np.matmul(np.linalg.inv(C1), S11 - np.matmul(S12, np.matmul(np.linalg.inv(S22), S21)))
eigenValue, eigenVector = np.linalg.eig(tmp)
u1 = eigenVector[:, np.argmax(eigenValue)]
# Eqn 13 solution
u2 = np.matmul(-np.matmul(np.linalg.inv(S22), S21), u1)
# Total solution
u = np.concatenate([u1, u2]).T
Q = np.array([[u[0], u[5], u[4]],
[u[5], u[1], u[3]],
[u[4], u[3], u[2]]])
n = np.array([[u[6]],
[u[7]],
[u[8]]])
d = u[9]
return Q, n, d
# In[3]:
def main():
#delete zeros
with open('magnetometer01.csv', 'r') as inp, open("C:/Users/Karla/Desktop/FER/ADCS/04_kalibracija magnetometra/mjerenja/magnetometer01_wout0.csv", 'w', newline='') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[0] != "0":
if row[1] != "0":
if row[2] != "0":
writer.writerow(row)
data = np.genfromtxt('C:/Users/Karla/Desktop/FER/ADCS/04_kalibracija magnetometra/mjerenja/magnetometer01_wout0.csv', dtype=int, delimiter=',')
magX = data[:, 0]
magY = data[:, 1]
magZ = data[:, 2]
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111, projection='3d')
ax1.scatter(magX, magY, magZ, s=5, color='r')
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
ax1.set_zlabel('Z')
# plot unit sphere
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax1.plot_wireframe(x, y, z, rstride=10, cstride=10, alpha=0.5)
ax1.plot_surface(x, y, z, alpha=0.3, color='b')
Q, n, d = fitEllipsoid(magX, magY, magZ)
Qinv = np.linalg.inv(Q)
b = -np.dot(Qinv, n)
Ainv = np.real(1 / np.sqrt(np.dot(n.T, np.dot(Qinv, n)) - d) * linalg.sqrtm(Q))
print("A_inv: ")
print(Ainv)
print()
print("b")
print(b)
print()
calibratedX = np.zeros(magX.shape)
calibratedY = np.zeros(magY.shape)
calibratedZ = np.zeros(magZ.shape)
totalError = 0
for i in range(len(magX)):
h = np.array([[magX[i], magY[i], magZ[i]]]).T
hHat = np.matmul(Ainv, h-b)
calibratedX[i] = hHat[0]
calibratedY[i] = hHat[1]
calibratedZ[i] = hHat[2]
mag = np.dot(hHat.T, hHat)
err = (mag[0][0] - 1)**2
totalError += err
print("Total Error: %f" % totalError)
fig2 = plt.figure(2)
ax2 = fig2.add_subplot(111, projection='3d')
ax2.scatter(calibratedX, calibratedY, calibratedZ, s=1, color='r')
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
ax2.set_zlabel('Z')
# plot unit sphere
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax2.plot_wireframe(x, y, z, rstride=10, cstride=10, alpha=0.5)
ax2.plot_surface(x, y, z, alpha=0.3, color='b')
plt.show()
# In[4]:
if __name__ == '__main__':
main()