| 1 | =head1 NAME | ||
| 2 | |||
| 3 | PDL::Fit::LM -- Levenberg-Marquardt fitting routine for PDL | ||
| 4 | |||
| 5 | =head1 DESCRIPTION | ||
| 6 | |||
| 7 | This module provides fitting functions for PDL. Currently, only | ||
| 8 | Levenberg-Marquardt fitting is implemented. Other procedures should | ||
| 9 | be added as required. For a fairly concise overview on fitting | ||
| 10 | see Numerical Recipes, chapter 15 "Modeling of data". | ||
| 11 | |||
| 12 | =head1 SYNOPSIS | ||
| 13 | |||
| 14 | use PDL::Fit::LM; | ||
| 15 | $ym = lmfit $x, $y, $sigma, \&expfunc, $initp, {Maxiter => 300}; | ||
| 16 | |||
| 17 | =head1 FUNCTIONS | ||
| 18 | |||
| 19 | =cut | ||
| 20 | |||
| 21 | package PDL::Fit::LM; | ||
| 22 | |||
| 23 | @EXPORT_OK = qw( lmfit tlmfit); | ||
| 24 | %EXPORT_TAGS = (Func=>[@EXPORT_OK]); | ||
| 25 | |||
| 26 | use PDL::Core; | ||
| 27 | use PDL::Exporter; | ||
| 28 | use PDL::Options; | ||
| 29 | use PDL::Slatec; # for matrix inversion | ||
| 30 | |||
| 31 | @ISA = qw( PDL::Exporter ); | ||
| 32 | |||
| 33 | =head2 lmfit | ||
| 34 | |||
| 35 | =for ref | ||
| 36 | |||
| 37 | Levenberg-Marquardt fitting of a user supplied model function | ||
| 38 | |||
| 39 | =for example | ||
| 40 | |||
| 41 | ($ym,$finalp,$covar,$iters) = | ||
| 42 | lmfit $x, $y, $sigma, \&expfunc, $initp, {Maxiter => 300, Eps => 1e-3}; | ||
| 43 | |||
| 44 | where $x is the independent variable and $y the value of the dependent variable at each $x, $sigma is the estimate of the uncertainty (i.e., standard deviation) of $y at each data point, the fourth argument is a subroutine reference (see below), and $initp the initial values of the parameters to be adjusted. | ||
| 45 | |||
| 46 | Options: | ||
| 47 | |||
| 48 | =for options | ||
| 49 | |||
| 50 | Maxiter: maximum number of iterations before giving up | ||
| 51 | Eps: convergence criterion for fit; success when normalized change | ||
| 52 | in chisquare smaller than Eps | ||
| 53 | |||
| 54 | The user supplied sub routine reference should accept 4 arguments | ||
| 55 | |||
| 56 | =over 4 | ||
| 57 | |||
| 58 | =item * | ||
| 59 | |||
| 60 | a vector of independent values $x | ||
| 61 | |||
| 62 | =item * | ||
| 63 | |||
| 64 | a vector of fitting parameters | ||
| 65 | |||
| 66 | =item * | ||
| 67 | |||
| 68 | a vector of dependent variables that will be assigned upon return | ||
| 69 | |||
| 70 | =item * | ||
| 71 | |||
| 72 | a matrix of partial derivatives with respect to the fitting parameters | ||
| 73 | that will be assigned upon return | ||
| 74 | |||
| 75 | =back | ||
| 76 | |||
| 77 | As an example take this definition of a single exponential with | ||
| 78 | 3 parameters (width, amplitude, offset): | ||
| 79 | |||
| 80 | sub expdec { | ||
| 81 | my ($x,$par,$ym,$dyda) = @_; | ||
| 82 | my ($a,$b,$c) = map {$par->slice("($_)")} (0..2); | ||
| 83 | my $arg = $x/$a; | ||
| 84 | my $ex = exp($arg); | ||
| 85 | $ym .= $b*$ex+$c; | ||
| 86 | my (@dy) = map {$dyda->slice(",($_)")} (0..2); | ||
| 87 | $dy[0] .= -$b*$ex*$arg/$a; | ||
| 88 | $dy[1] .= $ex; | ||
| 89 | $dy[2] .= 1; | ||
| 90 | } | ||
| 91 | |||
| 92 | Note usage of the C<.=> operator for assignment | ||
| 93 | |||
| 94 | In scalar context returns a vector of the fitted dependent | ||
| 95 | variable. In list context returns fitted y-values, vector | ||
| 96 | of fitted parameters, an estimate of the covariance matrix | ||
| 97 | (as an indicator of goodness of fit) and number of iterations | ||
| 98 | performed. | ||
| 99 | |||
| 100 | =cut | ||
| 101 | |||
| 102 | sub PDL::lmfit { | ||
| 103 | my ($x,$y,$sig,$func,$a,$opt) = @_; # not using $ia right now | ||
| 104 | $opt = {iparse( { Maxiter => 200, | ||
| 105 | Eps => 1e-4}, ifhref($opt))}; | ||
| 106 | my ($maxiter,$eps) = map {$opt->{$_}} qw/Maxiter Eps/; | ||
| 107 | # initialize some variables | ||
| 108 | my ($isig2,$chisq) = (1/($sig*$sig),0); #$isig2="inverse of sigma squared" | ||
| 109 | my ($ym,$al,$cov,$bet,$oldbet,$olda,$oldal,$ochisq,$di,$pivt,$info) = | ||
| 110 | map {null} (0..10); | ||
| 111 | my ($aldiag,$codiag); # the diagonals for later updating | ||
| 112 | # this will break threading | ||
| 113 | my $dyda = zeroes($x->type,$x->getdim(0),$a->getdim(0)); | ||
| 114 | my $alv = zeroes($x->type,$x->getdim(0),$a->getdim(0),$a->getdim(0)); | ||
| 115 | my ($iter,$lambda) = (0,0.001); | ||
| 116 | |||
| 117 | do { | ||
| 118 | if ($iter>0) { | ||
| 119 | $cov .= $al; | ||
| 120 | # local $PDL::debug = 1; | ||
| 121 | $codiag .= $aldiag*(1+$lambda); | ||
| 122 | gefa $cov, $pivt, $info; # gefa + gesl = solution by Gaussian elem. | ||
| 123 | gesl $cov, $pivt, $bet, 0; # solution returned in $bet | ||
| 124 | # lusd($cov,$bet,$da); | ||
| 125 | # print "changing by $da\n"; | ||
| 126 | $a += $bet; # what we used to call $da is now $bet | ||
| 127 | } | ||
| 128 | &$func($x,$a,$ym,$dyda); | ||
| 129 | $chisq = ($y-$ym)*($y-$ym); | ||
| 130 | $chisq *= $isig2; | ||
| 131 | $chisq = $chisq->sumover; # calculate chi^2 | ||
| 132 | $dyda->xchg(0,1)->outer($dyda->xchg(0,1),$alv->mv(0,2)); | ||
| 133 | $alv *= $isig2; | ||
| 134 | $alv->sumover($al); # calculate alpha | ||
| 135 | (($y-$ym)*$isig2*$dyda)->sumover($bet); # calculate beta | ||
| 136 | if ($iter == 0) {$olda .= $a; $ochisq .= $chisq; $oldbet .= $bet; | ||
| 137 | $oldal .= $al; $aldiag = $al->diagonal(0,1); | ||
| 138 | $cov .= $al; $codiag = $cov->diagonal(0,1)} | ||
| 139 | $di .= abs($chisq-$ochisq); | ||
| 140 | # print "$iter: chisq, lambda, dlambda: $chisq, $lambda,",$di/$chisq,"\n"; | ||
| 141 | if ($chisq < $ochisq) { | ||
| 142 | $lambda *= 0.1; | ||
| 143 | $ochisq .= $chisq; | ||
| 144 | $olda .= $a; | ||
| 145 | $oldbet .= $bet; | ||
| 146 | $oldal .= $al; | ||
| 147 | } else { | ||
| 148 | $lambda *= 10; | ||
| 149 | $chisq .= $ochisq; | ||
| 150 | $a .= $olda; # go back to previous a | ||
| 151 | $bet .= $oldbet; # and beta | ||
| 152 | $al .= $oldal; # and alpha | ||
| 153 | } | ||
| 154 | } while ($iter++==0 || $iter < $maxiter && $di/$chisq > $eps); | ||
| 155 | barf "iteration did not converge" if $iter >= $maxiter && $di/$chisq > $eps; | ||
| 156 | # return inv $al as estimate of covariance matrix | ||
| 157 | return wantarray ? ($ym,$a,matinv($al),$iter) : $ym; | ||
| 158 | } | ||
| 159 | *lmfit = \&PDL::lmfit; | ||
| 160 | |||
| 161 | =pod | ||
| 162 | |||
| 163 | An extended example script that uses lmfit is included below. | ||
| 164 | This nice example was provided by John Gehman and should | ||
| 165 | help you to master the initial hurdles. It can also be found in | ||
| 166 | the F<Example/Fit> directory. | ||
| 167 | |||
| 168 | use PDL; | ||
| 169 | use PDL::Math; | ||
| 170 | use PDL::Fit::LM; | ||
| 171 | use strict; | ||
| 172 | |||
| 173 | |||
| 174 | ### fit using pdl's lmfit (Marquardt-Levenberg non-linear least squares fitting) | ||
| 175 | ### | ||
| 176 | ### `lmfit' Syntax: | ||
| 177 | ### | ||
| 178 | ### ($ym,$finalp,$covar,$iters) | ||
| 179 | ### = lmfit $x, $y, $sigma, \&fn, $initp, {Maxiter => 300, Eps => 1e-3}; | ||
| 180 | ### | ||
| 181 | ### Explanation of variables | ||
| 182 | ### | ||
| 183 | ### OUTPUT | ||
| 184 | ### $ym = pdl of fitted values | ||
| 185 | ### $finalp = pdl of parameters | ||
| 186 | ### $covar = covariance matrix | ||
| 187 | ### $iters = number of iterations actually used | ||
| 188 | ### | ||
| 189 | ### INPUT | ||
| 190 | ### $x = x data | ||
| 191 | ### $y = y data | ||
| 192 | ### $sigma = piddle of y-uncertainties for each value of $y (can be set to scalar 1 for equal weighting) | ||
| 193 | ### \&fn = reference to function provided by user (more on this below) | ||
| 194 | ### $initp = initial values for floating parameters | ||
| 195 | ### (needs to be explicitly set prior to use of lmfit) | ||
| 196 | ### Maxiter = maximum iterations | ||
| 197 | ### Eps = convergence criterion (maximum normalized change in Chi Sq.) | ||
| 198 | |||
| 199 | ### Example: | ||
| 200 | # make up experimental data: | ||
| 201 | my $xdata = pdl sequence 5; | ||
| 202 | my $ydata = pdl [1.1,1.9,3.05,4,4.9]; | ||
| 203 | |||
| 204 | # set initial prameters in a pdl (order in accord with fit function below) | ||
| 205 | my $initp = pdl [0,1]; | ||
| 206 | |||
| 207 | # Weight all y data equally (else specify different uncertainties in a pdl) | ||
| 208 | my $sigma = 1; | ||
| 209 | |||
| 210 | # Use lmfit. Fourth input argument is reference to user-defined | ||
| 211 | # subroutine ( here \&linefit ) detailed below. | ||
| 212 | my ($yf,$pf,$cf,$if) = lmfit $xdata, $ydata, $sigma, \&linefit, $initp; | ||
| 213 | |||
| 214 | # Note output | ||
| 215 | print "\nXDATA\n$xdata\nY DATA\n$ydata\n\nY DATA FIT\n$yf\n\n"; | ||
| 216 | print "Slope and Intercept\n$pf\n\nCOVARIANCE MATRIX\n$cf\n\n"; | ||
| 217 | print "NUMBER ITERATIONS\n$if\n\n"; | ||
| 218 | |||
| 219 | |||
| 220 | # simple example of user defined fit function. Guidelines included on | ||
| 221 | # how to write your own function subroutine. | ||
| 222 | sub linefit { | ||
| 223 | |||
| 224 | # leave this line as is | ||
| 225 | my ($x,$par,$ym,$dyda) = @_; | ||
| 226 | |||
| 227 | # $m and $b are fit parameters, internal to this function | ||
| 228 | # call them whatever make sense to you, but replace (0..1) | ||
| 229 | # with (0..x) where x is equal to your number of fit parameters | ||
| 230 | # minus 1 | ||
| 231 | my ($m,$b) = map { $par->slice("($_)") } (0..1); | ||
| 232 | |||
| 233 | # Write function with dependent variable $ym, | ||
| 234 | # independent variable $x, and fit parameters as specified above. | ||
| 235 | # Use the .= (dot equals) assignment operator to express the equality | ||
| 236 | # (not just a plain equals) | ||
| 237 | $ym .= $m * $x + $b; | ||
| 238 | |||
| 239 | # Edit only the (0..1) part to (0..x) as above | ||
| 240 | my (@dy) = map {$dyda -> slice(",($_)") } (0..1); | ||
| 241 | |||
| 242 | # Partial derivative of the function with respect to first | ||
| 243 | # fit parameter ($m in this case). Again, note .= assignment | ||
| 244 | # operator (not just "equals") | ||
| 245 | $dy[0] .= $x; | ||
| 246 | |||
| 247 | # Partial derivative of the function with respect to next | ||
| 248 | # fit parameter ($b in this case) | ||
| 249 | $dy[1] .= 1; | ||
| 250 | |||
| 251 | # Add $dy[ ] .= () lines as necessary to supply | ||
| 252 | # partial derivatives for all floating parameters. | ||
| 253 | } | ||
| 254 | |||
| 255 | =cut | ||
| 256 | |||
| 257 | # the OtherPar is the sub routine ref | ||
| 258 | |||
| 259 | =head2 tlmfit | ||
| 260 | |||
| 261 | =for ref | ||
| 262 | |||
| 263 | threaded version of Levenberg-Marquardt fitting routine mfit | ||
| 264 | |||
| 265 | =for example | ||
| 266 | |||
| 267 | tlmfit $x, $y, float(1)->dummy(0), $na, float(200), float(1e-4), | ||
| 268 | $ym=null, $afit=null, \&expdec; | ||
| 269 | |||
| 270 | |||
| 271 | =for sig | ||
| 272 | |||
| 273 | Signature: tlmfit(x(n);y(n);sigma(n);initp(m);iter();eps();[o] ym(n);[o] finalp(m); | ||
| 274 | OtherPar => subref) | ||
| 275 | |||
| 276 | a threaded version of C<lmfit> by using perl threading. Direct | ||
| 277 | threading in C<lmfit> seemed difficult since we have an if condition | ||
| 278 | in the iteration. In principle that can be worked around by | ||
| 279 | using C<where> but .... Send a threaded C<lmfit> version if | ||
| 280 | you work it out! | ||
| 281 | |||
| 282 | Since we are using perl threading here speed is not really great | ||
| 283 | but it is just convenient to have a threaded version for many | ||
| 284 | applications (no explicit for-loops required, etc). Suffers from | ||
| 285 | some of the current limitations of perl level threading. | ||
| 286 | |||
| 287 | =cut | ||
| 288 | |||
| 289 | |||
| 290 | thread_define 'tlmfit(x(n);y(n);sigma(n);initp(m);iter();eps();[o] ym(n);[o] finalp(m)), | ||
| 291 | NOtherPars => 1', | ||
| 292 | over { | ||
| 293 | $_[7] .= $_[3]; # copy our parameter guess into the output | ||
| 294 | $_[6] .= PDL::lmfit $_[0],$_[1],$_[2],$_[8],$_[7],{Maxiter => $_[4], | ||
| 295 | Eps => $_[5]}; | ||
| 296 | }; | ||
| 297 | |||
| 298 | 1; | ||
| 299 | |||
| 300 | =head1 BUGS | ||
| 301 | |||
| 302 | Not known yet. | ||
| 303 | |||
| 304 | =head1 AUTHOR | ||
| 305 | |||
| 306 | This file copyright (C) 1999, Christian Soeller | ||
| 307 | (c.soeller@auckland.ac.nz). All rights reserved. There is no | ||
| 308 | warranty. You are allowed to redistribute this software documentation | ||
| 309 | under certain conditions. For details, see the file COPYING in the PDL | ||
| 310 | distribution. If this file is separated from the PDL distribution, the | ||
| 311 | copyright notice should be included in the file. | ||
| 312 | |||
| 313 | =cut | ||
| 314 | |||
| 315 | # return true | ||
| 316 | 1; |