lib/Algorithm/CurveFit/Simple.pm

filter: Statementstmt 94.3% 199 / 211 Branchbran 80.6% 71 / 88 Conditioncond 52.5% 21 / 40 MC/DCmcdc 30.4% 7 / 23 Subroutinesub 100% 16 / 16 Podpod 100% 1 / 1 totaltotal 83.1% 315 / 379 CC 64 SCAR 22.7
CC
64
Cov
86%
_init_data
17.1
_implement_formula_as_coderef
11.8
fit
11.7
CRAP 9.7
↑ Summary
1 package Algorithm::CurveFit::Simple;
2  
3 # ABSTRACT: Convenience wrapper around Algorithm::CurveFit.
4  
5 5 our $VERSION = '1.03'; # VERSION 1.03
6  
7 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use Algorithm::CurveFit;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 5 ▶use JSON::PP;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 5 our %STATS_H; # side-products of fit() stored here for profiling purposes
14  
15 5 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
16 5 require Exporter;
17 5 our $VERSION = '1.03';
18 5 our @ISA = qw(Exporter);
19 5 our @EXPORT_OK = qw(fit %STATS_H);
20 }
21  
22 # fit() - only public function for this distribution
23 # Given at least parameter "xy", generate a best-fit curve within a time limit.
24 # Output: max deviation, avg deviation, implementation source string (perl or C, for now).
25 # Optional parameters and their defaults:
26 # terms => 3 # number of terms in formula, max is 10
27 # time_limit => 3 # number of seconds to try for better fit
28 # inv => 1 # invert sense of curve-fit, from x->y to y->x
29 # impl_lang => 'perl' # programming language used for output implementation: perl, c
30 # impl_name => 'x2y' # name given to output implementation function
31 1 ▶sub fit {
Subroutine fit: called CC=10 SCAR=24.6
Pod documented
32 1 my %p = @_;
33  
34 1 my $formula = _init_formula(%p);
35 1 my ($xdata, $ydata) = _init_data(%p);
36 1 my $parameters = _init_parameters($xdata, $ydata, %p);
37  
38 1 my $iter_mode = 'time';
39 1 my $time_limit = 3; # sane default?
40 1 ▶ $time_limit = 0.01 if ($time_limit < 0.01);
Branch: 1 branch
BranchTrueFalseTotal
if $time_limit < "0.01" 0 1 1
41 1 my $n_iter;
42 1 ▶ if (defined($p{iterations})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $p{'iterations'}) { } 0 1 1
43 0 $iter_mode = 'iter';
44 0 ▶ $n_iter = $p{iterations} || 10000;
Condition0%0/2
$p{'iterations'} || 10000
l!l
00
MC/DC0%0/1
$p{'iterations'} || 10000
$p{'iterations'}
Truth table0%0/2
A
A= $p{'iterations'}
Aresult
11
00
45 } else {
46 1 ▶ $time_limit = $p{time_limit} // $time_limit;
Condition33%1/3
$p{"time_limit"} // $time_limit
l!l&&r!l&&!r
010
MC/DC0%0/2
$p{"time_limit"} // $time_limit
$p{"time_limit"} $time_limit
Truth table33%1/3
A // B
A= $p{"time_limit"}B= $time_limit
ABresult
1X1
011
000
47 1 $n_iter = 10000 * $time_limit; # will use this to figure out how long it -really- takes.
48 }
49
50 1 my ($n_sec, $params_ar_ar);
51 1 ▶ if ($iter_mode eq 'time') {
Branch: 1 branch
BranchTrueFalseTotal
if ($iter_mode eq "time") 1 0 1
52 1 ($n_sec, $params_ar_ar) = _try_fit($formula, $parameters, $xdata, $ydata, $n_iter, $p{fitter_class});
53 1 $STATS_H{iter_mode} = $iter_mode;
54 1 $STATS_H{fit_calib_iter} = $n_iter;
55 1 $STATS_H{fit_calib_time} = $n_sec;
56 1 $STATS_H{fit_calib_parar} = $params_ar_ar;
57 1 $n_iter = int(($time_limit / $n_sec) * $n_iter + 1);
58 }
59  
60 1 ($n_sec, $params_ar_ar) = _try_fit($formula, $parameters, $xdata, $ydata, $n_iter, $p{fitter_class});
61 1 $STATS_H{fit_iter} = $n_iter;
62 1 $STATS_H{fit_time} = $n_sec;
63 1 $STATS_H{fit_parar} = $params_ar_ar;
64  
65 1 my $coderef = _implement_formula($params_ar_ar, "coderef", "", $xdata, \%p);
66 1 my ($max_dev, $avg_dev) = _calculate_deviation($coderef, $xdata, $ydata);
67 1 ▶ my $impl_lang = $p{impl_lang} // 'perl';
Condition50%1/2
$p{"impl_lang"} // "perl"
l!l
10
MC/DC0%0/1
$p{"impl_lang"} // "perl"
$p{"impl_lang"}
Truth table50%1/2
A
A= $p{"impl_lang"}
Aresult
11
00
68 1 $impl_lang = lc($impl_lang);
69 1 ▶ my $impl_name = $p{inv} ? "y2x" : "x2y";
Branch: 1 branch
BranchTrueFalseTotal
$p{'inv'} ? : 0 1 1
70 1 ▶ $impl_name = $p{impl_name} // $impl_name;
Condition33%1/3
$p{"impl_name"} // $impl_name
l!l&&r!l&&!r
010
MC/DC0%0/2
$p{"impl_name"} // $impl_name
$p{"impl_name"} $impl_name
Truth table33%1/3
A // B
A= $p{"impl_name"}B= $impl_name
ABresult
1X1
011
000
71 1 my $impl = $coderef;
72 1 ▶ $impl = _implement_formula($params_ar_ar, $impl_lang, $impl_name, $xdata, \%p) unless($impl_lang eq 'coderef');
Branch: 1 branch
BranchTrueFalseTotal
unless $impl_lang eq "coderef" 1 0 1
73 1 return ($max_dev, $avg_dev, $impl);
74 }
75  
76 # ($n_sec, $params_ar_ar) = _try_fit($formula, $parameters, $xdata, $ydata, $n_iter, $p{fitter_class});
77 2 ▶sub _try_fit {
Subroutine _try_fit: called CC=2 SCAR=7.0
78 2 my ($formula, $parameters, $xdata, $ydata, $n_iter, $fitter_class) = @_;
79 2 ▶ $fitter_class //= "Algorithm::CurveFit";
Condition50%1/2
$fitter_class //= "Algorithm::CurveFit"
l!l
02
MC/DC0%0/1
$fitter_class //= "Algorithm::CurveFit"
$fitter_class
Truth table50%1/2
A
A= $fitter_class
Aresult
11
00
80 2 my $params_ar_ar = [map {[@$_]} @$parameters]; # making a copy because curve_fit() is destructive
81 2 my $tm0 = Time::HiRes::time();
82 2 my $res = $fitter_class->curve_fit(
83 formula => $formula,
84 params => $params_ar_ar,
85 variable => 'x',
86 xdata => $xdata,
87 ydata => $ydata,
88 maximum_iterations => $n_iter
89 );
90 2 my $tm_elapsed = Time::HiRes::time() - $tm0;
91 2 return ($tm_elapsed, $params_ar_ar);
92 }
93  
94 11 ▶sub _init_formula {
Subroutine _init_formula: called CC=5 SCAR=16.1
95 11 my %p = @_;
96 11 my $formula = 'k + a*x + b*x^2 + c*x^3'; # sane'ish default
97 11 ▶ my $terms = $p{terms} // 3;
Condition100%2/2
$p{"terms"} // 3
l!l
101
MC/DC100%1/1
$p{"terms"} // 3
$p{"terms"}
Truth table100%2/2
A
A= $p{"terms"}
Aresult
11
00
98 11 ▶ die "maximum of 10 terms\n" if ($terms > 10);
Branch: 1 branch
BranchTrueFalseTotal
if $terms > 10 0 11 11
99 11 ▶ if ($terms != 3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($terms != 3) 8 3 11
100 8 $formula = 'k';
101 8 ▶ for (my $i = 1; $i <= $terms; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= $terms) 42 8 50
102 42 my $fact = chr(ord('a') + $i - 1);
103 42 $formula .= " + $fact * x^$i";
104 }
105 }
106 11 return $formula;
107 }
108  
109 # ($xdata, $ydata) = _init_data(%p);
110 15 ▶sub _init_data {
Subroutine _init_data: called CC=16 SCAR=28.4
111 15 my %p = @_;
112 15 my ($xdata, $ydata);
113 15 ▶ if (defined($p{xydata})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $p{'xydata'}) { } 7 8 15
elsif (defined $p{'xdata'} and defined $p{'ydata'}) { } 5 3 8
114 7 my $xy = $p{xydata};
115 7 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $xy eq "ARRAY" and @$xy >= 2 and ref $xy->[0] eq "ARRAY" and ref $xy->[1] eq "ARRAY") 0 7 7
Condition33%3/9
ref $xy eq "ARRAY" and @$xy >= 2 and ref $xy->[0] eq "ARRAY" and ref $xy->[1] eq "ARRAY"
!ll&&!rl&&r
007
ref $xy eq "ARRAY" and @$xy >= 2 and ref $xy->[0] eq "ARRAY"
!ll&&!rl&&r
007
ref $xy eq "ARRAY" and @$xy >= 2
!ll&&!rl&&r
007
MC/DC0%0/4
ref $xy eq "ARRAY" and @$xy >= 2 and ref $xy->[0] eq "ARRAY" and ref $xy->[1] eq "ARRAY"
ref $xy eq "ARRAY" @$xy >= 2 ref $xy->[0] eq "ARRAY" ref $xy->[1] eq "ARRAY"
Truth table20%1/5
A and B and C and D
A= ref $xy eq "ARRAY"B= @$xy >= 2C= ref $xy->[0] eq "ARRAY"D= ref $xy->[1] eq "ARRAY"
ABCDresult
0XXX0
10XX0
110X0
11100
11111
116 ref($xy) eq 'ARRAY'
117 && @$xy >= 2
118 && ref($xy->[0]) eq 'ARRAY'
119 && ref($xy->[1]) eq 'ARRAY'
120 ) {
121 0 die "xydata must be either an arrayref of [x, y] data point arrayrefs or an arrayref [[x0, x1, ... xN], [y0, y1, ... yN]]\n";
122 }
123 7 ▶ if (@$xy == 2 && @{$xy->[0]} > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$xy == 2 and @{$xy->[0];} > 2) { } 2 5 7
Condition100%3/3
@$xy == 2 and @{$xy->[0];} > 2
!ll&&!rl&&r
412
MC/DC100%2/2
@$xy == 2 and @{$xy->[0];} > 2
@$xy == 2 @{$xy->[0];} > 2
Truth table100%3/3
A and B
A= @$xy == 2B= @{$xy->[0];} > 2
ABresult
0X0
100
111
124 # user has provided [[x, ..], [y, ..]]
125 2 $xdata = $xy->[0];
126 2 $ydata = $xy->[1];
127 } else {
128 # user has provided [[x, y], [x, y], ..]
129 5 ▶ die "pairwise xydata must have two data points per element\n" unless(@{$xy->[0]} == 2);
Branch: 1 branch
BranchTrueFalseTotal
unless @{$xy->[0];} == 2 1 4 5
130 4 $xdata = [map {$_->[0]} @{$xy}];
131 4 $ydata = [map {$_->[1]} @{$xy}];
132 }
133 }
134 ▶ elsif (defined($p{xdata}) && defined($p{ydata})) {
Condition100%3/3
defined $p{"xdata"} and defined $p{"ydata"}
!ll&&!rl&&r
215
MC/DC100%2/2
defined $p{"xdata"} and defined $p{"ydata"}
defined $p{"xdata"} defined $p{"ydata"}
Truth table100%3/3
A and B
A= defined $p{"xdata"}B= defined $p{"ydata"}
ABresult
0X0
100
111
135 5 $xdata = $p{xdata};
136 5 $ydata = $p{ydata};
137 }
138 else {
139 3 die "must provide at least xydata or both xdata and ydata\n";
140 }
141 11 ▶ die "xdata and ydata must both be arrayref\n" unless (ref($xdata) eq "ARRAY" && ref($ydata) eq "ARRAY");
Branch: 1 branch
BranchTrueFalseTotal
unless ref $xdata eq "ARRAY" and ref $ydata eq "ARRAY" 0 11 11
Condition33%1/3
ref $xdata eq "ARRAY" and ref $ydata eq "ARRAY"
!ll&&!rl&&r
0011
MC/DC0%0/2
ref $xdata eq "ARRAY" and ref $ydata eq "ARRAY"
ref $xdata eq "ARRAY" ref $ydata eq "ARRAY"
Truth table33%1/3
A and B
A= ref $xdata eq "ARRAY"B= ref $ydata eq "ARRAY"
ABresult
0X0
100
111
142 11 ▶ die "xdata and ydata must have the same number of elements\n" unless (@$xdata == @$ydata);
Branch: 1 branch
BranchTrueFalseTotal
unless @$xdata == @$ydata 2 9 11
143 9 ▶ die "must have more than one data-point\n" unless (@$xdata > 1);
Branch: 1 branch
BranchTrueFalseTotal
unless @$xdata > 1 1 8 9
144 8 ▶ if ($p{inv}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p{"inv"}) 3 5 8
145 3 $STATS_H{xdata} = $ydata;
146 3 $STATS_H{ydata} = $xdata;
147 3 return ($ydata, $xdata);
148 }
149 5 $STATS_H{xdata} = $xdata;
150 5 $STATS_H{ydata} = $ydata;
151 5 return ($xdata, $ydata);
152 }
153  
154 # $parameters = _init_parameters($xdata, $ydata, %p);
155 3 ▶sub _init_parameters {
Subroutine _init_parameters: called CC=3 SCAR=11.0
156 3 my ($xdata, $ydata, %p) = @_;
157 3 my $k = 0;
158 3 my $n_points = @$xdata;
159 3 foreach my $v (@$ydata) { $k += $v; }
160 3 $k /= $n_points;
161 # zzapp -- implement any precision hints here.
162 3 my @params = (['k', $k, 0.0000001]);
163 3 ▶ my $terms = $p{terms} // 3;
Condition100%2/2
$p{"terms"} // 3
l!l
21
MC/DC100%1/1
$p{"terms"} // 3
$p{"terms"}
Truth table100%2/2
A
A= $p{"terms"}
Aresult
11
00
164 3 push @params, map {[chr(ord('a')+$_-1), 0.5, 0.0000001]} (1..$terms);
165 3 return \@params;
166 }
167  
168 # $impl = _implement_formula($params_ar_ar, $impl_lang, $impl_name, $xdata, \%p) unless($impl_lang eq 'coderef');
169 10 ▶sub _implement_formula {
Subroutine _implement_formula: called CC=3 SCAR=11.0
170 10 my ($params_ar_ar, $impl_lang, $impl_name, $xdata, $opt_hr) = @_;
171 10 ▶ return _implement_formula_as_coderef(@_) if ($impl_lang eq 'coderef');
Branch: 1 branch
BranchTrueFalseTotal
if $impl_lang eq "coderef" 2 8 10
172 # return _implement_formula_as_python(@_) if ($impl_lang eq 'python'); # zzapp
173 8 ▶ return _implement_formula_as_C(@_) if ($impl_lang eq 'c');
Branch: 1 branch
BranchTrueFalseTotal
if $impl_lang eq "c" 3 5 8
174 # return _implement_formula_as_R(@_) if ($impl_lang eq 'r'); # zzapp
175 # return _implement_formula_as_MATLAB(@_) if ($impl_lang eq 'matlab'); # zzapp
176 5 return _implement_formula_as_perl(@_);
177 }
178  
179 2 ▶sub _implement_formula_as_coderef {
Subroutine _implement_formula_as_coderef: called CC=9 SCAR=24.6
180 2 my ($params_ar_ar, $impl_lang, $impl_name, $xdata, $opt_hr) = @_;
181 2 my $k_ar = $params_ar_ar->[0];
182 2 my $formula = sprintf("%f", $k_ar->[1]);
183 2 ▶ for (my $i = 1; defined($params_ar_ar->[$i]); $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params_ar_ar->[$i]) 6 2 8
184 6 my $fact = $params_ar_ar->[$i]->[1];
185 6 ▶ my $pow = ($i == 1) ? "" : "**$i";
Branch: 1 branch
BranchTrueFalseTotal
$i == 1 ? : 2 4 6
186 6 $formula .= sprintf(' + %f * $x%s', $fact, $pow);
187 }
188 2 $STATS_H{impl_formula} = $formula;
189 2 my $bounder = '';
190 2 ▶ if ($opt_hr->{bounds_check}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt_hr->{"bounds_check"}) 0 2 2
191 0 my ($high_x, $low_x) = ($xdata->[0], $xdata->[0]);
192 0 foreach my $x (@$xdata) {
193 0 ▶ $high_x = $x if ($high_x < $x);
Branch: 1 branch
BranchTrueFalseTotal
if $high_x < $x 0 0 0
194 0 ▶ $low_x = $x if ($low_x > $x);
Branch: 1 branch
BranchTrueFalseTotal
if $low_x > $x 0 0 0
195 }
196 0 $bounder = 'die "x out of bounds (high)" if ($x > '.$high_x.'); die "x out of bounds (low)" if ($x < '.$low_x.');';
197 }
198 2 my $rounder = '';
199 2 ▶ $rounder = '$y = int($y + 0.5);' if ($opt_hr->{round_result});
Branch: 1 branch
BranchTrueFalseTotal
if $opt_hr->{"round_result"} 0 2 2
200 2 my $src = 'sub { my($x) = @_; '.$bounder.' my $y = '.$formula.'; '.$rounder.' return $y; }';
201 2 $STATS_H{impl_source} = $src;
202 2 $STATS_H{impl_exception} = '';
203 2 my $coderef = eval($src);
204 2 ▶ $STATS_H{impl_exception} = $@ unless(defined($coderef));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $coderef 0 2 2
205 2 return $coderef;
206 }
207  
208 5 ▶sub _implement_formula_as_perl {
Subroutine _implement_formula_as_perl: called CC=8 SCAR=20.8
209 5 my ($params_ar_ar, $impl_lang, $impl_name, $xdata, $opt_hr) = @_;
210 5 my $k_ar = $params_ar_ar->[0];
211 5 my $formula = sprintf("%.11f", $k_ar->[1]);
212 5 ▶ for (my $i = 1; defined($params_ar_ar->[$i]); $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params_ar_ar->[$i]) 15 5 20
213 15 my $fact = $params_ar_ar->[$i]->[1];
214 15 ▶ my $pow = ($i == 1) ? "" : "**$i";
Branch: 1 branch
BranchTrueFalseTotal
$i == 1 ? : 5 10 15
215 15 $formula .= sprintf(' + %.11f * $x%s', $fact, $pow);
216 }
217 5 $STATS_H{impl_formula} = $formula;
218 5 my $bounder = '';
219 5 ▶ if ($opt_hr->{bounds_check}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt_hr->{"bounds_check"}) 1 4 5
220 1 my ($high_x, $low_x) = ($xdata->[0], $xdata->[0]);
221 1 foreach my $x (@$xdata) {
222 7 ▶ $high_x = $x if ($high_x < $x);
Branch: 1 branch
BranchTrueFalseTotal
if $high_x < $x 1 6 7
223 7 ▶ $low_x = $x if ($low_x > $x);
Branch: 1 branch
BranchTrueFalseTotal
if $low_x > $x 1 6 7
224 }
225 1 $bounder = sprintf(' die "x out of bounds (high)" if ($x > %.11f);'."\n", $high_x) .
226 sprintf(' die "x out of bounds (low)" if ($x < %.11f);'."\n", $low_x);
227 }
228 5 my $rounder = '';
229 5 ▶ $rounder = ' $y = int($y + 0.5);'."\n" if ($opt_hr->{round_result});
Branch: 1 branch
BranchTrueFalseTotal
if $opt_hr->{"round_result"} 1 4 5
230 5 my $src = join("\n",(
231 "sub $impl_name {",
232 ' my($x) = @_;',
233 $bounder,
234 ' my $y = '.$formula.';',
235 $rounder,
236 ' return $y;',
237 '}'
238 ));
239 5 $STATS_H{impl_source} = $src;
240 5 $STATS_H{impl_exception} = '';
241 5 return $src;
242 }
243  
244 3 ▶sub _implement_formula_as_C {
Subroutine _implement_formula_as_C: called CC=10 SCAR=23.0
245 3 my ($params_ar_ar, $impl_lang, $impl_name, $xdata, $opt_hr) = @_;
246 3 my $k_ar = $params_ar_ar->[0];
247 3 my $src = "";
248 3 ▶ $src .= "#include <math.h>\n" if ($opt_hr->{round_result} && !$opt_hr->{suppress_includes});
Branch: 1 branch
BranchTrueFalseTotal
if $opt_hr->{"round_result"} and not $opt_hr->{"suppress_includes"} 1 2 3
Condition66%2/3
$opt_hr->{"round_result"} and not $opt_hr->{"suppress_includes"}
!ll&&!rl&&r
201
MC/DC50%1/2
$opt_hr->{"round_result"} and not $opt_hr->{"suppress_includes"}
$opt_hr->{"round_result"} not $opt_hr->{"suppress_includes"}
Truth table66%2/3
A and not(B)
A= $opt_hr->{"round_result"}B= not $opt_hr->{"suppress_includes"}
ABresult
0X0
100
111
249 3 $src .= "double $impl_name(double x) {\n";
250 3 $src .= sprintf(" double y = %.11f;\n", $k_ar->[1]);
251 3 $src .= " double xx = x;\n"; # eliminating pow() calls, which gcc doesn't seem willing to optimize completely away
252  
253 3 ▶ if ($opt_hr->{bounds_check}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt_hr->{"bounds_check"}) 1 2 3
254 1 my ($high_x, $low_x) = ($xdata->[0], $xdata->[0]);
255 1 foreach my $x (@$xdata) {
256 7 ▶ $high_x = $x if ($high_x < $x);
Branch: 1 branch
BranchTrueFalseTotal
if $high_x < $x 1 6 7
257 7 ▶ $low_x = $x if ($low_x > $x);
Branch: 1 branch
BranchTrueFalseTotal
if $low_x > $x 1 6 7
258 }
259 # zzapp -- this is kludgy. better way to signal bounds violation?
260 1 $src .= sprintf(" if (x > %.11f) return -1.0;\n", $high_x) .
261 sprintf(" if (x < %.11f) return -1.0;\n", $low_x);
262 }
263  
264 3 my $formula = "";
265 3 ▶ for (my $i = 1; defined($params_ar_ar->[$i]); $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params_ar_ar->[$i]) 9 3 12
266 9 my $fact = $params_ar_ar->[$i]->[1];
267 9 $formula .= sprintf(" y += %.11f * xx;\n", $fact);
268 9 ▶ $formula .= " xx *= x;\n" if(defined($params_ar_ar->[$i+1]));
Branch: 1 branch
BranchTrueFalseTotal
if defined $$params_ar_ar[$i + 1] 6 3 9
269 }
270 3 $STATS_H{impl_formula} = $formula; # zzapp -- not clean!
271  
272 3 $src .= $formula;
273 3 ▶ $src .= " y = round(y);\n" if ($opt_hr->{round_result});
Branch: 1 branch
BranchTrueFalseTotal
if $opt_hr->{"round_result"} 1 2 3
274 3 $src .= " return y;\n}\n";
275 3 $STATS_H{impl_source} = $src;
276 3 $STATS_H{impl_exception} = '';
277 3 return $src;
278 }
279  
280 # ($max_dev, $avg_dev) = _calculate_deviation($coderef, $xdata, $ydata);
281 1 ▶sub _calculate_deviation {
Subroutine _calculate_deviation: called CC=7 SCAR=20.3
282 1 my ($coderef, $xdata, $ydata) = @_;
283 1 my $max_off = 1.0;
284 1 my $max_off_datum = 0.0;
285 1 my $tot_off = 0.0;
286 1 ▶ for (my $i = 0; defined($xdata->[$i]); $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $xdata->[$i]) 10 1 11
287 10 my $x = $xdata->[$i];
288 10 my $y = eval { $coderef->($x); };
289 10 ▶ unless(defined($y)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $y) 0 10 10
290 0 $STATS_H{deviation_exception} = $@;
291 0 $STATS_H{deviation_exception_datum} = $x;
292 0 die "caught exception calculating deviations";
293 }
294  
295 10 my $observed_y = $ydata->[$i];
296 10 ▶ if ($observed_y && $y) {
Branch: 1 branch
BranchTrueFalseTotal
if ($observed_y and $y) { } 10 0 10
Condition33%1/3
$observed_y and $y
!ll&&!rl&&r
0010
MC/DC0%0/2
$observed_y and $y
$observed_y $y
Truth table33%1/3
A and B
A= $observed_yB= $y
ABresult
0X0
100
111
297 10 ▶ my $deviation = $y > $observed_y ? $y / $observed_y : $observed_y / $y;
Branch: 1 branch
BranchTrueFalseTotal
$y > $observed_y ? : 5 5 10
298 10 my $dev_mag = abs($deviation - 1.0);
299 10 my $max_mag = abs($max_off - 1.0);
300 # print "x=$x\ty=$y\toy=$observed_y\tdev_mag=$dev_mag\tmax_mag=$max_mag\n";
301 10 ▶ ($max_off, $max_off_datum) = ($deviation, $x) if ($dev_mag > $max_mag);
Branch: 1 branch
BranchTrueFalseTotal
if $dev_mag > $max_mag 2 8 10
302 10 $tot_off += $deviation;
303 } else {
304 0 $tot_off += 1.0;
305 }
306 }
307 1 $STATS_H{deviation_max_offset_datum} = $max_off_datum;
308 1 return ($max_off, $tot_off / @$xdata);
309 }
310  
311  
312 5 1;
313  
314 =head1 NAME
315  
316 Algorithm::CurveFit::Simple - Convenience wrapper around Algorithm::CurveFit
317  
318 =head1 SYNOPSIS
319  
320 use Algorithm::CurveFit::Simple qw(fit);
321  
322 my ($max_dev, $avg_dev, $src) = fit(xdata => \@xdata, ydata => \@ydata, ..options..);
323  
324 # Alternatively pass xdata and ydata together:
325 my ($max_dev, $avg_dev, $src) = fit(xydata => [\@xdata, \@ydata], ..options..);
326  
327 # Alternatively pass data as array of [x,y] pairs:
328 my ($max_dev, $avg_dev, $src) = fit(xydata => [[1, 2], [2, 5], [3, 10]], ..options..);
329  
330 =head1 DESCRIPTION
331  
332 This is a convenience wrapper around L<Algorithm::CurveFit>. Given a body of (x, y) data points, it will generate a polynomial formula f(x) = y which fits that data.
333  
334 Its main differences from L<Algorithm::CurveFit> are:
335  
336 =over 4
337  
338 =item * It synthesizes the initial formula for you,
339  
340 =item * It allows for a time limit on the curve-fit instead of an iteration count,
341  
342 =item * It implements the formula as source code (or as a perl coderef, if you want to use the formula immediately in your program).
343  
344 =back
345  
346 Additionally it returns a maximum deviation and average deviation of the formula vs the xydata, which is more useful (to me, at least) than L<Algorithm::CurveFit>'s square residual output. Closer to 1.0 indicates a better fit. Play with C<terms =E<gt> #> until these deviations are as close to 1.0 as possible, and beware overfitting.
347  
348 =head1 SUBROUTINES
349  
350 There is only one public subroutine, C<fit()>. It B<must> be given either C<xydata> or C<xdata> and C<ydata> parameters. All other paramters are optional.
351  
352 It returns three values: A maximum deviation, the average deviation and the formula implementation.
353  
354 =head2 Options
355  
356 =over 4
357  
358 =item C<fit(xdata =E<gt> \@xdata, ydata =E<gt> \@ydata)>
359  
360 The data points the formula will fit. Same as L<Algorithm::CurveFit> parameters of the same name.
361  
362 =item C<fit(xydata =E<gt> [[1, 2, 3, 4], [10, 17, 26, 37]])>
363  
364 =item C<fit(xydata =E<gt> [[1, 10], [2, 17], [3, 26], [4, 37]])>
365  
366 A more convenient way to provide data points. C<fit()> will try to detect how the data points are organized -- list of x and list of y, or list of [x,y].
367  
368 =item C<fit(terms =E<gt> 3)>
369  
370 Sets the order of the polynomial, which will be of the form C<k + a*x + b*x**2 + c*x**3 ...>. The default is 3 and the limit is 10.
371  
372 There is no need to specify initial C<k>. It will be calculated from C<xydata>.
373  
374 =item C<fit(time_limit =E<gt> 3)>
375  
376 If a time limit is given (in seconds), C<fit()> will spend no more than that long trying to fit the data. It may return in much less time. The default is 3.
377  
378 =item C<fit(iterations =E<gt> 10000)>
379  
380 If an iteration count is given, C<fit()> will ignore any time limit and iterate up to C<iterations> times trying to fit the curve. Same as L<Algorithm::CurveFit> parameter of the same name.
381  
382 =item C<fit(inv =E<gt> 1)>
383  
384 Setting C<inv> inverts the sense of the fit. Instead of C<f(x) = y> the formula will fit C<f(y) = x>.
385  
386 =item C<fit(impl_lang =E<gt> "perl")>
387  
388 Sets the programming language in which the formula will be implemented. Currently supported languages are C<"C">, C<"coderef"> and the default, C<"perl">.
389  
390 When C<impl_lang =E<gt> "coderef"> is specified, a code reference is returned instead which may be used immediately by your perl script:
391  
392 my($max_dev, $avg_dev, $x2y) = fit(xydata => \@xy, impl_lang => "coderef");
393  
394 my $y = $x2y->(42);
395  
396 More implementation languages will be supported in the future.
397  
398 =item C<fit(impl_name =E<gt> "x2y")>
399  
400 Sets the name of the function implementing the formula. The default is C<"x2y">. Has no effect when used with C<impl_lang =E<gt> "coderef")>.
401  
402 my($max_dev, $avg_dev, $src) = fit(xydata => \@xy, impl_name => "converto");
403  
404 print "$src\n";
405  
406 sub converto {
407 my($x) = @_;
408 my $y = -5340.93059104837 + 249.23009968947 * $x + -3.87745746448 * $x**2 + 0.02114780993 * $x**3;
409 return $y;
410 }
411  
412 =item C<fit(bounds_check =E<gt> 1)>
413  
414 When set, the implementation will include logic for checking whether the input is out-of-bounds, per the highest and lowest x points in the data used to fit the formula. For implementation languages which support exceptions, an exception will be thrown. For others (like C), C<-1.0> will be returned to indicate the error.
415  
416 For instance, if the highest x in C<$xydata> is 83.0 and the lowest x is 60.0:
417  
418 my($max_dev, $avg_dev, $src) = fit(xydata => \@xy, bounds_check => 1);
419  
420 print "$src\n";
421  
422 sub x2y {
423 my($x) = @_;
424 die "x out of bounds (high)" if ($x > 83.80000000000);
425 die "x out of bounds (low)" if ($x < 60.80000000000);
426 my $y = -5340.93059104837 + 249.23009968947 * $x + -3.87745746448 * $x**2 + 0.02114780993 * $x**3;
427 return $y;
428 }
429  
430 =item C<fit(round_result =E<gt> 1)>
431  
432 When set, the implementation will round the output to the nearest whole number. When the implementation language is C<"C"> this adds an C<#include E<lt>math.hE<gt>> directive to the source code, which will have to be compiled against libm -- see C<man 3 round>.
433  
434 my($max_dev, $avg_dev, $src) = fit(xydata => \@xy, round_result => 1);
435  
436 print "$src\n";
437  
438 sub x2y {
439 my($x) = @_;
440 my $y = -5340.93059104837 + 249.23009968947 * $x + -3.87745746448 * $x**2 + 0.02114780993 * $x**3;
441 $y = int($y + 0.5);
442 return $y;
443 }
444  
445 =item C<fit(suppress_includes =E<gt> 1)>
446  
447 When set and C<lang_impl =E<gt> "C">, any C<#include> directives which the implementation might need will be suppressed.
448  
449 =back
450  
451 =head1 VARIABLES
452  
453 The class variable C<%STATS_H> contains various intermediate values which might be helpful. For instance, C<$STATS_H{deviation_max_offset_datum}> contains the x data point which corresponds to the maximum deviation returned.
454  
455 The contents of C<%STATS_H> is subject to change and might not be fully documented in future versions. The current fields are:
456  
457 =over 4
458  
459 =item C<deviation_max_offset_datum>: The x data point corresponding with returned maximum deviation.
460  
461 =item C<fit_calib_parar>: Arrayref of formula parameters as returned by L<Algorithm::CurveFit> after a short fitting attempt used for timing calibration.
462  
463 =item C<fit_calib_time>: The number of seconds L<Algorithm::CurveFit> spent in the calibration run.
464  
465 =item C<fit_iter>: The iterations parameter passed to L<Algorithm::CurveFit>.
466  
467 =item C<fit_parar>: Arrayref of formula parameters as returned by L<Algorithm::CurveFit>.
468  
469 =item C<fit_time>: The number of seconds L<Algorithm::CurveFit> actually spent fitting the formula.
470  
471 =item C<impl_exception>: The exception thrown when the implementation was used to calculate the deviations, or the empty string if none.
472  
473 =item C<impl_formula>: The formula part of the implementation.
474  
475 =item C<impl_source>: The implementation source string.
476  
477 =item C<iter_mode>: One of C<"time"> or C<"iter">, indicating whether a time limit was used or an iteration count.
478  
479 =item C<xdata>: Arrayref of x data points as passed to L<Algorithm::CurveFit>.
480  
481 =item C<ydata>: Arrayref of y data points as passed to L<Algorithm::CurveFit>.
482  
483 =back
484  
485 =head1 CAVEATS
486  
487 =over 4
488  
489 =item * Only simple polynomial functions are supported. Sometimes you need something else. Use L<Algorithm::CurveFit> for such cases.
490  
491 =item * If C<xydata> is very large, iterating over it to calculate deviances can take more time than permitted by C<time_limit>.
492  
493 =item * The dangers of overfitting are real! L<https://en.wikipedia.org/wiki/Overfitting>
494  
495 =item * Using too many terms can dramatically reduce the accuracy of the fitted formula.
496  
497 =item * Sometimes calling L<Algorithm::CurveFit> with a ten-term polynomial causes it to hang.
498  
499 =back
500  
501 =head1 TO DO
502  
503 =over 4
504  
505 =item * Support more programming languages for formula implementation: R, MATLAB, python
506  
507 =item * Calculate the actual term sigfigs and set precision appropriately in the formula implementation instead of just "%.11f".
508  
509 =item * Support trying a range of terms and returning whatever gives the best fit.
510  
511 =item * Support piecewise output formulas.
512  
513 =item * Work around L<Algorithm::CurveFit>'s occasional hang problem when using ten-term polynomials.
514  
515 =back
516  
517 =head1 SEE ALSO
518  
519 L<Algorithm::CurveFit>
520  
521 L<curvefit>
522  
523 =cut
↑ Summary