-
Notifications
You must be signed in to change notification settings - Fork 1
/
avgfilter.rb
81 lines (62 loc) · 1.46 KB
/
avgfilter.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
require 'optparse'
options = {}
$window_size = 10.0
$tolerance = 1.0
optparse = OptionParser.new do |opts|
opts.banner = "Usage: avgfilter.rb [options]"
opts.on( '-w', '--window SIZE', 'window (buffer) size' ) do |v|
$window_size = v.to_i
end
opts.on( '-t', '--tolerance VALUE', 'tolerance between two values' ) do |v|
$tolerance = v.to_f
end
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
optparse.parse!
$total = 0.0
$buf = []
$output = []
def enqueue(value)
abort "buffer overrun on #{value}" if $buf.length >= $window_size
$buf << value
$output << value
$total += value
end
def dequeue
value = $buf.shift
out = $output.shift
$total -= value
outtext = '%.2f'%out
puts outtext
end
$middle_index = $window_size / 2
def flush_buf
# for the last few data after the middle
#if $buf.length > $middle_index + 1
#end
while $buf.length > 0
dequeue
end
end
$<.each {|line|
new_value = line.to_f
if $buf.length > 0
if ($buf[-1]-new_value).abs > $tolerance
flush_buf
elsif $buf.length == $window_size
# update the output for the item in the middle of the buffer
$output[$middle_index] = $total / $window_size
# output the head of the buffer
dequeue
end
end
enqueue new_value
if $buf.length > 1
# for the first few data in the buffer
$output[-1] = $total / $buf.length
end
}
flush_buf