altos: Add computation of MicroPeak Kalman correction coefficients
[fw/altos] / src / kalman / kalman_micro.5c
1 #!/usr/bin/env nickle
2
3 /*
4  * Copyright © 2013 Keith Packard <keithp@keithp.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; version 2 of the License.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
18  */
19
20 autoimport ParseArgs;
21
22 load "load_csv.5c"
23 import load_csv;
24
25 load "matrix.5c"
26 import matrix;
27
28 load "kalman_filter.5c"
29 import kalman;
30
31 load "../util/atmosphere.5c"
32
33 real    height_scale = 1.0;
34 real    accel_scale = 1.0;
35 real    speed_scale = 1.0;
36
37 /*
38  * State:
39  *
40  * x[0] = pressure
41  * x[1] = delta pressure
42  * x[2] = delta delta pressure
43  */
44
45 /*
46  * Measurement
47  *
48  * z[0] = pressure
49  */
50
51 real default_σ_m = 5;
52 real default_σ_h = 2.4;        /* pascals */
53
54 real[3,3] model_error(t, Φ) = multiply_mat_val ((real[3,3]) {
55                 { t**5 / 20, t**4 / 8, t**3 / 6 },
56                 { t**4 /  8, t**3 / 3, t**2 / 2 },
57                 { t**3 /  6, t**2 / 2, t }
58         }, Φ);
59
60 parameters_t param_baro(real t, real σ_m, real σ_h) {
61         if (σ_m == 0) {
62                 printf ("Using default σ_m\n");
63                 σ_m = default_σ_m;
64         }
65         if (σ_h == 0) {
66                 printf ("Using default σ_h\n");
67                 σ_h = default_σ_h;
68         }
69
70         σ_m = imprecise(σ_m) * accel_scale;
71         σ_h = imprecise(σ_h) * height_scale;
72
73         t = imprecise(t);
74         return (parameters_t) {
75 /*
76  * Equation computing state k from state k-1
77  *
78  * height = height- + velocity- * t + acceleration- * t² / 2
79  * velocity = velocity- + acceleration- * t
80  * acceleration = acceleration-
81  */
82                 .a = (real[3,3]) {
83                         { 1, t * height_scale / speed_scale , t**2/2 * height_scale / accel_scale },
84                         { 0, 1, t * speed_scale / accel_scale },
85                         { 0, 0, 1 }
86                 },
87 /*
88  * Model error covariance. The only inaccuracy in the
89  * model is the assumption that acceleration is constant
90  */
91                 .q = model_error (t, σ_m**2),
92
93 /*
94  * Measurement error covariance
95  * Our sensors are independent, so
96  * this matrix is zero off-diagonal
97  */
98                 .r = (real[1,1]) {
99                         { σ_h ** 2 },
100                 },
101 /*
102  * Extract measurements from state,
103  * this just pulls out the height
104  * values.
105  */
106                 .h = (real[1,3]) {
107                         { 1, 0, 0 },
108                 },
109          };
110 }
111
112 bool    just_kalman = true;
113 real    accel_input_scale = 1;
114
115 real    error_avg;
116
117 void update_error_avg(real e) {
118         if (e < 0)
119                 e = -e;
120
121 #       if (e > 1000)
122 #               e = 1000;
123
124         error_avg -= error_avg / 8;
125         error_avg += (e * e) / 8;
126 }
127
128 void run_flight(string name, file f, bool summary, real σ_m, real σ_h) {
129         state_t current_both = {
130                 .x = (real[3]) { 0, 0, 0 },
131                 .p = (real[3,3]) { { 0 ... } ... },
132         };
133         state_t current_accel = current_both;
134         state_t current_baro = current_both;
135         real    t;
136         real    kalman_apogee_time = -1;
137         real    kalman_apogee = 0;
138         real    raw_apogee_time_first;
139         real    raw_apogee_time_last;
140         real    raw_apogee = 0;
141         real    speed = 0;
142         real    prev_acceleration = 0;
143         real    height, max_height = 0;
144         state_t apogee_state;
145         parameters_fast_t       fast_baro;
146         real                    fast_delta_t = 0;
147         bool                    fast = true;
148         int                     speed_lock = 0;
149
150         error_avg = 0;
151         for (;;) {
152                 record_t        record = parse_record(f, 1.0);
153                 if (record.done)
154                         break;
155                 if (is_uninit(&t))
156                         t = record.time;
157                 real delta_t = record.time - t;
158                 if (delta_t < 0.096)
159                         continue;
160 #               delta_t = 0.096;        /* pretend that we're getting micropeak-rate data */
161 #               record.time = record.time + delta_t;
162                 t = record.time;
163                 if (record.height > raw_apogee) {
164                         raw_apogee_time_first = record.time;
165                         raw_apogee = record.height;
166                 }
167                 if (record.height == raw_apogee)
168                         raw_apogee_time_last = record.time;
169
170                 real    pressure = record.pressure;
171
172                 if (current_baro.x[0] == 0)
173                         current_baro.x[0] = pressure;
174
175                 vec_t z_baro = (real[1]) { record.pressure * height_scale };
176
177                 real    error_h;
178
179                 if (fast) {
180                         if (delta_t != fast_delta_t) {
181                                 fast_baro = convert_to_fast(param_baro(delta_t, σ_m, σ_h));
182                                 fast_delta_t = delta_t;
183                         }
184
185                         current_baro.x = predict_fast(current_baro.x, fast_baro);
186                         error_h = current_baro.x[0] - pressure;
187                         current_baro.x = correct_fast(current_baro.x, z_baro, fast_baro);
188                 } else {
189                         parameters_t p_baro = param_baro(delta_t, σ_m, σ_h);
190
191                         state_t pred_baro = predict(current_baro, p_baro);
192                         error_h = current_baro.x[0] - pressure;
193                         state_t next_baro = correct(pred_baro, z_baro, p_baro);
194                         current_baro = next_baro;
195                 }
196
197                 update_error_avg(error_h);
198
199                 /* Don't check for maximum altitude if we're accelerating upwards */
200                 if (current_baro.x[2] / accel_scale < -2 * σ_m)
201                         speed_lock = 10;
202                 else if (speed_lock > 0)
203                         speed_lock--;
204
205                 height = pressure_to_altitude(current_baro.x[0] / height_scale);
206                 if (speed_lock == 0 && height > max_height)
207                         max_height = height;
208
209                 printf ("%16.8f %16.8f %16.8f %16.8f %16.8f %16.8f %16.8f %16.8f %16.8f %16.8f %d %d\n",
210                         record.time,
211                         record.pressure,
212                         pressure_to_altitude(record.pressure),
213                         current_baro.x[0] / height_scale,
214                         current_baro.x[1] / speed_scale,
215                         current_baro.x[2] / accel_scale,
216                         height,
217                         max_height,
218                         error_h,
219                         error_avg,
220                         error_avg > 50000 ? 0 : 95000,
221                         speed_lock > 0 ? 0 : 4500);
222
223                 if (kalman_apogee_time < 0) {
224                         if (current_baro.x[1] > 1) {
225                                 kalman_apogee = current_both.x[0];
226                                 kalman_apogee_time = record.time;
227                         }
228                 }
229         }
230         real raw_apogee_time = (raw_apogee_time_last + raw_apogee_time_first) / 2;
231         if (summary && !just_kalman) {
232                 printf("%s: kalman (%8.2f m %6.2f s) raw (%8.2f m %6.2f s) error %6.2f s\n",
233                        name,
234                        kalman_apogee, kalman_apogee_time,
235                        raw_apogee, raw_apogee_time,
236                        kalman_apogee_time - raw_apogee_time);
237         }
238 }
239
240 void main() {
241         bool    summary = false;
242         int     user_argind = 1;
243         real    time_step = 0.01;
244         string  compute = "none";
245         string  prefix = "AO_K";
246         real    σ_m = default_σ_m;
247         real    σ_h = default_σ_h;
248
249         ParseArgs::argdesc argd = {
250                 .args = {
251                         { .var = { .arg_flag = &summary },
252                           .abbr = 's',
253                           .name = "summary",
254                           .desc = "Print a summary of the flight" },
255                         { .var = { .arg_real = &time_step, },
256                           .abbr = 't',
257                           .name = "time",
258                           .expr_name = "<time-step>",
259                           .desc = "Set time step for convergence" },
260                         { .var = { .arg_string = &prefix },
261                           .abbr = 'p',
262                           .name = "prefix",
263                           .expr_name = "<prefix>",
264                           .desc = "Prefix for compute output" },
265                         { .var = { .arg_string = &compute },
266                           .abbr = 'c',
267                           .name = "compute",
268                           .expr_name = "{baro,none}",
269                           .desc = "Compute Kalman factor through convergence" },
270                         { .var = { .arg_real = &σ_m },
271                           .abbr = 'M',
272                           .name = "model",
273                           .expr_name = "<model-accel-error>",
274                           .desc = "Model co-variance for acceleration" },
275                         { .var = { .arg_real = &σ_h },
276                           .abbr = 'H',
277                           .name = "height",
278                           .expr_name = "<measure-height-error>",
279                           .desc = "Measure co-variance for height" },
280                 },
281
282                 .unknown = &user_argind,
283         };
284
285         ParseArgs::parseargs(&argd, &argv);
286
287         if (compute != "none") {
288                 parameters_t    param;
289
290                 printf ("/* Kalman matrix for micro %s\n", compute);
291                 printf (" *     step = %f\n", time_step);
292                 printf (" *     σ_m = %f\n", σ_m);
293                 switch (compute) {
294                 case "baro":
295                         printf (" *     σ_h = %f\n", σ_h);
296                         param = param_baro(time_step, σ_m, σ_h);
297                         break;
298                 }
299                 printf (" */\n\n");
300                 mat_t k = converge(param);
301                 int[] d = dims(k);
302                 int time_inc = floor(1/time_step + 0.5);
303                 for (int i = 0; i < d[0]; i++)
304                         for (int j = 0; j < d[1]; j++) {
305                                 string name;
306                                 if (d[1] == 1)
307                                         name = sprintf("%s_K%d_%d", prefix, i, time_inc);
308                                 else
309                                         name = sprintf("%s_K%d%d_%d", prefix, i, j, time_inc);
310                                 printf ("#define %s to_fix32(%12.10f)\n", name, k[i,j]);
311                         }
312                 printf ("\n");
313                 exit(0);
314         }
315         string[dim(argv) - user_argind] rest = { [i] = argv[i+user_argind] };
316
317         #       height_scale = accel_scale = speed_scale = 1;
318
319         if (dim(rest) == 0)
320                 run_flight("<stdin>", stdin, summary, σ_m, σ_h);
321         else {
322                 for (int i = 0; i < dim(rest); i++) {
323                         twixt(file f = File::open(rest[i], "r"); File::close(f)) {
324                                 run_flight(rest[i], f, summary, σ_m, σ_h);
325                         }
326                 }
327         }
328 }
329 main();