altos/test: Adjust CRC error rate after FEC fix
[fw/altos] / src / util / make-altitude-pa
1 #!/usr/bin/nickle -f
2 /*
3  * Pressure Sensor Model, version 1.1
4  *
5  * written by Holly Grimes
6  *
7  * Uses the International Standard Atmosphere as described in
8  *   "A Quick Derivation relating altitude to air pressure" (version 1.03)
9  *    from the Portland State Aerospace Society, except that the atmosphere
10  *    is divided into layers with each layer having a different lapse rate.
11  *
12  * Lapse rate data for each layer was obtained from Wikipedia on Sept. 1, 2007
13  *    at site <http://en.wikipedia.org/wiki/International_Standard_Atmosphere
14  *
15  * Height measurements use the local tangent plane.  The postive z-direction is up.
16  *
17  * All measurements are given in SI units (Kelvin, Pascal, meter, meters/second^2).
18  *   The lapse rate is given in Kelvin/meter, the gas constant for air is given
19  *   in Joules/(kilogram-Kelvin).
20  */
21
22 const real GRAVITATIONAL_ACCELERATION = -9.80665;
23 const real AIR_GAS_CONSTANT = 287.053;
24 const int NUMBER_OF_LAYERS = 7;
25 const real MAXIMUM_ALTITUDE = 84852;
26 const real MINIMUM_PRESSURE = 0.3734;
27 const real LAYER0_BASE_TEMPERATURE = 288.15;
28 const real LAYER0_BASE_PRESSURE = 101325;
29
30 /* lapse rate and base altitude for each layer in the atmosphere */
31 const real[NUMBER_OF_LAYERS] lapse_rate = {
32         -0.0065, 0.0, 0.001, 0.0028, 0.0, -0.0028, -0.002,
33 };
34 const int[NUMBER_OF_LAYERS] base_altitude = {
35         0, 11000, 20000, 32000, 47000, 51000, 71000,
36 };
37
38
39 /* outputs atmospheric pressure associated with the given altitude. altitudes
40    are measured with respect to the mean sea level */
41 real altitude_to_pressure(real altitude) {
42
43    real base_temperature = LAYER0_BASE_TEMPERATURE;
44    real base_pressure = LAYER0_BASE_PRESSURE;
45
46    real pressure;
47    real base; /* base for function to determine pressure */
48    real exponent; /* exponent for function to determine pressure */
49    int layer_number; /* identifies layer in the atmosphere */
50    int delta_z; /* difference between two altitudes */
51
52    if (altitude > MAXIMUM_ALTITUDE) /* FIX ME: use sensor data to improve model */
53       return 0;
54
55    /* calculate the base temperature and pressure for the atmospheric layer
56       associated with the inputted altitude */
57    for(layer_number = 0; layer_number < NUMBER_OF_LAYERS - 2 && altitude > base_altitude[layer_number + 1]; layer_number++) {
58       delta_z = base_altitude[layer_number + 1] - base_altitude[layer_number];
59       if (lapse_rate[layer_number] == 0.0) {
60          exponent = GRAVITATIONAL_ACCELERATION * delta_z
61               / AIR_GAS_CONSTANT / base_temperature;
62          base_pressure *= exp(exponent);
63       }
64       else {
65          base = (lapse_rate[layer_number] * delta_z / base_temperature) + 1.0;
66          exponent = GRAVITATIONAL_ACCELERATION /
67               (AIR_GAS_CONSTANT * lapse_rate[layer_number]);
68          base_pressure *= pow(base, exponent);
69       }
70       base_temperature += delta_z * lapse_rate[layer_number];
71    }
72
73    /* calculate the pressure at the inputted altitude */
74    delta_z = altitude - base_altitude[layer_number];
75    if (lapse_rate[layer_number] == 0.0) {
76       exponent = GRAVITATIONAL_ACCELERATION * delta_z
77            / AIR_GAS_CONSTANT / base_temperature;
78       pressure = base_pressure * exp(exponent);
79    }
80    else {
81       base = (lapse_rate[layer_number] * delta_z / base_temperature) + 1.0;
82       exponent = GRAVITATIONAL_ACCELERATION /
83            (AIR_GAS_CONSTANT * lapse_rate[layer_number]);
84       pressure = base_pressure * pow(base, exponent);
85    }
86
87    return pressure;
88 }
89
90
91 /* outputs the altitude associated with the given pressure. the altitude
92    returned is measured with respect to the mean sea level */
93 real pressure_to_altitude(real pressure) {
94
95    real next_base_temperature = LAYER0_BASE_TEMPERATURE;
96    real next_base_pressure = LAYER0_BASE_PRESSURE;
97
98    real altitude;
99    real base_pressure;
100    real base_temperature;
101    real base; /* base for function to determine base pressure of next layer */
102    real exponent; /* exponent for function to determine base pressure
103                              of next layer */
104    real coefficient;
105    int layer_number; /* identifies layer in the atmosphere */
106    int delta_z; /* difference between two altitudes */
107
108    if (pressure < 0)  /* illegal pressure */
109       return -1;
110    if (pressure < MINIMUM_PRESSURE) /* FIX ME: use sensor data to improve model */
111       return MAXIMUM_ALTITUDE;
112
113    /* calculate the base temperature and pressure for the atmospheric layer
114       associated with the inputted pressure. */
115    layer_number = -1;
116    while (layer_number < NUMBER_OF_LAYERS - 2) {
117       layer_number++;
118       base_pressure = next_base_pressure;
119       base_temperature = next_base_temperature;
120       delta_z = base_altitude[layer_number + 1] - base_altitude[layer_number];
121       if (lapse_rate[layer_number] == 0.0) {
122          exponent = GRAVITATIONAL_ACCELERATION * delta_z
123               / AIR_GAS_CONSTANT / base_temperature;
124          next_base_pressure *= exp(exponent);
125       }
126       else {
127          base = (lapse_rate[layer_number] * delta_z / base_temperature) + 1.0;
128          exponent = GRAVITATIONAL_ACCELERATION /
129               (AIR_GAS_CONSTANT * lapse_rate[layer_number]);
130          next_base_pressure *= pow(base, exponent);
131       }
132       next_base_temperature += delta_z * lapse_rate[layer_number];
133       if (pressure >= next_base_pressure)
134               break;
135    }
136
137    /* calculate the altitude associated with the inputted pressure */
138    if (lapse_rate[layer_number] == 0.0) {
139       coefficient = (AIR_GAS_CONSTANT / GRAVITATIONAL_ACCELERATION)
140                                                     * base_temperature;
141       altitude = base_altitude[layer_number]
142                     + coefficient * log(pressure / base_pressure);
143    }
144    else {
145       base = pressure / base_pressure;
146       exponent = AIR_GAS_CONSTANT * lapse_rate[layer_number]
147                                        / GRAVITATIONAL_ACCELERATION;
148       coefficient = base_temperature / lapse_rate[layer_number];
149       altitude = base_altitude[layer_number]
150                       + coefficient * (pow(base, exponent) - 1);
151    }
152    return altitude;
153 }
154
155 /*
156  * Values for our MS5607
157  *
158  * From the data sheet:
159  *
160  * Pressure range: 10-1200 mbar (1000 - 120000 Pa)
161  *
162  * Pressure data is reported in units of Pa
163  */
164
165 typedef struct {
166         real m, b;
167 } line_t;
168
169 /*
170  * Linear least-squares fit values in the specified array
171  */
172 line_t best_fit(real[] values, int first, int last) {
173        real sum_x = 0, sum_x2 = 0, sum_y = 0, sum_xy = 0;
174        int n = last - first + 1;
175        real m, b;
176
177        for (int i = first; i <= last; i++) {
178                sum_x += i;
179                sum_x2 += i**2;
180                sum_y += values[i];
181                sum_xy += values[i] * i;
182        }
183        m = (n*sum_xy - sum_y*sum_x) / (n*sum_x2 - sum_x**2);
184        b = sum_y/n - m*(sum_x/n);
185        return (line_t) { m = m, b = b };
186 }
187
188 void print_table (int pa_sample_shift, int pa_part_shift)
189 {
190         real    min_Pa = 0;
191         real    max_Pa = 120000;
192
193         int pa_part_mask = (1 << pa_part_shift) - 1;
194
195         int num_part = ceil(max_Pa / (2 ** (pa_part_shift + pa_sample_shift)));
196
197         int num_samples = num_part << pa_part_shift;
198
199         real sample_to_Pa(int sample) = sample << pa_sample_shift;
200
201         real sample_to_altitude(int sample) = pressure_to_altitude(sample_to_Pa(sample));
202
203         int part_to_sample(int part) = part << pa_part_shift;
204
205         int sample_to_part(int sample) = sample >> pa_part_shift;
206
207         bool is_part(int sample) = (sample & pa_part_mask) == 0;
208
209         real[num_samples] alt = { [n] = sample_to_altitude(n) };
210
211         int seg_len = 1 << pa_part_shift;
212
213         line_t [num_part] fit = {
214                 [n] = best_fit(alt, n * seg_len, n * seg_len + seg_len - 1)
215         };
216
217         real[num_samples/seg_len + 1]   alt_part;
218         real[dim(alt_part)]             alt_error = {0...};
219
220         alt_part[0] = fit[0].b;
221         alt_part[dim(fit)] = fit[dim(fit)-1].m * dim(fit) * seg_len + fit[dim(fit)-1].b;
222
223         for (int i = 0; i < dim(fit) - 1; i++) {
224                 real    here, there;
225                 here = fit[i].m * (i+1) * seg_len + fit[i].b;
226                 there = fit[i+1].m * (i+1) * seg_len + fit[i+1].b;
227 #               printf ("at %d mis-fit %8.2f\n", i, there - here);
228                 alt_part[i+1] = (here + there) / 2;
229         }
230
231         real round(real x) = floor(x + 0.5);
232
233         real sample_to_fit_altitude(int sample) {
234                 int     sub = sample // seg_len;
235                         int     off = sample % seg_len;
236                 line_t  l = fit[sub];
237                 real r_v;
238                 real i_v;
239
240                 r_v = sample * l.m + l.b;
241                 i_v = (round(alt_part[sub]*10) * (seg_len - off) + round(alt_part[sub+1]*10) * off) / seg_len;
242                 return i_v/10;
243         }
244
245         real max_error = 0;
246         int max_error_sample = 0;
247         real total_error = 0;
248
249         for (int sample = 0; sample < num_samples; sample++) {
250                 real    Pa = sample_to_Pa(sample);
251                 real    meters = alt[sample];
252
253                 real    meters_approx = sample_to_fit_altitude(sample);
254                 real    error = abs(meters - meters_approx);
255
256                 int     part = sample_to_part(sample);
257
258                 if (error > alt_error[part])
259                         alt_error[part] = error;
260
261                 total_error += error;
262                 if (error > max_error) {
263                         max_error = error;
264                         max_error_sample = sample;
265                 }
266                 if (false) {
267                         printf ("       %8.1f %8.2f %8.2f %8.2f %s\n",
268                                 Pa,
269                                 meters,
270                                 meters_approx,
271                                 meters - meters_approx,
272                                 is_part(sample) ? "*" : "");
273                 }
274         }
275
276         printf ("/*max error %f at %7.3f kPa. Average error %f*/\n",
277                 max_error, sample_to_Pa(max_error_sample) / 1000, total_error / num_samples);
278
279         printf ("#define NALT %d\n", dim(alt_part));
280         printf ("#define ALT_SHIFT %d\n", pa_part_shift + pa_sample_shift);
281         printf ("#ifndef AO_ALT_VALUE\n#define AO_ALT_VALUE(x) (alt_t) (x)\n#endif\n");
282
283         for (int part = 0; part < dim(alt_part); part++) {
284                 real kPa = sample_to_Pa(part_to_sample(part)) / 1000;
285                 printf ("AO_ALT_VALUE(%10.1f), /* %6.2f kPa error %6.2fm */\n",
286                         round (alt_part[part]*10) / 10, kPa,
287                         alt_error[part]);
288         }
289 }
290
291 autoload ParseArgs;
292
293 void main()
294 {
295         /* Target is an array of < 1000 entries */
296         int pa_sample_shift = 2;
297         int pa_part_shift = 6;
298
299         ParseArgs::argdesc argd = {
300                 .args = {
301                         { .var = { .arg_int = &pa_sample_shift },
302                           .abbr = 's',
303                           .name = "sample",
304                           .expr_name = "sample_shift",
305                           .desc = "sample shift value" },
306                         { .var = { .arg_int = &pa_part_shift },
307                           .abbr = 'p',
308                           .name = "part",
309                           .expr_name = "part_shift",
310                           .desc = "part shift value" },
311                 }
312         };
313
314         ParseArgs::parseargs(&argd, &argv);
315
316         print_table(pa_sample_shift, pa_part_shift);
317 }
318
319 main();