-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfilter.js
73 lines (70 loc) · 1.77 KB
/
filter.js
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
// a lowpass filter
class LowPass {
sinc(x)
{
if (x==0) return 1.0;
return Math.sin(Math.PI*x) / (Math.PI*x);
}
// construct with the cutoff frequency, and 'b' parameter,
// a larger 'b', means more latency, and a better filter.
constructor(fc, b)
{
var N = Math.ceil(4/b);
if (N%2==0) { ++N; }
var sumh = 0;
this.h = [];
for (let n = 0 ; n < N ; ++n) {
var h = this.sinc(2*fc*(n-(N-1)/2));
var w = 0.42 - 0.5*Math.cos(2*Math.PI*n/(N-1)) + 0.08*Math.cos(4*Math.PI*n/(N-1));
this.h.push(h*w);
sumh += h*w;
}
for (let n = 0 ; n < N ; ++n)
this.h[n] /= sumh;
}
convolve(a, b)
{
var res = [];
for (let j=Math.floor(b.length/2) ; j>0 ; --j)
{
var sum = 0;
for (let jj=j, i=0 ; i<a.length && jj<b.length ; ++i, ++jj)
sum += a[i] * b[jj];
res.push(sum);
}
for (let i=0 ; i < a.length-Math.floor(b.length/2) ; ++i)
{
var sum = 0;
for (let ii=i, j=0 ; j<b.length && ii<a.length ; ++j, ++ii)
sum += a[ii] * b[j];
res.push(sum);
}
return res;
}
calc(vec)
{
return this.convolve(vec, this.h);
}
};
// simple n-day smoothing.
class Smoothing {
constructor(ndays)
{
this.ndays = ndays;
}
calc(vec)
{
/*
r[i] = sum(v[i-j], j=0..N-1)/N
*/
var res = [];
for (var i=this.ndays-1 ; i<vec.length ; i++)
{
var sum = 0;
for (var j=0 ; j<this.ndays ; j++)
sum += vec[i-j];
res.push(sum/this.ndays);
}
return res;
}
};