SimDriver  0.1
Filter.h
1 // Copyright (c) 2020 Institute for Automotive Engineering (ika), RWTH Aachen University. All rights reserved.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to deal
5 // in the Software without restriction, including without limitation the rights
6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 // copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in all
11 // copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 // SOFTWARE.
20 //
21 // Created by Jens Klimke on 2020-04-04
22 // Contributors:
23 //
24 
25 
26 #ifndef SIMDRIVER_FILTER_H
27 #define SIMDRIVER_FILTER_H
28 
29 #include <deque>
30 #include <vector>
31 
32 namespace agent_model {
33 
34 
38  class Filter {
39 
40  protected:
41 
42  unsigned int n;
43  unsigned int i;
44 
45  std::vector<double> _elements;
46 
47  public:
48 
54  void init(unsigned int length) {
55 
56  // set length and index
57  n = length;
58  i = 0;
59 
60  // create vector
61  if (_elements.size() != n) {
62  _elements.clear();
63  _elements.reserve(n);
64  }
65 
66  }
67 
68 
73  double value() {
74 
75  // special case
76  if(_elements.empty())
77  return 0.0;
78 
79  // sum up
80  auto sum = 0.0;
81  for (auto &e : _elements)
82  sum += e;
83 
84  // return average value
85  return sum / (double) _elements.size();
86 
87  }
88 
89 
95  double value(double v) {
96 
97  // add element
98  if(_elements.size() < n)
99  _elements.emplace_back(v);
100  else
101  _elements.at(i) = v;
102 
103  // increment i
104  i = (i + 1) % n;
105 
106  // return mean value
107  return value();
108 
109  }
110 
111  };
112 
113 
114 }
115 
116 
117 #endif // SIMDRIVER_FILTER_H
double value(double v)
Definition: Filter.h:95
void init(unsigned int length)
Definition: Filter.h:54
Definition: DistanceTimeInterval.h:33
A class to implement a mean filter.
Definition: Filter.h:38
double value()
Definition: Filter.h:73
unsigned int i
Current element&#39;s index (circular buffer)
Definition: Filter.h:43
std::vector< double > _elements
Element container.
Definition: Filter.h:45
unsigned int n
Number of elements.
Definition: Filter.h:42