ALGO_Kalman_ATY.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /**
  2. * @file ALGO_Kalman_ATY.c
  3. *
  4. * @param Project ALGO_Algorithm_ATY_LIB
  5. *
  6. * @author ATY
  7. *
  8. * @copyright
  9. * - Copyright 2017 - 2026 MZ-ATY
  10. * - This code follows:
  11. * - MZ-ATY Various Contents Joint Statement -
  12. * <a href="https://mengze.top/MZ-ATY_VCJS">
  13. * https://mengze.top/MZ-ATY_VCJS</a>
  14. * - CC 4.0 BY-NC-SA -
  15. * <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
  16. * https://creativecommons.org/licenses/by-nc-sa/4.0/</a>
  17. * - Your use will be deemed to have accepted the terms of this statement.
  18. *
  19. * @brief functions of Kalman
  20. *
  21. * @note
  22. * https://www.kalmanfilter.net/
  23. * https://github.com/xiahouzuoxin/kalman_filter
  24. * https://blog.csdn.net/whereismatrix/article/details/79920748
  25. *
  26. * @version
  27. * - 1_01_220605 > ATY
  28. * -# Preliminary version, first Release
  29. * - 1_02_230108 > ATY
  30. * -# Finish and test 2D
  31. ********************************************************************************
  32. */
  33. #ifndef __ALGO_Kalman_ATY_C
  34. #define __ALGO_Kalman_ATY_C
  35. #include "ALGO_Kalman_ATY.h"
  36. /******************************* For user *************************************/
  37. /******************************************************************************/
  38. #if !Kalman1D_TYPE // use below instead
  39. /**
  40. * @brief Kalman filter one-dimensional with A = H = 1
  41. * @param kfp kalman struct init value
  42. * @param input filter data(series)
  43. * @return data after filter
  44. * @note Origin equations
  45. * - State Equation
  46. * x(k) = A * x(k-1) + B * u(k) + w(k-1)
  47. * (if no controlled quantity then: B * u(k)=0, like detect Tem/Hum)
  48. * - Observations Equation
  49. * z(k) = H * x(k) + y(k)
  50. * - Prediction Equations
  51. * x(k|k-1) = A * x(k-1|k-1) + B * u(k)
  52. * P(k|k-1) = A * P(k-1|k-1) * A^T + Q
  53. * - Correction Equations
  54. * K(k) = P(k|k-1) * H^T * (H * P(k|k-1) * H^T + R)^(-1)
  55. * x(k|k) = x(k|k-1) + K(k) * (z(k) - H * x(k|k-1))
  56. * P(k|k) = (I - K(k) * H) * P(k|k-1)
  57. * @note Equations Note:
  58. * x and P only need to be assigned initial values, each iteration will produce new values; K does not need to be assigned an initial value
  59. * Q and R assignments can also be changed in subsequent iterations
  60. * The initial values of x and P can be arbitrarily set, and the powerful Kalman filter will immediately erase the irrdibility
  61. * But notice that the initial value of P cannot be 0, otherwise the filter will think that there is no error
  62. * The larger R is, the smoother the curve is, but the filter becomes insensitive and lags exist
  63. * (The value of Q and R can also be time-varying, can recognize jump changes, can be adaptive)
  64. * Q: process noise, Q increases, dynamic response becomes faster, convergence stability becomes worse
  65. * R: measurement noise, R increases, the dynamic response becomes slower, and the convergence stability becomes better
  66. */
  67. float ALGO_KalmanFilter1D(ALGO_Kalman1D_S* kfp, float input){
  68. // Prediction covariance:
  69. // estimated system covariance at time k
  70. // = system covariance at time k-1 + process noise covariance
  71. kfp->P = kfp->L_P + kfp->Q;
  72. // Kalman gain:
  73. // Kalman gain
  74. // = system estimated covariance at time k
  75. kfp->G = kfp->P / (kfp->P + kfp->R);
  76. // Update the optimal value:
  77. // Optimal value of state variable at time k
  78. // = predicted value of state variable + Kalman gain
  79. // * (Measured value - predicted value of state variable)
  80. // / (system estimated covariance at time k + observation noise covariance)
  81. kfp->O = kfp->O + kfp->G * (input - kfp->O);
  82. // Update the covariance:
  83. // this time the system covariance is paid to kfp->LastP for the next operation
  84. kfp->L_P = (1 - kfp->G) * kfp->P;
  85. return kfp->O;
  86. }
  87. #else
  88. /**
  89. * @brief Kalman filter one-dimensional
  90. * @param kfp kalman struct init value
  91. * @param input filter data(series)
  92. * @return data after filter
  93. * @note Origin equations
  94. * - State Equation
  95. * x(k) = A * x(k-1) + B * u(k) + w(k-1)
  96. * (if no controlled quantity then: B * u(k)=0, like detect Tem/Hum)
  97. * - Observations Equation
  98. * z(k) = H * x(k) + y(k)
  99. * - Prediction Equations
  100. * x(k|k-1) = A * x(k-1|k-1) + B * u(k)
  101. * P(k|k-1) = A * P(k-1|k-1) * A^T + Q
  102. * - Correction Equations
  103. * K(k) = P(k|k-1) * H^T * (H * P(k|k-1) * H^T + R)^(-1)
  104. * x(k|k) = x(k|k-1) + K(k) * (z(k) - H * x(k|k-1))
  105. * P(k|k) = (I - K(k) * H) * P(k|k-1)
  106. * @note Equations Note:
  107. * x and P only need to be assigned initial values, each iteration will produce new values; K does not need to be assigned an initial value
  108. * Q and R assignments can also be changed in subsequent iterations
  109. * The initial values of x and P can be arbitrarily set, and the powerful Kalman filter will immediately erase the irrdibility
  110. * But notice that the initial value of P cannot be 0, otherwise the filter will think that there is no error
  111. * The larger R is, the smoother the curve is, but the filter becomes insensitive and lags exist
  112. * (The value of Q and R can also be time-varying, can recognize jump changes, can be adaptive)
  113. * Q: process noise, Q increases, dynamic response becomes faster, convergence stability becomes worse
  114. * R: measurement noise, R increases, the dynamic response becomes slower, and the convergence stability becomes better
  115. * @note A = H = 1 in always use
  116. */
  117. float ALGO_KalmanFilter1D(ALGO_Kalman1D_S* kfp, float input){
  118. // Prediction covariance:
  119. // estimated system covariance at time k
  120. // = system covariance at time k-1 + process noise covariance
  121. kfp->X = kfp->A * kfp->X;
  122. kfp->P = kfp->A * kfp->A * kfp->P + kfp->Q;
  123. // Kalman gain:
  124. // Kalman gain
  125. // = system estimated covariance at time k
  126. kfp->G = kfp->P * kfp->H / (kfp->P * kfp->H * kfp->H + kfp->R);
  127. // Update the optimal value:
  128. // Optimal value of state variable at time k
  129. // = predicted value of state variable + Kalman gain
  130. // * (Measured value - predicted value of state variable)
  131. // / (system estimated covariance at time k + observation noise covariance)
  132. kfp->X = kfp->X + kfp->G * (input - kfp->H * kfp->X);
  133. // Update the covariance:
  134. // this time the system covariance is paid to kfp->LastP for the next operation
  135. kfp->P = (1 - kfp->G * kfp->H) * kfp->P;
  136. return kfp->X;
  137. }
  138. #endif /* 01 */
  139. #ifdef Kalman_2D
  140. /**
  141. * @brief Kalman filter two-dimensional
  142. * @param kfp kalman struct init value
  143. * @param input filter data(series)
  144. * @return data after filter
  145. * @note allways in default:
  146. * A = {{1, 0.1}, {0, 1}};
  147. * H = {1, 0};
  148. */
  149. float ALGO_KalmanFilter2D(ALGO_Kalman2D_S* kfp, float input){
  150. float temp[3] = {0.0};
  151. /* Step1: Predict */
  152. kfp->X[0] = kfp->A[0][0] * kfp->X[0] + kfp->A[0][1] * kfp->X[1];
  153. kfp->X[1] = kfp->A[1][0] * kfp->X[0] + kfp->A[1][1] * kfp->X[1];
  154. /* P(n|n-1)=A^2*P(n-1|n-1)+Q */
  155. kfp->P[0][0] = kfp->A[0][0] * kfp->P[0][0] + kfp->A[0][1] * kfp->P[1][0] + kfp->Q[0][0];
  156. kfp->P[0][1] = kfp->A[0][0] * kfp->P[0][1] + kfp->A[1][1] * kfp->P[1][1] + kfp->Q[0][1];
  157. kfp->P[1][0] = kfp->A[1][0] * kfp->P[0][0] + kfp->A[0][1] * kfp->P[1][0] + kfp->Q[1][0];
  158. // kfp->P[0][1] = kfp->A[0][0] * kfp->P[0][1] + kfp->A[1][1] * kfp->P[1][1];
  159. // kfp->P[1][0] = kfp->A[1][0] * kfp->P[0][0] + kfp->A[0][1] * kfp->P[1][0];
  160. kfp->P[1][1] = kfp->A[1][0] * kfp->P[0][1] + kfp->A[1][1] * kfp->P[1][1] + kfp->Q[1][1];
  161. /* Step2: Measurement */
  162. /* G = P * H^T * [R + H * P * H^T]^(-1), H^T means transpose. */
  163. temp[0] = kfp->P[0][0] * kfp->H[0] + kfp->P[0][1] * kfp->H[1];
  164. temp[1] = kfp->P[1][0] * kfp->H[0] + kfp->P[1][1] * kfp->H[1];
  165. temp[2] = kfp->R + kfp->H[0] * temp[0] + kfp->H[1] * temp[1];
  166. kfp->G[0] = temp[0] / temp[2];
  167. kfp->G[1] = temp[1] / temp[2];
  168. /* x(n|n) = x(n|n-1) + G(n) * [input - H(n)*x(n|n-1)]*/
  169. temp[2] = kfp->H[0] * kfp->X[0] + kfp->H[1] * kfp->X[1];
  170. kfp->X[0] = kfp->X[0] + kfp->G[0] * (input - temp[2]);
  171. kfp->X[1] = kfp->X[1] + kfp->G[1] * (input - temp[2]);
  172. /* Update @P: P(n|n) = [I - G * H] * P(n|n-1) */
  173. kfp->P[0][0] = (1 - kfp->G[0] * kfp->H[0]) * kfp->P[0][0];
  174. kfp->P[0][1] = (1 - kfp->G[0] * kfp->H[1]) * kfp->P[0][1];
  175. kfp->P[1][0] = (1 - kfp->G[1] * kfp->H[0]) * kfp->P[1][0];
  176. kfp->P[1][1] = (1 - kfp->G[1] * kfp->H[1]) * kfp->P[1][1];
  177. return kfp->X[0];
  178. }
  179. #endif /* Kalman_2D */
  180. #ifdef ALGO_Kalman_ATY_Test_ATY
  181. #if !Kalman1D_TYPE
  182. ALGO_Kalman1D_S ALGO_kfp1D = {1, 0, 0, 0, 1e-9, 1e-6};
  183. #else
  184. ALGO_Kalman1D_S ALGO_kfp1D = {0, 0, 1, 1, 1, 1e-9, 1e-6};
  185. #endif /* Kalman1D_TYPE */
  186. #ifdef Kalman_2D
  187. ALGO_Kalman2D_S ALGO_kfp2D =
  188. {
  189. {0, 0},
  190. {0, 0},
  191. {{1, 0.1}, {0, 1}},
  192. {1, 0},
  193. {{1, 0}, {0, 1}},
  194. {{1e-9, 0}, {0, 1e-9}},
  195. 10e-6
  196. };
  197. #endif /* Kalman_2D */
  198. uint16_t tempSaveOW = 0;
  199. float tempSaveO = 0;
  200. float tempSaveK = 0;
  201. float tempSaveK2 = 0;
  202. void ALGO_Kalman_Test(void){
  203. uint16_t i = 0;
  204. uint8_t testNum = 1;
  205. if(testNum == 1){
  206. ALGO_kfp1D.Q = 1e-6;
  207. ALGO_kfp1D.R = 1e-4;
  208. for(i = 0; i < 120; i++){
  209. tempSaveO = testSignalSigned[i];
  210. tempSaveK = ALGO_KalmanFilter1D(&ALGO_kfp1D, testSignalSigned[i]);
  211. #ifdef Kalman_2D
  212. tempSaveK2 = ALGO_KalmanFilter2D(&ALGO_kfp2D, testSignalSigned[i]);
  213. #endif /* Kalman_2D */
  214. printf_ATY_D("$");
  215. printf_ATY_D("%f ", testSignalSigned[i]);
  216. printf_ATY_D("%f", ALGO_KalmanFilter1D(&ALGO_kfp1D, testSignalSigned[i]));
  217. printf_ATY_D(";");
  218. }
  219. }
  220. else if(testNum == 2){
  221. ALGO_kfp1D.Q = 1e-6;
  222. ALGO_kfp1D.R = 1e-4;
  223. for(i = 0; i < 120; i++){
  224. tempSaveO = testSignalUnsigned[i];
  225. tempSaveK = ALGO_KalmanFilter1D(&ALGO_kfp1D, testSignalUnsigned[i]);
  226. #ifdef Kalman_2D
  227. tempSaveK2 = ALGO_KalmanFilter2D(&ALGO_kfp2D, testSignalUnsigned[i]);
  228. #endif /* Kalman_2D */
  229. printf_ATY_D("$");
  230. printf_ATY_D("%f ", testSignalUnsigned[i]);
  231. printf_ATY_D("%f", ALGO_KalmanFilter1D(&ALGO_kfp1D, testSignalUnsigned[i]));
  232. printf_ATY_D(";");
  233. }
  234. }
  235. else if(testNum == 3){
  236. ALGO_kfp1D.Q = 1e-9;
  237. ALGO_kfp1D.R = 1e-6;
  238. for(i = 0; i < 3000; i++){
  239. tempSaveO = (float)testSignalUint16[i];
  240. tempSaveK = ALGO_KalmanFilter1D(&ALGO_kfp1D, testSignalUint16[i]);
  241. #ifdef Kalman_2D
  242. tempSaveK2 = ALGO_KalmanFilter2D(&ALGO_kfp2D, testSignalUint16[i]);
  243. #endif /* Kalman_2D */
  244. printf_ATY_D("$");
  245. printf_ATY_D("%d ", testSignalUint16[i]);
  246. printf_ATY_D("%d", (uint16_t)ALGO_KalmanFilter1D(&ALGO_kfp1D, (float)testSignalUint16[i]));
  247. printf_ATY_D(";");
  248. }
  249. }
  250. }
  251. /*
  252. // debug output data format: $y1a y1b;$y2a y2b;...------------------------------
  253. $0.732202 0.732166;$1.107485 0.923521;$0.832648 0.891278;$0.997930 0.921472;
  254. $0.743661 0.878040;$0.928340 0.889176;$0.546396 0.818120;$0.510484 0.757106;
  255. $0.114057 0.633303;$0.181101 0.547962;$-0.103150 0.426716;$-0.561716 0.244303;
  256. $-0.307147 0.143145;$-0.921523 -0.051368;$-0.626582 -0.156174;$-0.817900 -0.276524;
  257. $-0.899243 -0.389642;$-1.011869 -0.502578;$-0.948660 -0.583498;$-1.024685 -0.663502;
  258. $-1.078591 -0.738754;$-0.854667 -0.759765;$-0.905492 -0.786177;$-0.548572 -0.743116;
  259. $-0.737286 -0.742059;$-0.450227 -0.689175;$-1.032790 -0.751442;$-0.293712 -0.668498;
  260. $-0.159926 -0.576342;$-0.117551 -0.493208;$0.363302 -0.338006;$0.637550 -0.161233;
  261. $0.284187 -0.080522;$0.737519 0.067708;$0.521005 0.149846;$0.893311 0.284563;
  262. $1.054081 0.424001;$0.525526 0.442397;$0.782144 0.503960;$1.009261 0.595521;
  263. $0.967746 0.662969;$1.229197 0.765570;$1.179795 0.840628;$0.998553 0.869244;
  264. $0.806697 0.857911;$0.615047 0.813903;$0.003506 0.667058;$0.023320 0.550412;
  265. $0.510523 0.543184;$0.020320 0.448441;$-0.168222 0.336701;$-0.358753 0.210684;
  266. $-0.424160 0.095649;$-0.492052 -0.010843;$-0.425293 -0.085942;$-0.460660 -0.153841;
  267. $-0.712114 -0.255001;$-1.311701 -0.446476;$-0.815038 -0.513260;$-0.827395 -0.570182;
  268. $-0.946493 -0.638370;$-0.962119 -0.697033;$-0.849309 -0.724626;$-0.733573 -0.726247;
  269. $-0.680960 -0.718041;$-0.742870 -0.722540;$-0.529109 -0.687490;$-0.567446 -0.665738;
  270. $-0.136456 -0.569832;$-0.199753 -0.502773;$0.169624 -0.380934;$0.231133 -0.270027;
  271. $0.686898 -0.096631;$0.284297 -0.027606;$0.491547 0.066465;$0.766148 0.193248;
  272. $0.808002 0.304642;$1.106872 0.450007;$1.134952 0.574120;$0.806723 0.616268;
  273. $1.119804 0.707509;$0.931759 0.748143;$1.326805 0.852998;$0.890237 0.859745;
  274. $0.653111 0.822303;$0.973650 0.849727;$0.903934 0.859550;$0.350950 0.767391;
  275. $0.088230 0.644326;$0.208081 0.565278;$-0.084471 0.447543;$-0.272629 0.317047;
  276. $-0.352162 0.195785;$-0.748851 0.024616;$-0.887943 -0.140741;$-0.736057 -0.248613;
  277. $-0.939653 -0.373830;$-1.119212 -0.508894;$-0.944213 -0.587774;$-0.761944 -0.619334;
  278. $-0.988381 -0.686206;$-0.681791 -0.685406;$-0.900586 -0.724397;$-1.064615 -0.786045;
  279. $-0.843333 -0.796425;$-0.718142 -0.782240;$-0.138929 -0.665672;$-0.583088 -0.650707;
  280. $-0.460869 -0.616308;$-0.050059 -0.513703;$0.101613 -0.402207;$0.150226 -0.302106;
  281. $0.593740 -0.139777;$0.454790 -0.032041;$0.612092 0.084677;$0.829426 0.219626;
  282. $0.899205 0.342766;$1.024959 0.466381;$1.159378 0.591953;$0.977459 0.661807;
  283. <!DOCTYPE html>
  284. <html>
  285. <head><title>Line</title></head>
  286. <body>
  287. <textarea id="dataInput" style="width: 795px;" placeholder="$y1a y1b;$y2a y2b;..."
  288. onchange="plotGraph()"></textarea><br>
  289. <canvas id="graphCanvas" width="800" height="400"></canvas>
  290. <script>
  291. function parseData(input) {
  292. const records = input.trim().split(';').filter(r => r.trim() !== '');
  293. const s1 = [], s2 = [];
  294. for (let r of records) {
  295. if (!r.startsWith('$')) continue;
  296. const vals = r.substring(1).trim().split(/\s+/);
  297. if (vals.length !== 2) continue;
  298. const y1 = parseFloat(vals[0]), y2 = parseFloat(vals[1]);
  299. if (isNaN(y1) || isNaN(y2)) continue;
  300. s1.push(y1); s2.push(y2);
  301. }
  302. return { s1, s2 };
  303. }
  304. function plotGraph() {
  305. const { s1, s2 } = parseData(document.getElementById('dataInput').value);
  306. if (s1.length === 0 || s2.length === 0) { alert('No valid data'); return; }
  307. const canvas = document.getElementById('graphCanvas');
  308. const ctx = canvas.getContext('2d');
  309. ctx.clearRect(0, 0, canvas.width, canvas.height);
  310. const allY = [...s1, ...s2];
  311. let minY = Math.min(...allY), maxY = Math.max(...allY);
  312. const margin = (maxY - minY) * 0.05 || 0.1;
  313. minY -= margin; maxY += margin;
  314. const n = s1.length, w = canvas.width, h = canvas.height;
  315. function mapY(y) { return h - ((y - minY) / (maxY - minY)) * h; }
  316. ctx.strokeStyle = '#1f77b4'; ctx.beginPath();
  317. for (let i = 0; i < n; i++) {
  318. const x = (i / (n - 1)) * w, y = mapY(s1[i]);
  319. if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
  320. }
  321. ctx.stroke();
  322. ctx.strokeStyle = '#ff7f0e'; ctx.beginPath();
  323. for (let i = 0; i < n; i++) {
  324. const x = (i / (n - 1)) * w, y = mapY(s2[i]);
  325. if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
  326. }
  327. ctx.stroke();
  328. }
  329. </script>
  330. </body>
  331. </html>
  332. */
  333. #endif /* ALGO_Kalman_ATY_Test_ATY */
  334. #endif /* __ALGO_Kalman_ATY_C */
  335. /******************************** End Of File *********************************/