ros2_control - foxy
Loading...
Searching...
No Matches
rolling_mean_accumulator.hpp
1// Copyright 2020 PAL Robotics S.L.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/*
16 * Author: Víctor López
17 */
18
19#ifndef TRICYCLE_CONTROLLER__ROLLING_MEAN_ACCUMULATOR_HPP_
20#define TRICYCLE_CONTROLLER__ROLLING_MEAN_ACCUMULATOR_HPP_
21
22#include <cassert>
23#include <vector>
24
25namespace tricycle_controller
26{
33template <typename T>
35{
36public:
37 explicit RollingMeanAccumulator(size_t rolling_window_size)
38 : buffer_(rolling_window_size, 0.0), next_insert_(0), sum_(0.0), buffer_filled_(false)
39 {
40 }
41
42 void accumulate(T val)
43 {
44 sum_ -= buffer_[next_insert_];
45 sum_ += val;
46 buffer_[next_insert_] = val;
47 next_insert_++;
48 buffer_filled_ |= next_insert_ >= buffer_.size();
49 next_insert_ = next_insert_ % buffer_.size();
50 }
51
52 T getRollingMean() const
53 {
54 size_t valid_data_count = buffer_filled_ * buffer_.size() + !buffer_filled_ * next_insert_;
55 assert(valid_data_count > 0);
56 return sum_ / valid_data_count;
57 }
58
59private:
60 std::vector<T> buffer_;
61 size_t next_insert_;
62 T sum_;
63 bool buffer_filled_;
64};
65} // namespace tricycle_controller
66#endif // TRICYCLE_CONTROLLER__ROLLING_MEAN_ACCUMULATOR_HPP_
Simplification of boost::accumulators::accumulator_set<double, bacc::stats<bacc::tag::rolling_mean>> ...
Definition rolling_mean_accumulator.hpp:35