moving_average_filter.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 # Copyright 2011 Shadow Robot Company Ltd.
4 #
5 # This program is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation version 2 of the License.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 # more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with this program. If not, see <http://www.gnu.org/licenses/>.
16 
17 import rospy
18 from std_msgs.msg import Float64
19 
20 
21 class FilterMessages(object):
22  def __init__(self):
23  rospy.init_node('mean_filter', anonymous=True)
24 
25  if rospy.has_param('~nb_occ'):
26  nb_occurence = rospy.get_param('~nb_occ')
27  else:
28  nb_occurence = 5
29  rospy.core.logwarn("N number of occurence provided, using 5 as default")
30 
31  if rospy.has_param('~in_topic'):
32  input_topic_param = rospy.get_param('~in_topic')
33  self.subs = rospy.Subscriber(input_topic_param, Float64, self.callback)
34  self.pub = rospy.Publisher(input_topic_param+"_filtered", Float64)
35  else:
36  rospy.core.logerr("No input topic provided, not starting filtering")
37  return
38 
39  self.queue = []
40  self.queue_len = nb_occurence
41  self.mean = Float64(0.0)
42 
43  rospy.spin()
44 
45  def compute_mean(self):
46  mean = 0.0
47  for val in range(self.queue_len):
48  mean = mean+self.queue[val].data
49 
50  return mean/self.queue_len
51 
52  def callback(self, data):
53  self.queue.append(data)
54 
55  if len(self.queue) >= self.queue_len:
56  self.mean = Float64(self.compute_mean())
57  self.queue.pop(0)
58 
59  self.pub.publish(self.mean)
60 
61 
62 if __name__ == '__main__':


sr_utilities
Author(s): Ugo Cupcic
autogenerated on Mon Feb 28 2022 23:52:19