1 | #include <iostream> |
---|
2 | #include <math.h> |
---|
3 | #include <Utils/Hanning.hh> |
---|
4 | |
---|
5 | Hanning::Hanning(){ |
---|
6 | allocated=false; |
---|
7 | } |
---|
8 | |
---|
9 | Hanning::~Hanning(){ |
---|
10 | if(allocated) delete [] coeffs; |
---|
11 | } |
---|
12 | |
---|
13 | Hanning::Hanning(int size){ |
---|
14 | /** |
---|
15 | * Constructor that sets the Hanning width and calculates the |
---|
16 | * coefficients. Does this by simply calling the |
---|
17 | * Hanning::define(int) function. |
---|
18 | * \param size The full width of the filter. The parameter \f$a\f$ |
---|
19 | * is defined as (size+1)/2. |
---|
20 | */ |
---|
21 | |
---|
22 | this->allocated=false; |
---|
23 | this->define(size); |
---|
24 | }; |
---|
25 | |
---|
26 | void Hanning::define(int size) |
---|
27 | { |
---|
28 | /** |
---|
29 | * Function that sets the Hanning width and calculates the coefficients. |
---|
30 | * \param size The full width of the filter. The parameter \f$a\f$ is |
---|
31 | * defined as (size+1)/2. |
---|
32 | */ |
---|
33 | if(size%2==0){ |
---|
34 | std::cerr << "Hanning: need an odd number for the size. " |
---|
35 | << "Changing "<< size << " to " << ++size<<".\n"; |
---|
36 | } |
---|
37 | this->hanningSize = size; |
---|
38 | if(this->allocated) delete [] this->coeffs; |
---|
39 | this->coeffs = new float[size]; |
---|
40 | this->allocated = true; |
---|
41 | float a = (size+1.)/2.; |
---|
42 | for(int i=0;i<size;i++){ |
---|
43 | float x = i-(size-1)/2.; |
---|
44 | this->coeffs[i] = 0.5 + 0.5*cos(x * M_PI / a); |
---|
45 | } |
---|
46 | } |
---|
47 | |
---|
48 | |
---|
49 | |
---|
50 | float *Hanning::smooth(float *array, int npts){ |
---|
51 | /** |
---|
52 | * This smooths an array of float by doing a discrete convolution of |
---|
53 | * the input array with the filter coefficients. |
---|
54 | * |
---|
55 | * Currently only works for C arrays of floats, as that is all I |
---|
56 | * need it for. Could be made more general if needs be. |
---|
57 | * |
---|
58 | * \param array The input array. Needs to be defined -- no memory |
---|
59 | * checks are done! |
---|
60 | * \param npts The size of the input array. |
---|
61 | * \return Returns an array of the same size. If filter coefficients |
---|
62 | * have not been allocated, the input array is returned. |
---|
63 | */ |
---|
64 | if(!this->allocated) return array; |
---|
65 | else{ |
---|
66 | float *newarray = new float[npts]; |
---|
67 | float scale = (hanningSize+1.)/2.; |
---|
68 | for(int i=0;i<npts;i++){ |
---|
69 | newarray[i] = 0.; |
---|
70 | for(int j=0;j<hanningSize;j++){ |
---|
71 | int x = j-(hanningSize-1)/2; |
---|
72 | if((i+x>0)&&(i+x<npts)) newarray[i]+=coeffs[j] * array[i+x]; |
---|
73 | } |
---|
74 | newarray[i] /= scale; |
---|
75 | } |
---|
76 | return newarray; |
---|
77 | } |
---|
78 | } |
---|