00001 /* 00002 * Copyright 2018 The urg_stamped Authors 00003 * 00004 * Licensed under the Apache License, Version 2.0 (the "License"); 00005 * you may not use this file except in compliance with the License. 00006 * You may obtain a copy of the License at 00007 * 00008 * http://www.apache.org/licenses/LICENSE-2.0 00009 * 00010 * Unless required by applicable law or agreed to in writing, software 00011 * distributed under the License is distributed on an "AS IS" BASIS, 00012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00013 * See the License for the specific language governing permissions and 00014 * limitations under the License. 00015 */ 00016 00017 #ifndef TIMESTAMP_MOVING_AVERAGE_H 00018 #define TIMESTAMP_MOVING_AVERAGE_H 00019 00020 #include <ros/ros.h> 00021 00022 #include <cmath> 00023 #include <vector> 00024 00025 class TimestampMovingAverage 00026 { 00027 protected: 00028 size_t window_size_; 00029 ros::Duration interval_; 00030 std::vector<ros::Time> buffer_; 00031 size_t pos_; 00032 00033 public: 00034 TimestampMovingAverage( 00035 const size_t window_size, 00036 const ros::Duration &interval) 00037 : window_size_(window_size) 00038 , interval_(interval) 00039 , pos_(0) 00040 { 00041 buffer_.resize(window_size); 00042 } 00043 void setInterval(const ros::Duration &interval) 00044 { 00045 interval_ = interval; 00046 } 00047 ros::Time update(const ros::Time &stamp) 00048 { 00049 buffer_[pos_ % window_size_] = stamp; 00050 pos_++; 00051 if (pos_ < window_size_) 00052 return stamp; 00053 00054 ros::Duration sum(0); 00055 for (const ros::Time &b : buffer_) 00056 { 00057 sum += ros::Duration(remainder((b - stamp).toSec(), interval_.toSec())); 00058 } 00059 return stamp + sum * (1.0 / window_size_); 00060 } 00061 void reset() 00062 { 00063 pos_ = 0; 00064 } 00065 }; 00066 00067 #endif // TIMESTAMP_MOVING_AVERAGE_H