Add DSP code to filter data, allowing for integration/differentiation
[fw/altos] / ao-tools / lib / cc-integrate.c
1 /*
2  * Copyright © 2009 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #include "cc.h"
19 #include <stdlib.h>
20
21 struct cc_timedata *
22 cc_timedata_convert(struct cc_timedata *d, double (*f)(double v, double a), double a)
23 {
24         struct cc_timedata      *r;
25         int                     n;
26
27         r = calloc (1, sizeof (struct cc_timedata));
28         r->num = d->num;
29         r->size = d->num;
30         r->data = calloc (r->size, sizeof (struct cc_timedataelt));
31         r->time_offset = d->time_offset;
32         for (n = 0; n < d->num; n++) {
33                 r->data[n].time = d->data[n].time;
34                 r->data[n].value = f(d->data[n].value, a);
35         }
36         return r;
37 }
38
39 struct cc_timedata *
40 cc_timedata_integrate(struct cc_timedata *d)
41 {
42         struct cc_timedata      *i;
43         int                     n;
44
45         i = calloc (1, sizeof (struct cc_timedata));
46         i->num = d->num;
47         i->size = d->num;
48         i->data = calloc (i->size, sizeof (struct cc_timedataelt));
49         i->time_offset = d->time_offset;
50         for (n = 0; n < d->num; n++) {
51                 i->data[n].time = d->data[n].time;
52                 if (n == 0) {
53                         i->data[n].value = 0;
54                 } else {
55                         i->data[n].value = i->data[n-1].value +
56                                 (d->data[n].value + d->data[n-1].value) / 2 *
57                                 ((d->data[n].time - d->data[n-1].time) / 100.0);
58                 }
59         }
60         return i;
61 }
62
63 struct cc_perioddata *
64 cc_perioddata_differentiate(struct cc_perioddata *i)
65 {
66         struct cc_perioddata    *d;
67         int                     n;
68
69         d = calloc (1, sizeof (struct cc_perioddata));
70         d->num = i->num;
71         d->start = i->start;
72         d->step = i->step;
73         d->data = calloc (d->num, sizeof(double));
74         for (n = 1; n < d->num; n++)
75                 d->data[n] = (i->data[n] - i->data[n-1]) / i->step;
76         d->data[0] = d->data[1];
77         return d;
78 }