blib/lib/Algorithm/CurveFit.pm

filter: Statementstmt 91.6% 131 / 143 Branchbran 56.0% 28 / 50 Conditioncond 36.1% 13 / 36 MC/DCmcdc 5.0% 1 / 20 Subroutinesub 100% 11 / 11 Podpod 100% 1 / 1 totaltotal 70.8% 185 / 261 CC 45 SCAR 43.6
CC
45
Cov
75%
curve_fit
95.6
BEGIN
1.0
BEGIN
1.0
CRAP 78.4
↑ Summary
1 package Algorithm::CurveFit;
2  
3 3 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 3 our $VERSION = '1.06';
8  
9 3 require Exporter;
10  
11 3 our @ISA = qw(Exporter);
12  
13 3 our %EXPORT_TAGS = (
14 'all' => [ qw( curve_fit ) ]
15 );
16  
17 3 our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
18  
19 3 our @EXPORT = qw();
20  
21 3 ▶use Carp qw/confess/;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 3 ▶use Math::Symbolic qw/parse_from_string/;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 3 ▶use Math::MatrixReal;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 3 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 # machine epsilon
27 3 ▶use constant EPS => 2.2e-16;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 3 ▶use constant SQRT_EPS => sqrt(EPS);
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 2 ▶sub curve_fit {
Subroutine curve_fit: called CC=45 SCAR=45.6
Pod documented
31 2 ▶ shift @_ if not ref $_[0] and defined $_[0] and $_[0] eq 'Algorithm::CurveFit';
Branch: 1 branch
BranchTrueFalseTotal
if not ref $_[0] and defined $_[0] and $_[0] eq "Algorithm::CurveFit" 1 1 2
Condition50%3/6
not ref $_[0] and defined $_[0] and $_[0] eq "Algorithm::CurveFit"
!ll&&!rl&&r
011
not ref $_[0] and defined $_[0]
!ll&&!rl&&r
002
MC/DC33%1/3
not ref $_[0] and defined $_[0] and $_[0] eq "Algorithm::CurveFit"
not ref $_[0] defined $_[0] $_[0] eq "Algorithm::CurveFit"
Truth table50%2/4
not(A) and B and C
A= not ref $_[0]B= defined $_[0]C= $_[0] eq "Algorithm::CurveFit"
ABCresult
0XX0
10X0
1100
1111
32  
33 2 ▶ confess('Uneven number of arguments to Algorithm::CurveFit::curve_fit.')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 0 2 2
34 if @_ % 2;
35  
36 2 my %args = @_;
37  
38 # Formula
39 2 ▶ confess("Missing 'formula' parameter.") if not defined $args{formula};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"formula"} 0 2 2
40 2 my $formula;
41 2 ▶ if (ref($args{formula}) =~ /^Math::Symbolic/) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref($args{'formula'}) =~ /^Math::Symbolic/) { } 0 2 2
42 0 $formula = $args{formula};
43 }
44 else {
45 2 eval { $formula = parse_from_string( $args{formula} ); };
46 2 ▶ confess( "Cannot parse formula '" . $args{formula} . "'. ($@)" )
Branch: 1 branch
BranchTrueFalseTotal
if not defined $formula or $@ 0 2 2
Condition33%1/3
not defined $formula or $@
l!l&&r!l&&!r
002
MC/DC0%0/2
not defined $formula or $@
not defined $formula $@
Truth table33%1/3
not(A) or B
A= not defined $formulaB= $@
ABresult
1X1
011
000
47 if not defined $formula or $@;
48 }
49  
50 # Variable (optional)
51 2 my $variable = $args{variable};
52 2 ▶ $variable = 'x' if not defined $variable;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $variable 0 2 2
53 confess("Formula '"
54 . $args{formula}
55 . "' not explicitly dependent on "
56 . "variable '$variable'." )
57 2 ▶ if not grep { $_ eq $variable } $formula->explicit_signature();
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $variable;} $formula->explicit_signature 0 2 2
58  
59 # Parameters
60 2 my $params = $args{params};
61  
62 2 ▶ confess("Parameter 'params' has to be an array reference.")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $params and ref $params eq "ARRAY" 0 2 2
Condition33%1/3
defined $params and ref $params eq "ARRAY"
!ll&&!rl&&r
002
MC/DC0%0/2
defined $params and ref $params eq "ARRAY"
defined $params ref $params eq "ARRAY"
Truth table33%1/3
A and B
A= defined $paramsB= ref $params eq "ARRAY"
ABresult
0X0
100
111
63 if not defined $params
64 or not ref($params) eq 'ARRAY';
65 2 my @parameters = @$params;
66 2 ▶ confess('No parameters specified.') if not @parameters;
Branch: 1 branch
BranchTrueFalseTotal
unless @parameters 0 2 2
67 confess('Individual parameters need to be array references.')
68 2 ▶ if grep { not defined $_ or not ref($_) eq 'ARRAY' } @parameters;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not defined $_ && ref $_ eq "ARRAY";} @parameters 0 2 2
Condition33%1/3
defined $_ && ref $_ eq 'ARRAY'
!ll&&!rl&&r
006
MC/DC0%0/2
defined $_ && ref $_ eq 'ARRAY'
defined $_ ref $_ eq 'ARRAY'
Truth table33%1/3
A && B
A= defined $_B= ref $_ eq 'ARRAY'
ABresult
0X0
100
111
69 2 foreach my $p (@parameters) {
70 confess("Weird parameter\n'"
71 . Dumper($p)
72 . "' Should have the format\n"
73 . "[ NAME_STRING, GUESSED_VALUE, ACCURACY ]\n"
74 . "With the accuracy being optional. See docs." )
75 if @$p > 3
76 or @$p < 2
77 6 ▶ or grep { not defined $_ } @$p;
Branch: 1 branch
BranchTrueFalseTotal
if @$p > 3 or @$p < 2 or grep {not defined $_;} @$p 0 6 6
Condition33%2/6
@$p > 3 or @$p < 2 or grep {not defined $_;} @$p
l!l&&r!l&&!r
006
@$p > 3 or @$p < 2
l!l&&r!l&&!r
006
MC/DC0%0/3
@$p > 3 or @$p < 2 or grep {not defined $_;} @$p
@$p > 3 @$p < 2 grep {not defined $_;} @$p
Truth table25%1/4
A or B or C
A= @$p > 3B= @$p < 2C= grep {not defined $_;} @$p
ABCresult
1XX1
01X1
0011
0000
78  
79 confess("Formula '"
80 . $args{formula}
81 . "' not explicitly dependent on "
82 . "parameter '"
83 . $p->[0]
84 . "'." )
85 6 ▶ if not grep { $_ eq $p->[0] } $formula->explicit_signature();
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $p->[0];} $formula->explicit_signature 0 6 6
86 }
87  
88 # XData
89 2 my $xdata = $args{xdata};
90 2 ▶ confess('X-Data missing.')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $xdata and ref $xdata eq "ARRAY" and @$xdata 0 2 2
Condition33%2/6
defined $xdata and ref $xdata eq "ARRAY" and @$xdata
!ll&&!rl&&r
002
defined $xdata and ref $xdata eq "ARRAY"
!ll&&!rl&&r
002
MC/DC0%0/3
defined $xdata and ref $xdata eq "ARRAY" and @$xdata
defined $xdata ref $xdata eq "ARRAY" @$xdata
Truth table25%1/4
A and B and C
A= defined $xdataB= ref $xdata eq "ARRAY"C= @$xdata
ABCresult
0XX0
10X0
1100
1111
91 if not defined $xdata
92 or not ref($xdata) eq 'ARRAY'
93 or not @$xdata;
94 2 my @xdata = @$xdata;
95  
96 # YData
97 2 my $ydata = $args{ydata};
98 2 ▶ confess('Y-Data missing.')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ydata and ref $ydata eq "ARRAY" and @$ydata 0 2 2
Condition33%2/6
defined $ydata and ref $ydata eq "ARRAY" and @$ydata
!ll&&!rl&&r
002
defined $ydata and ref $ydata eq "ARRAY"
!ll&&!rl&&r
002
MC/DC0%0/3
defined $ydata and ref $ydata eq "ARRAY" and @$ydata
defined $ydata ref $ydata eq "ARRAY" @$ydata
Truth table25%1/4
A and B and C
A= defined $ydataB= ref $ydata eq "ARRAY"C= @$ydata
ABCresult
0XX0
10X0
1100
1111
99 if not defined $ydata
100 or not ref($ydata) eq 'ARRAY'
101 or not @$ydata;
102 2 ▶ confess('Y-Data and X-Data need to have the same number of elements.')
Branch: 1 branch
BranchTrueFalseTotal
unless @$ydata == @xdata 0 2 2
103 if not @$ydata == @xdata;
104 2 my @ydata = @$ydata;
105  
106 # Max_Iter (optional)
107 2 my $max_iter = $args{maximum_iterations};
108 2 ▶ $max_iter = 0 if not defined $max_iter;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $max_iter 0 2 2
109  
110 # Add third element (dlamda) to parameter arrays in case they're missing.
111 2 foreach my $param (@parameters) {
112 6 ▶ push @$param, 0 if @$param < 3;
Branch: 1 branch
BranchTrueFalseTotal
if @$param < 3 0 6 6
113 }
114  
115 # Array holding all first order partial derivatives of the function in respect
116 # to the parameters in order.
117 2 my @derivatives;
118 2 my @param_names = ($variable, map {$_->[0]} @parameters);
119 2 foreach my $param (@parameters) {
120 6 my $deriv =
121 Math::Symbolic::Operator->new( 'partial_derivative', $formula,
122 $param->[0] );
123 6 $deriv = $deriv->simplify()->apply_derivatives()->simplify();
124 6 my ($sub, $trees) = Math::Symbolic::Compiler->compile_to_sub($deriv, \@param_names);
125 6 ▶ if ($trees) {
Branch: 1 branch
BranchTrueFalseTotal
if ($trees) { } 6 0 6
126 6 push @derivatives, $deriv; # residual trees, need to evaluate
127 } else {
128 0 push @derivatives, $sub;
129 }
130 }
131  
132 # if not compilable, close over a ->value call for convenience later on
133 2 my $formula_sub = do {
134 2 my ($sub, $trees) = Math::Symbolic::Compiler->compile_to_sub($formula, \@param_names);
135 $trees
136 492 ▶ ? sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
137 $formula->value(
138 492 map { ($param_names[$_] => $_[$_]) } 0..$#param_names
139 )
140 }
141 2 ▶ : $sub
Branch: 1 branch
BranchTrueFalseTotal
$trees ? : 2 0 2
142 };
143  
144 2 my $dbeta;
145  
146 # Iterative approximation of the parameters
147 2 my $iteration = 0;
148  
149 # As long as we're under max_iter or maxiter==0
150 2 ▶ while ( !$max_iter || ++$iteration < $max_iter ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $max_iter or ++$iteration < $max_iter) 5 0 5
Condition33%1/3
not $max_iter or ++$iteration < $max_iter
l!l&&r!l&&!r
050
MC/DC0%0/2
not $max_iter or ++$iteration < $max_iter
not $max_iter ++$iteration < $max_iter
Truth table33%1/3
not(A) or B
A= not $max_iterB= ++$iteration < $max_iter
ABresult
1X1
011
000
151 # Generate Matrix A
152 5 my @cols;
153 5 my $pno = 0;
154 5 my @par_values = map {$_->[1]} @parameters;
155 5 foreach my $param (@parameters) {
156 16 my $deriv = $derivatives[ $pno++ ];
157  
158 16 my @ary;
159 16 ▶ if (ref $deriv eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $deriv eq 'CODE') { } 0 16 16
160 0 foreach my $x ( 0 .. $#xdata ) {
161 0 my $xv = $xdata[$x];
162 0 my $value = $deriv->($xv, @par_values);
163 0 ▶ if (not defined $value) { # fall back to numeric five-point stencil
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value) 0 0 0
164 0 my $h = SQRT_EPS*$xv; my $t = $xv + $h; $h = $t-$xv; # numerics. Cf. NR
165 0 $value = $formula_sub->($xv, map { $_->[1] } @parameters)
166 }
167 0 push @ary, $value;
168 }
169 }
170 else {
171 16 $deriv = $deriv->new; # better safe than sorry
172 16 foreach my $x ( 0 .. $#xdata ) {
173 968 my $xv = $xdata[$x];
174 my $value = $deriv->value(
175 $variable => $xv,
176 968 map { ( @{$_}[ 0, 1 ] ) } @parameters # a, guess
177 );
178 968 ▶ if (not defined $value) { # fall back to numeric five-point stencil
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value) 1 967 968
179 1 my $h = SQRT_EPS*$xv; my $t = $xv + $h; $h = $t-$xv; # numerics. Cf. NR
180 1 $value = $formula_sub->($xv, map { $_->[1] } @parameters)
181 }
182 968 push @ary, $value;
183 }
184 }
185 16 push @cols, \@ary;
186 }
187  
188 # Prepare matrix of datapoints X parameters
189 5 my $A = Math::MatrixReal->new_from_cols( \@cols );
190  
191 # transpose
192 5 my $AT = ~$A;
193 5 my $M = $AT * $A;
194  
195 # residuals
196 my @beta =
197 map {
198 5 $ydata[$_] - $formula_sub->(
199 $xdata[$_],
200 343 map { $_->[1] } @parameters
201 )
202 } 0 .. $#xdata;
203 5 $dbeta = Math::MatrixReal->new_from_cols( [ \@beta ] );
204  
205 5 my $N = $AT * $dbeta;
206  
207 # Normalize before solving => better accuracy.
208 5 my ( $matrix, $vector ) = $M->normalize($N);
209  
210 # solve
211 5 my $LR = $matrix->decompose_LR();
212 5 my ( $dim, $x, $B ) = $LR->solve_LR($vector);
213  
214 # extract parameter modifications and test for convergence
215 5 my $last = 1;
216 5 foreach my $pno ( 1 .. @parameters ) {
217 16 my $dlambda = $x->element( $pno, 1 );
218 16 ▶ $last = 0 if abs($dlambda) > $parameters[ $pno - 1 ][2];
Branch: 1 branch
BranchTrueFalseTotal
if abs $dlambda > $parameters[$pno - 1][2] 7 9 16
219 16 $parameters[ $pno - 1 ][1] += $dlambda;
220 }
221 5 ▶ last if $last;
Branch: 1 branch
BranchTrueFalseTotal
if $last 2 3 5
222 }
223  
224 # Recalculate dbeta for the squared residuals.
225 my @beta =
226 map {
227 2 $ydata[$_] - $formula_sub->(
228 $xdata[$_],
229 148 map { $_->[1] } @parameters
230 )
231 } 0 .. $#xdata;
232 2 $dbeta = Math::MatrixReal->new_from_cols( [ \@beta ] );
233  
234 2 my $square_residual = $dbeta->scalar_product($dbeta);
235 2 return $square_residual;
236 }
237  
238 3 1;
239 __END__
↑ Summary