blib/lib/Math/KalmanFilter.pm

filter: Statementstmt 45.2% 19 / 42 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 66.6% 4 / 6 Podpod 100% 1 / 1 totaltotal 48.9% 24 / 49 CC 1 SCAR 2.9
CC
1
Cov
45%
__ANON__
2.0
getAngle
2.0
BEGIN
1.0
CRAP 1.3
↑ Summary
1 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 package Math::KalmanFilter;
5  
6 # PODNAME: Math::KalmanFilter
7 # ABSTRACT: Kalman Filter(also known as Linear Quadratic Estimation) implementation for sensor fusion and such
8 #
9 # This file is part of Math-KalmanFilter
10 #
11 # This software is copyright (c) 2016 by Shantanu Bhadoria.
12 #
13 # This is free software; you can redistribute it and/or modify it under
14 # the same terms as the Perl 5 programming language system itself.
15 #
16 1 our $VERSION = '0.05'; # VERSION
17  
18 # Dependencies
19 1 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22  
23 1 has qAngle => (
24 is => 'rw',
25 default => 0.001,
26 );
27  
28  
29 1 has qBias => (
30 is => 'rw',
31 default => 0.003,
32 );
33  
34  
35 1 has rMeasure => (
36 is => 'rw',
37 default => 0.03,
38 );
39  
40  
41 1 has bias => (
42 is => 'rw',
43 default => 0,
44 );
45  
46  
47 has covariance => (
48 is => 'rw',
49 default => sub {
50 0 ▶ return [ [ 0, 0 ], [ 0, 0 ] ];
Subroutine __ANON__: not called CC=1 SCAR=6.9
51 }
52 1 );
53  
54  
55 1 has angle => ( is => 'rw', );
56  
57  
58 sub getAngle {
59 0 ▶ my ( $self, $newAngle, $newRate, $deltaTime ) = @_;
Subroutine getAngle: not called CC=1 SCAR=6.9
Pod documented
60  
61 0 my $covariance = $self->covariance;
62 0 my $angle = $self->angle;
63 0 my $bias = $self->bias;
64  
65 0 my $rate = $newAngle - $bias;
66 0 $angle += $deltaTime * $rate;
67  
68 0 $covariance->[0]->[0] +=
69 $deltaTime *
70 ( $deltaTime * $covariance->[1]->[1] -
71 $covariance->[0]->[1] -
72 $covariance->[1]->[0] +
73 $self->qAngle );
74 0 $covariance->[0]->[1] -= $deltaTime * $covariance->[1]->[1];
75 0 $covariance->[1]->[0] -= $deltaTime * $covariance->[1]->[1];
76 0 $covariance->[1]->[1] += $deltaTime * $self->qBias;
77  
78 0 my $innovationCovariance = $covariance->[0]->[0] + $self->rMeasure;
79  
80 0 my $kalmanGain = [
81 $covariance->[0]->[0] / $innovationCovariance,
82 $covariance->[1]->[0] / $innovationCovariance,
83 ];
84  
85 0 my $y = $newAngle - $angle;
86 0 $angle += $kalmanGain->[0] * $y;
87 0 $bias += $kalmanGain->[1] * $y;
88  
89 0 $covariance->[0]->[0] -= $kalmanGain->[0] * $covariance->[0]->[0];
90 0 $covariance->[0]->[1] -= $kalmanGain->[0] * $covariance->[0]->[1];
91 0 $covariance->[1]->[0] -= $kalmanGain->[1] * $covariance->[0]->[0];
92 0 $covariance->[1]->[1] -= $kalmanGain->[1] * $covariance->[0]->[1];
93  
94 0 $self->covariance($covariance);
95 0 $self->angle($angle);
96  
97 0 return $angle;
98 }
99  
100 1 1;
101  
102 __END__
103  
104 =pod
105  
106 =head1 NAME
107  
108 Math::KalmanFilter - Kalman Filter(also known as Linear Quadratic Estimation) implementation for sensor fusion and such
109  
110 =head1 VERSION
111  
112 version 0.05
113  
114 =head1 SYNOPSIS
115  
116 use Math::KalmanFilter;
117 use Time::HiRes qw(time);
118
119 my $oldTime = time();
120 # Read State from state sensor, in a IMU this would be one of the accelerometer orientation angle
121 # e.g. Angle between orientation vector and X axis in degrees.
122 my $state = readStateSensor();
123
124 # Read rate of change of state, in a IMU gyroscope measures the delta i.e. the Rate of change of
125 # $state e.g. rate of change of angle between orientation vector and X axis in degree per second.
126 my $delta = readDeltaSensor();
127
128 #Created a Kalman filter object to hold state changes for your measurement target.
129 $kalman = Math::KalmanFilter->new(
130 angle => $state
131 );
132
133 while($keep_running){
134 my $newTime = time();
135 my $deltaTime = $newTime - $oldTime;
136 $oldTime = $newTime;
137
138 my $state = readStateSensor();
139 my $delta = readDeltaSensor();
140 my $angle = $kalman->getAngle($state,$delta,$deltaTime);
141
142 print "CURRENT ANGLE:$angle";
143 }
144  
145 =head1 DESCRIPTION
146  
147 The Kalman filter, also known as linear quadratic estimation (LQE), is an algorithm that uses a series
148 of measurements observed over time, containing noise (random variations) and other inaccuracies, and
149 produces estimates of unknown variables that tend to be more precise than those based on a single
150 measurement alone.
151  
152 Algorithm is recursive, which means it takes the output of its previous calculations as a factor in
153 calculating the next step which improves its accuracy over time. The key to Kalman filters are two sensors
154 with different kind of accuracy issues in each. Sensor A or the state sensor might give in-accurate value
155 for a measurement on the whole but it doesn't drift. Sensor B or delta sensor gives gives much more accurate
156 rate of change in value(or delta) but it drifts over time due to its small inaccuracies as it only measures
157 rate of change in value and not the actual value. Kalman filter uses this knowledge to fuse results from both
158 sensors to give a state value which is more accurate than state value received from any of these filters
159 alone.
160  
161 An example of application for this is calculating orientation of objects using Gyroscopes and Accelerometers.
162  
163 While Accelerometer is usually used to measure gravity it can be used to measure the inclination of a body
164 with respect to the surface of earth along the x and y axis(not z axis as Z axis is usually facing the
165 opposite direction as the force of gravity) by measuring the direction in which the force of gravity is
166 applied.
167  
168 Gyroscope measures the rate of rotation about one or all the axis of a body. while it gives fairly accurate
169 estimation of the angular velocity, if we use it to calculate the current inclination based on the starting
170 inclination and the angular velocity, there is a lot of drift, which means the gyroscope error will accumulate
171 over time as we calculate newer angles based on previous angle and angular velocity and the error in angular
172 velocity piles on.
173  
174 A real life example of how Kalman filter works is while driving on a highway in a car. If you take the time
175 passed since when your started driving and your estimated average speed every hour and use it to calculate
176 the distance you have traveled your calculation will become more inaccurate as you drive on.
177  
178 This is drift in value. However if you watch each milestone and calculate your current position using milestone
179 data and your speed since the last milestone your result will be much more accurate. That is approximately close
180  
181 to how Kalman filter works.
182  
183 =head1 ATTRIBUTES
184  
185 =head2 qAngle
186  
187 * default: 0.001
188  
189 =head2 qBias
190  
191 * default: 0.003
192  
193 =head2 rMeasure
194  
195 * default: 0.03
196  
197 =head2 bias
198  
199 * starting value(default): 0
200 * recalculated(optimised) at each new sensor reading.
201  
202 =head2 covariance
203  
204 This is the covariance matrix, it is stored as a 2d array ref
205 * starting value(default): [[0,0],[0,0]]
206 * recalculated(optimised) at each new sensor reading.
207  
208 =head2 angle
209  
210 Calculated angle
211  
212 =head1 METHODS
213  
214 =head2 getAngle
215  
216 Calculate new state based on observed reading from state sensor, delta sensor and time elapsed since last reading.
217  
218 =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan
219  
220 =head1 SUPPORT
221  
222 =head2 Bugs / Feature Requests
223  
224 Please report any bugs or feature requests through github at
225 L<https://github.com/shantanubhadoria/perl-math-kalmanfilter/issues>.
226 You will be notified automatically of any progress on your issue.
227  
228 =head2 Source Code
229  
230 This is open source software. The code repository is available for
231 public review and contribution under the terms of the license.
232  
233 L<https://github.com/shantanubhadoria/perl-math-kalmanfilter>
234  
235 git clone git://github.com/shantanubhadoria/perl-math-kalmanfilter.git
236  
237 =head1 AUTHOR
238  
239 Shantanu Bhadoria <shantanu at cpan dott org>
240  
241 =head1 CONTRIBUTORS
242  
243 =for stopwords Shantanu Bhadoria
244  
245 =over 4
246  
247 =item *
248  
249 Shantanu Bhadoria <shantanu.bhadoria@gmail.com>
250  
251 =item *
252  
253 Shantanu Bhadoria <shantanu@cpan.org>
254  
255 =back
256  
257 =head1 COPYRIGHT AND LICENSE
258  
259 This software is copyright (c) 2016 by Shantanu Bhadoria.
260  
261 This is free software; you can redistribute it and/or modify it under
262 the same terms as the Perl 5 programming language system itself.
263  
264 =cut
↑ Summary