blib/lib/TimeSeries/AdaptiveFilter.pm

filter: Statementstmt 98.8% 82 / 83 Branchbran 76.9% 20 / 26 Conditioncond 75.0% 24 / 32 MC/DCmcdc 47.0% 8 / 17 Subroutinesub 100% 6 / 6 Podpod 100% 1 / 1 totaltotal 85.4% 141 / 165 CC 28 SCAR 27.6
CC
28
Cov
89%
__ANON__
21.6
filter
8.1
BEGIN
1.0
CRAP 15.8
↑ Summary
1 package TimeSeries::AdaptiveFilter;
2 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 =head1 NAME
6  
7 TimeSeries::AdaptiveFilter - Adaptive filter for data stream with possible outliers
8  
9 =cut
10  
11 2 our $VERSION = '0.05';
12  
13 =head1 STATUS
14  
15 =begin HTML
16  
17 <p>
18 <a href="https://travis-ci.org/binary-com/perl-TimeSeries-AdaptiveFilter"><img src="https://travis-ci.org/binary-com/perl-TimeSeries-AdaptiveFilter.svg" /></a>
19 </p>
20  
21 =end HTML
22  
23 =cut
24  
25 2 ▶use List::Util qw(sum max);
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 2 ▶use Exporter qw/import/;
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 2 our @EXPORT_OK = qw/filter/;
30  
31 =head1 SYNOPSYS
32  
33 use TimeSeries::AdaptiveFilter qw/filter/;
34  
35 # creation with defaults
36 my $filter = filter();
37  
38 # create filter with tuned parameters
39 my $filter = filter({
40 floor => 6
41 cap => 0.2,
42 lookback_capacity => 20,
43 lookback_period => 4,
44 decay_speeds => [0.03, 0.01, 0.003],
45 build_up_count => 5,
46 reject_criterium => 4,
47 });
48  
49 # usage
50 my $now = time;
51 $filter->($now, 100.002); # returns true, i.e. all data is valid on learning period
52 $filter->($now + 1, 100.001); # returns true
53 ... # it learns form sample of 60 seconds
54 $filter->($now + 60, 100.005); # returns true
55 $filter->($now + 61, 99.9995); # returns true, as value does not differs much
56 $filter->($now + 62, 10_0000); # returns false, outlier data
57 $filter->($now + 63, 10.0001); # returns false, outlier data
58 $filter->($now + 64, 100.011); # returns true, even if the sample is oulier, because
59 # the filter rejected too much values, and has to
60 # re-adapt to time seria again
61  
62 =head1 DESCRIPTION
63  
64 For the details of underlying mathematical model of the filter, configurable parameters
65 and their usage, please, look at the shipped C<doc> folder.
66  
67 =cut
68  
69 2 my $sqrt2pi = 1 / sqrt(2 * atan2(1, 1));
70  
71 =head1 FUNCTIONS
72  
73 =head2 filter
74  
75 =cut
76  
77 4 ▶sub filter {
Subroutine filter: called CC=8 SCAR=20.9
Pod documented
78 4 my $params = shift;
79  
80 ##############################
81 ## filter tuning parameters ##
82 ##############################
83  
84 # minimum amount of values in lookback to take an decision.
85 # Otherwise, input values will be accepted
86 4 ▶ my $floor = $params->{floor} // 6;
Condition100%2/2
$params->{"floor"} // 6
l!l
13
MC/DC100%1/1
$params->{"floor"} // 6
$params->{"floor"}
Truth table100%2/2
A
A= $params->{"floor"}
Aresult
11
00
87 # maximum share of rejected input values. Upon hit, input values will be accepted
88 4 ▶ my $cap = $params->{cap} // 0.2;
Condition50%1/2
$params->{"cap"} // "0.2"
l!l
04
MC/DC0%0/1
$params->{"cap"} // "0.2"
$params->{"cap"}
Truth table50%1/2
A
A= $params->{"cap"}
Aresult
11
00
89 # maximum amount ot input values in lookback
90 4 ▶ my $lookback_capacity = $params->{lookback_capacity} // 20;
Condition50%1/2
$params->{"lookback_capacity"} // 20
l!l
04
MC/DC0%0/1
$params->{"lookback_capacity"} // 20
$params->{"lookback_capacity"}
Truth table50%1/2
A
A= $params->{"lookback_capacity"}
Aresult
11
00
91 # the retention period for lookback, i.e. max age for input values
92 4 ▶ my $lookback_period = $params->{lookback_period} // 4;
Condition50%1/2
$params->{"lookback_period"} // 4
l!l
04
MC/DC0%0/1
$params->{"lookback_period"} // 4
$params->{"lookback_period"}
Truth table50%1/2
A
A= $params->{"lookback_period"}
Aresult
11
00
93 4 ▶ my $decay_speeds = $params->{decay_speeds} // [0.03, 0.01, 0.003];
Condition50%1/2
$params->{"decay_speeds"} // ["0.03", "0.01", "0.003"]
l!l
04
MC/DC0%0/1
$params->{"decay_speeds"} // ["0.03", "0.01", "0.003"]
$params->{"decay_speeds"}
Truth table50%1/2
A
A= $params->{"decay_speeds"}
Aresult
11
00
94 4 ▶ my $build_up_count = $params->{build_up_count} // 5;
Condition100%2/2
$params->{"build_up_count"} // 5
l!l
13
MC/DC100%1/1
$params->{"build_up_count"} // 5
$params->{"build_up_count"}
Truth table100%2/2
A
A= $params->{"build_up_count"}
Aresult
11
00
95 4 ▶ my $reject_criterium = $params->{reject_criterium} // 4;
Condition50%1/2
$params->{"reject_criterium"} // 4
l!l
04
MC/DC0%0/1
$params->{"reject_criterium"} // 4
$params->{"reject_criterium"}
Truth table50%1/2
A
A= $params->{"reject_criterium"}
Aresult
11
00
96  
97 ########################
98 ## enclosed variables ##
99 ########################
100  
101 4 my @lookback;
102 4 my $lookback_rejected = 0;
103 4 my @minute;
104 my $trust_w;
105 4 my $ad;
106 4 my @ads; # used on build stage only
107 4 my $mad;
108 4 my @mads;
109 4 my $wsum = 0;
110 4 my $csum = 0;
111 4 my $_accepted;
112  
113 # flag initicates, that we still need to accumulate enough time series
114 # before doing actual filtering.
115 4 my $build = 1;
116  
117 # resulting adaptive filter function
118 213 ▶ my $fn = sub {
Subroutine __ANON__: called CC=21 SCAR=30.7
119 213 my ($epoch, $spot) = @_;
120  
121 # operating on nature log
122 213 $spot = log $spot;
123  
124 # prevent loopback window overgrow
125 213 ▶ while (@lookback > $lookback_capacity or @lookback > $floor and $lookback[0][0] < $epoch - $lookback_period) {
Branch: 1 branch
BranchTrueFalseTotal
if (@lookback > $lookback_capacity or @lookback > $floor and $lookback[0][0] < $epoch - $lookback_period) 178 213 391
Condition100%6/6
@lookback > $lookback_capacity or @lookback > $floor and $lookback[0][0] < $epoch - $lookback_period
l!l&&r!l&&!r
8098213
@lookback > $floor and $lookback[0][0] < $epoch - $lookback_period
!ll&&!rl&&r
1199498
MC/DC100%3/3
@lookback > $lookback_capacity or @lookback > $floor and $lookback[0][0] < $epoch - $lookback_period
@lookback > $lookback_capacity @lookback > $floor $lookback[0][0] < $epoch - $lookback_period
Truth table100%4/4
A or B and C
A= @lookback > $lookback_capacityB= @lookback > $floorC= $lookback[0][0] < $epoch - $lookback_period
ABCresult
1XX1
0111
00X0
0100
126 178 my $leaving = shift @lookback;
127 178 ▶ --$lookback_rejected unless $leaving->[3];
Branch: 1 branch
BranchTrueFalseTotal
unless $leaving->[3] 0 178 178
128 }
129 213 my $accepted;
130  
131 213 ▶ if ($build) {
Branch: 1 branch
BranchTrueFalseTotal
if ($build) { } 173 40 213
132 # always accept the incoming value
133 173 ($trust_w, $accepted) = (1, 1);
134  
135 # gather absolute differences
136 173 ▶ unless (@lookback < $build_up_count) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@lookback < $build_up_count) 153 20 173
137 153 $ad = abs($spot - $lookback[-$build_up_count][1]) / sqrt($build_up_count);
138 153 push @ads, $ad;
139 }
140  
141 # build condition: the current tick is 60s newer
142 # and we have enough absolute differences
143 173 ▶ if ( @minute
Branch: 1 branch
BranchTrueFalseTotal
if (@minute and $minute[0] < $epoch - 60 and @ads >= $build_up_count) 1 172 173
Condition83%5/6
@minute and $minute[0] < $epoch - 60 and @ads >= $build_up_count
!ll&&!rl&&r
17201
@minute and $minute[0] < $epoch - 60
!ll&&!rl&&r
31691
MC/DC66%2/3
@minute and $minute[0] < $epoch - 60 and @ads >= $build_up_count
@minute $minute[0] < $epoch - 60 @ads >= $build_up_count
Truth table75%3/4
A and B and C
A= @minuteB= $minute[0] < $epoch - 60C= @ads >= $build_up_count
ABCresult
0XX0
10X0
1100
1111
144 and $minute[0] < $epoch - 60
145 and @ads >= $build_up_count)
146 {
147 1 $build = 0;
148 1 my @new_ads = sort { $a <=> $b } @ads;
149 1 my $cut = int(@new_ads / $build_up_count);
150 1 @new_ads = @new_ads[$cut .. ($build_up_count - 1) * $cut];
151 1 $mad = sum(@new_ads) / @new_ads;
152 1 @mads = ($mad) x scalar(@$decay_speeds);
153 }
154 } else {
155 # prevent @minute overgrow
156 40 ▶ while (@minute and $minute[0] < $epoch - 60) {
Branch: 1 branch
BranchTrueFalseTotal
if (@minute and $minute[0] < $epoch - 60) 41 40 81
Condition66%2/3
@minute and $minute[0] < $epoch - 60
!ll&&!rl&&r
04041
MC/DC50%1/2
@minute and $minute[0] < $epoch - 60
@minute $minute[0] < $epoch - 60
Truth table66%2/3
A and B
A= @minuteB= $minute[0] < $epoch - 60
ABresult
0X0
100
111
157 41 shift @minute;
158 }
159 40 my $density = 60 / (1 + @minute); # the number "1", beacuse we account the current value too
160 40 my $ha = $wsum / $csum;
161 40 my $vol = $mad / $sqrt2pi;
162 40 my $diff = abs($spot - $ha);
163  
164 # ther there is zero-difference, we accept current piece of data;
165 # otherwise, if it is zero-volatility (flat), we reject it.
166 40 ▶ my $reject =
Branch: 2 branches
BranchTrueFalseTotal
$diff ? : 40 0 40
$vol ? : 40 0 40
167 $diff
168 ? ($vol ? ($diff / $vol) : $reject_criterium + 1)
169 : 0;
170  
171 40 $accepted = !($reject > $reject_criterium);
172 40 $trust_w = 1 / (1 + ($reject / $reject_criterium)**8);
173  
174 40 ▶ if (not $accepted and $lookback_rejected > $cap * @lookback) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $accepted and $lookback_rejected > $cap * @lookback) 0 40 40
Condition66%2/3
not $accepted and $lookback_rejected > $cap * @lookback
!ll&&!rl&&r
3910
MC/DC0%0/2
not $accepted and $lookback_rejected > $cap * @lookback
not $accepted $lookback_rejected > $cap * @lookback
Truth table66%2/3
not(A) and B
A= not $acceptedB= $lookback_rejected > $cap * @lookback
ABresult
0X0
100
111
175 0 ($accepted, $trust_w) = (1, 1);
176 }
177 40 $ad = abs($spot - $_accepted->[-$build_up_count][1]) / sqrt($build_up_count);
178 40 ▶ if ($ad) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ad) 40 0 40
179 40 for my $idx (0 .. @$decay_speeds - 1) {
180 # MAD (mean absolute deviation)
181 120 my $mu = $trust_w * (1 - exp(-$density * $decay_speeds->[$idx]));
182 120 $mads[$idx] = (1 - $mu) * $mads[$idx] + $mu * $ad;
183 }
184 }
185 40 $mad = max(@mads);
186 }
187 213 push @minute, $epoch;
188 213 push @lookback, [$epoch, $spot, $trust_w, $accepted];
189 213 ▶ if ($accepted) {
Branch: 1 branch
BranchTrueFalseTotal
if ($accepted) { } 212 1 213
190 212 push @$_accepted, [$epoch, $spot];
191 212 ▶ shift @$_accepted while @$_accepted > $build_up_count;
Branch: 1 branch
BranchTrueFalseTotal
@$_accepted > $build_up_count and do { shift @$_accepted } 192 212 404
192 } else {
193 1 ++$lookback_rejected;
194 }
195 213 ▶ if ($trust_w) {
Branch: 1 branch
BranchTrueFalseTotal
if ($trust_w) 213 0 213
196 213 $wsum = 0.5 * $wsum + $spot * $trust_w;
197 213 $csum = 0.5 * $csum + $trust_w;
198 }
199 213 return $accepted;
200 4 };
201 4 return $fn;
202 }
203  
204 2 1;
↑ Summary