| 1 | # | ||
| 2 | # GENERATED WITH PDL::PP from levmar.pd! Don't modify! | ||
| 3 | # | ||
| 4 | package PDL::Fit::Levmar; | ||
| 5 | |||
| 6 | 9 | our @EXPORT_OK = qw(levmar levmar_report levmar_chkjac levmar_der_lb levmar_der_ub levmar_der_ levmar_der_lb_ub levmar_diff_lb levmar_diff_ub levmar_diff_ levmar_diff_lb_ub _levmar_chkjac _levmar_chkjac_no_t ); | |
| 7 | 9 | our %EXPORT_TAGS = (Func=>\@EXPORT_OK); | |
| 8 | |||
| 9 | 9 | ▶ | use PDL::Core; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 10 | 9 | ▶ | use PDL::Exporter; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 11 | 9 | ▶ | use DynaLoader; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 12 | |||
| 13 | |||
| 14 | 9 | our $VERSION = '0.0111'; | |
| 15 | 9 | our @ISA = ( 'PDL::Exporter','DynaLoader' ); | |
| 16 | 9 | push @PDL::Core::PP, __PACKAGE__; | |
| 17 | 9 | bootstrap PDL::Fit::Levmar $VERSION; | |
| 18 | |||
| 19 | |||
| 20 | |||
| 21 | |||
| 22 | |||
| 23 | |||
| 24 | |||
| 25 | |||
| 26 | #line 14 "levmar.pd" | ||
| 27 | |||
| 28 | =head1 NAME | ||
| 29 | |||
| 30 | PDL::Fit::Levmar - Levenberg-Marquardt fit/optimization routines | ||
| 31 | |||
| 32 | =head1 DESCRIPTION | ||
| 33 | |||
| 34 | Levenberg-Marquardt routines for least-squares fit to | ||
| 35 | functions non-linear in fit parameters. | ||
| 36 | |||
| 37 | This module provides a L<PDL> interface to the non-linear fitting | ||
| 38 | library levmar 2.6 (written in C). Levmar is | ||
| 39 | L<broadcast|/example--6> aware, provides support for analytic | ||
| 40 | or finite difference derivatives (in case no analytic | ||
| 41 | derivatives are supplied), L<linear|/A> and/or L<box|/UB> | ||
| 42 | and/or L<inequality|/C> | ||
| 43 | constraints (with L<parameter fixing|/FIX> as a special | ||
| 44 | case) and pure single or double precision computation. The | ||
| 45 | routines are re-entrant, so they can be used in | ||
| 46 | multi-threaded applications (not tested!). Levmar is suited | ||
| 47 | both for data fitting and for optimization problems. | ||
| 48 | |||
| 49 | The source code for the C levmar library is included in this | ||
| 50 | distribution. However, linearly-constrained fitting requires | ||
| 51 | that C<PDL::Fit::Levmar> be built with support for B<lapack> | ||
| 52 | and B<blas> libraries. See the files F<INSTALL> and | ||
| 53 | F<Makefile.PL>, for more information. If | ||
| 54 | C<PDL::Fit::Levmar> is built without support for C<lapack>, | ||
| 55 | the fitting options C<A>, C<B>, C<C>, C<D>, and C<FIX> may | ||
| 56 | not be used. All other options, including C<FIXB>, do not | ||
| 57 | require C<lapack>. | ||
| 58 | |||
| 59 | User supplied fit functions can be written in perl code that | ||
| 60 | takes pdls as arguments, or, for efficiency, in in a simple | ||
| 61 | function description language (C<lpp>), which is rapidly and | ||
| 62 | transparently translated to C, compiled, and dynamically | ||
| 63 | linked. Fit functions may also be written in pure C. If C | ||
| 64 | or C<lpp> fit functions are used, the entire fitting | ||
| 65 | procedure is done in pure compiled C. The compilation and | ||
| 66 | linking is done only the first time the function is defined. | ||
| 67 | |||
| 68 | There is a document distributed with this module | ||
| 69 | F<./doc/levmar.pdf> by the author of liblevmar describing | ||
| 70 | the fit algorithms. Additional information on liblevmar is available at | ||
| 71 | L<http://www.ics.forth.gr/~lourakis/levmar/> | ||
| 72 | |||
| 73 | Don't confuse this module with, but see also, L<PDL::Fit::LM>. | ||
| 74 | |||
| 75 | =head1 SYNOPSIS | ||
| 76 | |||
| 77 | use PDL::Fit::Levmar; | ||
| 78 | $result_hash = levmar($params,$x,$t, FUNC => ' | ||
| 79 | function somename | ||
| 80 | x = p0 * exp(-t*t * p1);'); | ||
| 81 | print levmar_report($result_hash); | ||
| 82 | |||
| 83 | =head1 EXAMPLES | ||
| 84 | |||
| 85 | A number of examples of invocations of C<levmar> follow. The test | ||
| 86 | directory C<./t> in the module distribution contains many more examples. | ||
| 87 | The following seven examples are included as stand-alone scripts in the | ||
| 88 | ./examples/ directory. Some of the necessary lines are not repeated in | ||
| 89 | each example below. | ||
| 90 | |||
| 91 | =over 3 | ||
| 92 | |||
| 93 | =item example--1 | ||
| 94 | |||
| 95 | In this example we fill co-ordinate $t and ordinate $x arrays | ||
| 96 | with 100 pairs of sample data. Then we call the fit routine | ||
| 97 | with initial guesses of the parameters. | ||
| 98 | |||
| 99 | use PDL::LiteF; | ||
| 100 | use PDL::Fit::Levmar; | ||
| 101 | use PDL::NiceSlice; | ||
| 102 | |||
| 103 | $n = 100; | ||
| 104 | $t = 10 * (sequence($n)/$n -1/2); | ||
| 105 | $x = 3 * exp(-$t*$t * .3 ); | ||
| 106 | $p = pdl [ 1, 1 ]; # initial parameter guesses | ||
| 107 | |||
| 108 | $h = levmar($p,$x,$t, FUNC => | ||
| 109 | ' function | ||
| 110 | x = p0 * exp( -t*t * p1); | ||
| 111 | '); | ||
| 112 | print levmar_report($h); | ||
| 113 | |||
| 114 | This example gives the output: | ||
| 115 | |||
| 116 | Estimated parameters: [ 3 0.3] | ||
| 117 | Covariance: | ||
| 118 | [ | ||
| 119 | [5.3772081e-25 7.1703376e-26] | ||
| 120 | [7.1703376e-26 2.8682471e-26] | ||
| 121 | ] | ||
| 122 | |||
| 123 | ||e||_2 at initial parameters = 125.201 | ||
| 124 | Errors at estimated parameters: | ||
| 125 | ||e||_2 = 8.03854e-22 | ||
| 126 | ||J^T e||_inf = 2.69892e-05 | ||
| 127 | ||Dp||_2 = 3.9274e-15 | ||
| 128 | \mu/max[J^T J]_ii ] = 1.37223e-05 | ||
| 129 | number of iterations = 15 | ||
| 130 | reason for termination: = stopped by small ||e||_2 | ||
| 131 | number of function evaluations = 20 | ||
| 132 | number of jacobian evaluations = 2 | ||
| 133 | |||
| 134 | In the example above and all following examples, it is necessary | ||
| 135 | to include the three C<use> statements at the top of the file. | ||
| 136 | The fit function in this example is in C<lpp> code. | ||
| 137 | The parameter pdl $p is the input parameters (guesses) | ||
| 138 | levmar returns a hash with several elements including a | ||
| 139 | plain text report of the fit, which we chose to print. | ||
| 140 | |||
| 141 | The interface is flexible-- we could have also called levmar like this | ||
| 142 | |||
| 143 | $h = levmar($p,$x,$t, ' function | ||
| 144 | x = p0 * exp( -t*t * p1); | ||
| 145 | '); | ||
| 146 | |||
| 147 | or like this | ||
| 148 | |||
| 149 | $h = levmar(P =>$p, X => $x, T=> $t, FUNC => ' function | ||
| 150 | x = p0 * exp( -t*t * p1); | ||
| 151 | '); | ||
| 152 | |||
| 153 | After the fit, the input parameters $p are left | ||
| 154 | unchanged. The output hash $h contains, among other things, | ||
| 155 | the optimized parameters in $h->{P}. | ||
| 156 | |||
| 157 | =item example--2 | ||
| 158 | |||
| 159 | Next, we do the same fit, but with a perl/PDL fit function. | ||
| 160 | |||
| 161 | $h = levmar($p,$x,$t, FUNC => sub { | ||
| 162 | my ($p,$x,$t) = @_; | ||
| 163 | my ($p0,$p1) = list $p; | ||
| 164 | $x .= $p0 * exp(-$t*$t * $p1); | ||
| 165 | }); | ||
| 166 | |||
| 167 | Using perl code (second example) results in slower execution | ||
| 168 | than using pure C (first example). How much slower depends | ||
| 169 | on the problem (see L</IMPLEMENTATION> below). See also the | ||
| 170 | section on L<perl subroutines|/Perl_Subroutines>. | ||
| 171 | |||
| 172 | =item example--3 | ||
| 173 | |||
| 174 | Next, we solve the same problem using a C fit routine. | ||
| 175 | |||
| 176 | levmar($p,$x,$t, FUNC => ' | ||
| 177 | #include <math.h> | ||
| 178 | void gaussian(FLOAT *p, FLOAT *x, int m, int n, FLOAT *t) | ||
| 179 | { | ||
| 180 | int i; | ||
| 181 | for(i=0; i<n; ++i) | ||
| 182 | x[i] = p[0] * exp( -t[i]*t[i] * p[1]); | ||
| 183 | } | ||
| 184 | '); | ||
| 185 | |||
| 186 | The macro C<FLOAT> is used rather than float or double because | ||
| 187 | the C code will be used for both single and double precision | ||
| 188 | routines. ( The code is automatically compiled twice; once | ||
| 189 | with C<FLOAT> expanded to double and once expanded to float) | ||
| 190 | The correct version is used automatically depending on the | ||
| 191 | type of pdls you give levmar. | ||
| 192 | |||
| 193 | =item example--4 | ||
| 194 | |||
| 195 | We supply an analytic derivative ( analytic jacobian). | ||
| 196 | |||
| 197 | $st = ' | ||
| 198 | function | ||
| 199 | x = p0 * exp( -t*t * p1); | ||
| 200 | |||
| 201 | jacobian | ||
| 202 | FLOAT ex, arg; | ||
| 203 | loop | ||
| 204 | arg = -t*t * p1; | ||
| 205 | ex = exp(arg); | ||
| 206 | d0 = ex; | ||
| 207 | d1 = -p0 * t*t * ex ; | ||
| 208 | |||
| 209 | '; | ||
| 210 | |||
| 211 | $h = levmar($p,$x,$t, FUNC => $st); | ||
| 212 | |||
| 213 | If no jacobian function is supplied, levmar automatically | ||
| 214 | uses numeric difference derivatives. You can also explicitly | ||
| 215 | use numeric derivatives with the option C<DERIVATIVE> | ||
| 216 | C<< => 'numeric' >>. | ||
| 217 | |||
| 218 | Note that the directives C<function> and C<jacobian> begin | ||
| 219 | the function definitions. You can also supply a name if | ||
| 220 | you like, eg. C<function john> and C<jacobian mary>. | ||
| 221 | |||
| 222 | In C<lpp>, the co-ordinate data is always identified by 't', the | ||
| 223 | ordinate data by 'x' in the fit function and by 'dn', with n a | ||
| 224 | number, in the jacobian. The parameters are identified by | ||
| 225 | 'p'. All other identifiers are pure C identifiers and | ||
| 226 | must be defined, as are C<ex> and C<arg> in the example. | ||
| 227 | |||
| 228 | Referring to the example above, if the directive C<loop> appears | ||
| 229 | on a line by itself, code after it is wrapped in a loop over | ||
| 230 | the data; code before it is not. If C<loop> does not appear, | ||
| 231 | then all the code is wrapped in a loop. 'loop' must occur zero | ||
| 232 | or one times in each of the fit and jacobian definitions. | ||
| 233 | For some problems, you will not want a loop at all. In this | ||
| 234 | case the directive C<noloop> is placed after the declarations. | ||
| 235 | |||
| 236 | To see what C<lpp> does, pass the option C<NOCLEAN> C<< => 1 >> to levmar | ||
| 237 | and look at the C source file that is written. | ||
| 238 | |||
| 239 | When defining the derivatives above (d0, d1) etc., you must | ||
| 240 | put the lines in the proper order ( eg, not d1,d0 ). (This | ||
| 241 | is for efficiency, see the generated C code.) | ||
| 242 | |||
| 243 | One final note on this example-- we declared C<ex> and C<arg> to | ||
| 244 | be type C<FLOAT>. Because they are temporary variables, we could | ||
| 245 | have hard coded them to double, in which case both the float | ||
| 246 | and double code versions would have used type double for them. | ||
| 247 | This is ok, because it doesn't cost any storage or cause | ||
| 248 | a memory fault because of incorrect pointer arithmetic. | ||
| 249 | |||
| 250 | =item example--5 | ||
| 251 | |||
| 252 | Here is an example from the liblevmar demo program that shows | ||
| 253 | one more bit of C<lpp> syntax. | ||
| 254 | |||
| 255 | $defst = " | ||
| 256 | function modros | ||
| 257 | noloop | ||
| 258 | x0 = 10 * (p1 -p0*p0); | ||
| 259 | x1 = 1.0 - p0; | ||
| 260 | x2 = 100; | ||
| 261 | jacobian jacmodros | ||
| 262 | noloop | ||
| 263 | d0[0] = -20 * p0; | ||
| 264 | d1[0] = 10; | ||
| 265 | d0[1] = -1; | ||
| 266 | d1[1] = 0; | ||
| 267 | d0[2] = 0; | ||
| 268 | d1[2] = 0; | ||
| 269 | "; | ||
| 270 | $p = pdl [-1.2, 1]; | ||
| 271 | $x = pdl [0,0,0]; | ||
| 272 | $h = levmar( $p,$x, FUNC => $defst ); | ||
| 273 | |||
| 274 | The directive C<noloop> mentioned above has been used, | ||
| 275 | indicating that there are no implied loops in the | ||
| 276 | function. Note that this model function is designed only for | ||
| 277 | $x->nelem == 3. The additional syntax is in the | ||
| 278 | derivatives. Keeping in mind that there is no loop variable, | ||
| 279 | dq[r] means derivative w.r.t q evaluated at x[r]. (This is | ||
| 280 | translated by C<lpp> to d[q+r*m], which is the index into a | ||
| 281 | 1-d array.) | ||
| 282 | |||
| 283 | =item example--6 | ||
| 284 | |||
| 285 | Here is an example that uses implicit broadcasting. We create data | ||
| 286 | from a gaussian function with four different sets of parameters | ||
| 287 | and fit it all in one function call. | ||
| 288 | |||
| 289 | $st = ' | ||
| 290 | function | ||
| 291 | x = p0 * exp( -t*t * p1); | ||
| 292 | '; | ||
| 293 | |||
| 294 | $n = 10; | ||
| 295 | $t = 10 * (sequence($n)/$n -1/2); | ||
| 296 | $x = zeroes($n,4); | ||
| 297 | map { $x(:,$_->[0]) .= $_->[1] * exp(-$t*$t * $_->[2] ) } | ||
| 298 | ( [0,3,.2], [1, 28, .1] , [2,2,.01], [3,3,.3] ); | ||
| 299 | $p = [ 5, 1]; # initial guess | ||
| 300 | $h = levmar($p,$x,$t, FUNC => $st ); | ||
| 301 | print $h->{P} . "\n"; | ||
| 302 | |||
| 303 | [ | ||
| 304 | [ 3 0.2] | ||
| 305 | [ 28 0.1] | ||
| 306 | [ 2 0.01] | ||
| 307 | [ 3 0.3] | ||
| 308 | ] | ||
| 309 | |||
| 310 | =item example--7 | ||
| 311 | |||
| 312 | This example shows how to fit a bivariate Gaussian. Here | ||
| 313 | is the fit function. | ||
| 314 | |||
| 315 | sub gauss2d { | ||
| 316 | my ($p,$xin,$t) = @_; | ||
| 317 | my ($p0,$p1,$p2) = list $p; | ||
| 318 | my $n = $t->nelem; | ||
| 319 | my $t1 = $t(:,*$n); # first coordinate | ||
| 320 | my $t2 = $t(*$n,:); # second coordinate | ||
| 321 | my $x = $xin->splitdim(0,$n); | ||
| 322 | $x .= $p0 * exp( -$p1*$t1*$t1 - $p2*$t2*$t2); | ||
| 323 | } | ||
| 324 | |||
| 325 | We would prefer a function that maps t(n,n) --> x(n,n) (with | ||
| 326 | p viewed as parameters.) But the levmar library expects one | ||
| 327 | dimensional x and t. So we design C<gauss2d> to take | ||
| 328 | ndarrays with these dimensions: C<p(3)>, C<xin(n*n)>, | ||
| 329 | C<t(n)>. For this example, we assume that both the co-ordinate | ||
| 330 | axes run over the same range, so we only need to pass n | ||
| 331 | values for t. The ndarrays t1 and t2 are (virtual) copies of | ||
| 332 | t with dummy dimensions inserted. Each represents | ||
| 333 | co-ordinate values along each of the two axes at each point | ||
| 334 | in the 2-d space, but independent of the position along the | ||
| 335 | other axis. For instance C<t1(i,j) == t(i)> and C<t1(i,j) | ||
| 336 | == t(j)>. We assume that the ndarray xin is a flattened | ||
| 337 | version of the ordinate data, so we split the dimensions in | ||
| 338 | x. Then the entire bi-variate gaussian is calculated with | ||
| 339 | one line that operates on 2-d matrices. Now we create some | ||
| 340 | data, | ||
| 341 | |||
| 342 | my $n = 101; # number of data points along each axis | ||
| 343 | my $scale = 3; # range of co-ordiate data | ||
| 344 | my $t = sequence($n); # co-ordinate data (used for both axes) | ||
| 345 | $t *= $scale/($n-1); | ||
| 346 | $t -= $scale/2; # rescale and shift. | ||
| 347 | my $x = zeroes($n,$n); | ||
| 348 | my $p = pdl [ .5,2,3]; # actual parameters | ||
| 349 | my $xlin = $x->clump(-1); # flatten the x data | ||
| 350 | gauss2d( $p, $xlin, $t->copy); # compute the bivariate gaussian data. | ||
| 351 | |||
| 352 | Now x contains the ordinate data (so does xlin, but in a flattened shape.) | ||
| 353 | Finally, we fit the data with an incorrect set of initial parameters, | ||
| 354 | |||
| 355 | my $p1 = pdl [ 1,1,1]; # not the parameters we used to make the data | ||
| 356 | my $h = levmar($p1,$xlin,$t,\&gauss2d); | ||
| 357 | |||
| 358 | At this point C<$h->{P}> refers to the output parameter ndarray C<[0.5, 2, 3]>. | ||
| 359 | |||
| 360 | =back | ||
| 361 | |||
| 362 | =head1 CONSTRAINTS | ||
| 363 | |||
| 364 | Several of the options below are related to constraints. There are | ||
| 365 | three types: box, linear equation, and linear inequality. They may | ||
| 366 | be used in any combination. (But there is no testing if | ||
| 367 | there is a possible solution.) None or one or two of C<UB> and C<LB> may be | ||
| 368 | specified. None or both of C<A> and C<B> may be specified. | ||
| 369 | None or both of C<C> and C<D> may be specified. | ||
| 370 | |||
| 371 | =head1 OPTIONS | ||
| 372 | |||
| 373 | It is best to learn how to call levmar by looking at the | ||
| 374 | examples first, and looking at this section later. | ||
| 375 | |||
| 376 | levmar() is called like this | ||
| 377 | |||
| 378 | levmar($arg1, $arg2, ..., OPT1=>$val1, OPT2=>$val2, ...); | ||
| 379 | or this: | ||
| 380 | levmar($arg1, $arg2, ..., {OPT1=>$val1, OPT2=>$val2, ...}); | ||
| 381 | |||
| 382 | When calling levmar, the first 3 ndarray arguments (or refs | ||
| 383 | to arrays), if present, are taken to be C<$p>,C<$x>, and C<$t> | ||
| 384 | (parameters, ordinate data, and co-ordinate data) in that | ||
| 385 | order. The first scalar value that can be interpreted as a | ||
| 386 | function will be. Everything else must be passed as an | ||
| 387 | option in a key-value pair. If you prefer, you can pass some | ||
| 388 | or all of C<$p,$x,$t> and the function as key-values in the | ||
| 389 | hash. Note that after the first key-value pair, you cannot | ||
| 390 | pass any more non-hash arguments. The following calls are equivalent | ||
| 391 | (where $func specifies the function as described in L</FUNC> ). | ||
| 392 | |||
| 393 | levmar($p, $x, $t, $func); | ||
| 394 | levmar($func,$p, $x, $t); | ||
| 395 | levmar($p, $x, $t, FUNC=> $func); | ||
| 396 | levmar($p, $x, T=>$t, FUNC => $func); | ||
| 397 | levmar($p, X=>$x, T=>$t, FUNC => $func); | ||
| 398 | levmar(P=>$p, X=>$x, T=>$t, FUNC => $func); | ||
| 399 | |||
| 400 | In the following, if the default value is not mentioned, it is undef. | ||
| 401 | C<$outh> refers to the output hash. | ||
| 402 | |||
| 403 | Some of these options are actually options to Levmar::Func. | ||
| 404 | All options to Levmar::Func may by given in calls to levmar(). | ||
| 405 | |||
| 406 | =over 4 | ||
| 407 | |||
| 408 | =item FUNC | ||
| 409 | |||
| 410 | This option is required (but it can be passed before the | ||
| 411 | options hash without the key C<FUNC> ) It can be | ||
| 412 | any of the following, which are auto-detected. | ||
| 413 | |||
| 414 | a string containing lpp code | ||
| 415 | a string containing pure C code | ||
| 416 | the filename of a file containing lpp code (which must end in '.lpp' ) | ||
| 417 | the filename of a file containing pure C code ( which must end in '.c' ) | ||
| 418 | a reference to perl code | ||
| 419 | a reference to a previously created Levmar::Func object (which was | ||
| 420 | previously created via one of the preceeding methods.) | ||
| 421 | |||
| 422 | If you are fitting a lot of data by doing many iterations over | ||
| 423 | a loop of perl code, it is by far most efficient to create a Func | ||
| 424 | object from C or lpp code and pass it to levmar. (Implicit broadcasting | ||
| 425 | does not recompile code in any case.) | ||
| 426 | |||
| 427 | You can also pass pure C code via the option CSRC. | ||
| 428 | |||
| 429 | =item JFUNC | ||
| 430 | |||
| 431 | This parameter is the jacobian as a ref to perl CODE. For | ||
| 432 | C and C<lpp> code, the jacobian, if present, is always in the | ||
| 433 | same source file as the fit function; in this case, you | ||
| 434 | should leave C<JFUNC> undefined. See L</Perl_Subroutines> | ||
| 435 | |||
| 436 | =item DERIVATIVE | ||
| 437 | |||
| 438 | This takes the value 'numeric' or 'analytic'. If it is | ||
| 439 | set to 'analytic', but no analytic jacobian of the model | ||
| 440 | function is supplied, then the numeric algorithms will be used | ||
| 441 | anyway. | ||
| 442 | |||
| 443 | =item NOCLEAN | ||
| 444 | |||
| 445 | If defined (NOCLEAN => 1), files containing generated C | ||
| 446 | object and dynamic library code are not deleted. If not | ||
| 447 | defined, these files are deleted after they are no longer | ||
| 448 | needed. For the source and object (.c and .o) files, this | ||
| 449 | means immediately after the dynamic library (.so) is built. | ||
| 450 | The dynamic library file is deleted when the corresponding | ||
| 451 | Levmar::Func object is destroyed. (It could be deleted after | ||
| 452 | it is loaded, I suppose, and then be rebuilt if needed | ||
| 453 | again) | ||
| 454 | |||
| 455 | =item FIX | ||
| 456 | |||
| 457 | Example: Fix => [1,0,0,1,0]. | ||
| 458 | This option takes a pdl (or array ref) of the same shape as | ||
| 459 | the parameters $p. Each element must have the value zero or | ||
| 460 | one. A zero corresponds to a free parameter and a one to a | ||
| 461 | fixed parameter. The best fit is found keeping the fixed | ||
| 462 | parameters at their input values and letting the free | ||
| 463 | parameters vary. This is implemented by using the linear | ||
| 464 | constraint option described below. Each element must be | ||
| 465 | either one or zero. This option currently cannot be | ||
| 466 | broadcasted. That is, if the array FIX has more than one | ||
| 467 | dimension you will not get correct results. Also, PDL will | ||
| 468 | not add dimension correctly if you pass additional | ||
| 469 | dimensions in other quantities. Threading will work if you | ||
| 470 | use linear constraints directly via C<A> and C<b>. | ||
| 471 | |||
| 472 | =item FIXB | ||
| 473 | |||
| 474 | This option is almost the same as FIX. It takes the same | ||
| 475 | values with the same meanings. It fixes parameters at the value | ||
| 476 | of the input parameters, but uses | ||
| 477 | box constraints, i.e., UB and LB rather than linear | ||
| 478 | constraints A and B. You can specify all three of UB,LB, and FIXB. | ||
| 479 | In this case, first box constraints determined by UB and LB are applied | ||
| 480 | Then, for those elements of FIXB with value one, the corresponding | ||
| 481 | values of UB and LB are overridden. | ||
| 482 | |||
| 483 | =item A | ||
| 484 | |||
| 485 | Example: A =>pdl [ [1,0], [0,1] ] , B => pdl [ 1,2 ] | ||
| 486 | |||
| 487 | Minimize with linear constraints $A x $p = $b. That is, | ||
| 488 | parameters $p are optimized over the subset of parameters | ||
| 489 | that solve the equation. The dimensions of the quantities | ||
| 490 | are A(k,m), b(m), p(m), where k is the number of | ||
| 491 | constraints. ( k <= m ). Note that $b is a vector (it has one | ||
| 492 | fewer dimensions than A), but the option key is a capital 'B'. | ||
| 493 | |||
| 494 | =item B | ||
| 495 | |||
| 496 | See C<A>. | ||
| 497 | |||
| 498 | =item UB | ||
| 499 | |||
| 500 | Example: UB => [10,10,10], LB => [-10,0,-5]. | ||
| 501 | Box constraints. These have the same shape as the parameter | ||
| 502 | pdl $p. The fit is done with ub forming upper bounds and lb | ||
| 503 | lower bounds on the parameter values. Use, for instance | ||
| 504 | PDL::Fit::Levmar::get_dbl_max() for parameters that you | ||
| 505 | don't want bounded. You can use either linear constraints or | ||
| 506 | box constraints, or both. That is, you may specify A, B, UB, and LB. | ||
| 507 | |||
| 508 | =item LB | ||
| 509 | |||
| 510 | See C<UB>. | ||
| 511 | |||
| 512 | =item WGHTS | ||
| 513 | |||
| 514 | Penalty weights can be given optionally when box and linear equality | ||
| 515 | constraints are both passed to levmar. See the levmar documenation for | ||
| 516 | how to use this. Note that if C and D are used then the WGHTS must | ||
| 517 | not passed. | ||
| 518 | |||
| 519 | =item C | ||
| 520 | |||
| 521 | Example: C => [ [ -1, -2, -1, -1], [ -3, -1, -2, 1] ], D => [ -5, -0.4] | ||
| 522 | Linear inequality constraints. Minimize with constraints $C x $p >= $d. | ||
| 523 | The dimensions are C(k2,m), D(m), p(m). | ||
| 524 | |||
| 525 | =item D | ||
| 526 | |||
| 527 | See C<C> | ||
| 528 | |||
| 529 | =item P | ||
| 530 | |||
| 531 | Keys P, X, and T can be used to send to the parameters, ordinates and coordinates. | ||
| 532 | Alternatively, you can send them as non-option arguments to levmar before | ||
| 533 | the option arguments. | ||
| 534 | |||
| 535 | =item X | ||
| 536 | |||
| 537 | See C<P> | ||
| 538 | |||
| 539 | =item T | ||
| 540 | |||
| 541 | See C<P> | ||
| 542 | |||
| 543 | =item DIR | ||
| 544 | |||
| 545 | The directory containing files created when compiling C<lpp> | ||
| 546 | and C fit functions. This defaults to being created by | ||
| 547 | L<File::Temp/tempdir>. The .c, | ||
| 548 | .o, and .so files will be written to this directory. This | ||
| 549 | option actually falls through to levmar_func. Such options | ||
| 550 | should be in separate section, or otherwise noted. | ||
| 551 | |||
| 552 | =item GETOPTS | ||
| 553 | |||
| 554 | If defined, return a ref to a hash containing the default | ||
| 555 | values of the parameters. | ||
| 556 | |||
| 557 | =item COVAR | ||
| 558 | |||
| 559 | Send a pdl reference for the output hash element COVAR. You may | ||
| 560 | want to test if this option is more efficient for | ||
| 561 | some problem. But unless the covariance matrix is very large, | ||
| 562 | it probably won't help much. On the other hand it almost certainly | ||
| 563 | won't make levmar() less efficient. | ||
| 564 | |||
| 565 | Note that levmar returns an ndarray representing the covariance in | ||
| 566 | the output hash. This will be the the same ndarray that you give | ||
| 567 | as input via this option. So, if you do the following, | ||
| 568 | |||
| 569 | my $covar = PDL->null | ||
| 570 | my $h =levmar(...., COVAR => $covar); | ||
| 571 | |||
| 572 | then $covar and $h->{COVAR} are references to the same | ||
| 573 | pdl. The storage for the pdl will not be destroyed until | ||
| 574 | both $covar and $h->{COVAR} become undefined. | ||
| 575 | |||
| 576 | =item NOCOVAR | ||
| 577 | |||
| 578 | If defined, no covariance matrix is computed. | ||
| 579 | |||
| 580 | =item POUT | ||
| 581 | |||
| 582 | Send a pdl reference for the output hash element P. Don't | ||
| 583 | confuse this with the option P which can be used to send the | ||
| 584 | initial guess for the parameters (see C<COVAR>). | ||
| 585 | |||
| 586 | =item INFO | ||
| 587 | |||
| 588 | Send a pdl reference for the output hash element C<INFO>. | ||
| 589 | (see C<COVAR>) | ||
| 590 | |||
| 591 | =item RET | ||
| 592 | |||
| 593 | Send a pdl reference for the output hash element C<RET>. | ||
| 594 | (see C<COVAR>) | ||
| 595 | |||
| 596 | =item MAXITS | ||
| 597 | |||
| 598 | Maximum number of iterations to try before giving up. The default | ||
| 599 | is 100. | ||
| 600 | |||
| 601 | =item MU | ||
| 602 | |||
| 603 | The starting value of the parameter mu in the L-M algorithm. | ||
| 604 | |||
| 605 | =item EPS1, EPS2, EPS3 | ||
| 606 | |||
| 607 | Stopping thresholds for C<||J^T e||_inf>, C<||Dp||_2> and | ||
| 608 | C<||e||_2>. (see the document levmar.pdf by the author of | ||
| 609 | liblevmar and distributed with this module) The algorithm | ||
| 610 | stops when the first threshold is reached (or C<MAXITS> is reached). See | ||
| 611 | C<REASON> for determining which threshold was reached. | ||
| 612 | |||
| 613 | Here, C<e> is a the vector of errors between the data and | ||
| 614 | the model function and C<p> is the vector of parameters. | ||
| 615 | S<||J^T e||_inf> is the gradient of C<e> w.r.t C<p> | ||
| 616 | at the current estimate of C<p>; C<||Dp||_2> is the amount | ||
| 617 | by which C<p> is currently being shifted at each iteration; | ||
| 618 | C<||e||_2> is a measure of the error between the model function | ||
| 619 | at the current estimate for C<p> and the data. | ||
| 620 | |||
| 621 | =item DELTA | ||
| 622 | |||
| 623 | This is a step size used in computing numeric derivatives. It is | ||
| 624 | not used if the analytic jacobian is used. | ||
| 625 | |||
| 626 | =item MKOBJ | ||
| 627 | |||
| 628 | command to compile source into object code. This option is actually set in | ||
| 629 | the Levmar::Func object, but can be given in calls to levmar(). | ||
| 630 | The default value is determined by the perl installation and can | ||
| 631 | be determined by examining the Levmar::Func object returned by | ||
| 632 | new or the output hash of a call to levmar. A typical value is | ||
| 633 | cc -c -O2 -fPIC -o %o %c | ||
| 634 | |||
| 635 | =item MKSO | ||
| 636 | |||
| 637 | command to convert object code to dynamic library code. | ||
| 638 | This option is actually set in the Levmar::Func object. A | ||
| 639 | typical default value is | ||
| 640 | cc -shared -L/usr/local/lib -fstack-protector %o -o %s | ||
| 641 | |||
| 642 | =item CTOP | ||
| 643 | |||
| 644 | The value of this string will be written at the top of the c code | ||
| 645 | written by Levmar::Func. This can be used to include headers and so forth. | ||
| 646 | This option is actually set in the Levmar::Func object. This code is also written | ||
| 647 | at the top of c code translated from lpp code. | ||
| 648 | |||
| 649 | =item FVERBOSE | ||
| 650 | |||
| 651 | If true (eg 1) Print the compiling and linking commands to STDERR when compiling fit functions. | ||
| 652 | This option is actually passed to Levmar::Func. Default is 0. | ||
| 653 | |||
| 654 | =item Default values | ||
| 655 | |||
| 656 | Here are the default values | ||
| 657 | of some options | ||
| 658 | |||
| 659 | $Levmar_defaults = { | ||
| 660 | FUNC => undef, # Levmar::Func object, or function def, or ... | ||
| 661 | JFUNC => undef, # must be ref to perl sub | ||
| 662 | MAXITS => 100, # maximum iterations | ||
| 663 | MU => LM_INIT_MU, # These are described in levmar docs | ||
| 664 | EPS1 => LM_STOP_THRESH, | ||
| 665 | EPS2 => LM_STOP_THRESH, | ||
| 666 | EPS3 => LM_STOP_THRESH, | ||
| 667 | DELTA => LM_DIFF_DELTA, | ||
| 668 | DERIVATIVE => 'analytic', | ||
| 669 | FIX => undef, | ||
| 670 | A => undef, | ||
| 671 | B => undef, | ||
| 672 | C => undef, | ||
| 673 | D => undef, | ||
| 674 | UB = undef, | ||
| 675 | LB => undef, | ||
| 676 | X => undef, | ||
| 677 | P => undef, | ||
| 678 | T => undef, | ||
| 679 | WGHTS => undef, | ||
| 680 | # meant to be private | ||
| 681 | LFUNC => undef, # only Levmar::Func object, made from FUNC | ||
| 682 | }; | ||
| 683 | |||
| 684 | =back | ||
| 685 | |||
| 686 | =head1 OUTPUT | ||
| 687 | |||
| 688 | This section describes the contents of the hash that | ||
| 689 | levmar takes as output. Do not confuse these hash keys with | ||
| 690 | the hash keys of the input options. It may be a good idea | ||
| 691 | to change the interface by prepending O to all of the output | ||
| 692 | keys that could be confused with options to levmar(). | ||
| 693 | |||
| 694 | =over 3 | ||
| 695 | |||
| 696 | =item P (output) | ||
| 697 | |||
| 698 | pdl containing the optimized parameters. It has the same shape | ||
| 699 | as the input parameters. | ||
| 700 | |||
| 701 | =item FUNC (output) | ||
| 702 | |||
| 703 | ref to the Levmar::Func object. This object may have been created | ||
| 704 | during the call to levmar(). For instance, if you pass a string | ||
| 705 | contiaining an C<lpp> definition, the compiled object (and associated | ||
| 706 | information) is contained in $outh->{FUNC}. Don't confuse this with | ||
| 707 | the input parameter of the same name. | ||
| 708 | |||
| 709 | =item COVAR (output) | ||
| 710 | |||
| 711 | a pdl representing covariance matrix. | ||
| 712 | |||
| 713 | =item REASON | ||
| 714 | |||
| 715 | an integer code representing the reason for terminating the | ||
| 716 | fit. (call levmar_report($outh) for an interpretation. The interpretations | ||
| 717 | are listed here as well (see the liblevmar documentation if you don't | ||
| 718 | find an explanation somewhere here.) | ||
| 719 | |||
| 720 | 1 stopped by small gradient J^T e | ||
| 721 | 2 stopped by small Dp | ||
| 722 | 3 stopped by itmax | ||
| 723 | 4 singular matrix. Restart from current p with increased \mu | ||
| 724 | 5 no further error reduction is possible. Restart with increased \mu | ||
| 725 | 6 stopped by small ||e||_2 | ||
| 726 | |||
| 727 | =item ERRI, ERR1, ERR2, ERR3, ERR4 | ||
| 728 | |||
| 729 | ERRI is C<||e||_2> at the initial paramters. ERR1 through | ||
| 730 | ERR3 are the actual values on termination of the quantities | ||
| 731 | corresponding to the thresholds EPS1 through EPS3 described | ||
| 732 | in the options section. ERR4 is C<mu/max[J^T J]_ii> | ||
| 733 | |||
| 734 | =item ITS | ||
| 735 | |||
| 736 | Number of iterations performed | ||
| 737 | |||
| 738 | =item NFUNC, NJAC, NLS | ||
| 739 | |||
| 740 | Number of function evaluations, number of jacobian evaluations | ||
| 741 | and number of linear systems solved. | ||
| 742 | |||
| 743 | =item INFO | ||
| 744 | |||
| 745 | Array containing ERRI,ERR1, ..., ERR4, ITS, REASON, NFUNC, NJAC, NLS. | ||
| 746 | |||
| 747 | =back | ||
| 748 | |||
| 749 | =head1 FIT FUNCTIONS | ||
| 750 | |||
| 751 | Fit functions, or model functions can be specified in the following | ||
| 752 | ways. | ||
| 753 | |||
| 754 | =over 3 | ||
| 755 | |||
| 756 | =item lpp | ||
| 757 | |||
| 758 | It is easier to learn to use C<lpp> by reading the C<EXAMPLES> section. | ||
| 759 | |||
| 760 | C<lpp> processes a function definition into C code. It writes | ||
| 761 | the opening and closing parts of the function, alters a | ||
| 762 | small number of identifiers if they appear, and wraps some | ||
| 763 | of the code in a loop. C<lpp> recognizes four directives. They | ||
| 764 | must occur on a line with nothing else, not even comments. | ||
| 765 | |||
| 766 | First, the directives are explained, then the substitutions. | ||
| 767 | The directive lines have a strict format. All other lines | ||
| 768 | can contain any C code including comments and B<cpp> | ||
| 769 | macros. They will be written to a function in C after the | ||
| 770 | substitutions described below. | ||
| 771 | |||
| 772 | =over 3 | ||
| 773 | |||
| 774 | =item C<function, jacobian> | ||
| 775 | |||
| 776 | The first line of the fit function definition must be | ||
| 777 | C<function funcname>. The first line of the jacobian | ||
| 778 | definition, if the jacobian is to be defined, is C<jacobian | ||
| 779 | funcname>. The function names can be any valid C function | ||
| 780 | name. The names may also be omitted as they are never needed | ||
| 781 | by the user. The names can be identical. (Note that a | ||
| 782 | numeric suffix will be automatically added to the function | ||
| 783 | name if the .so file already exists. This is because, if | ||
| 784 | another Func object has already loaded the shared library | ||
| 785 | from an .so file, dlopen will use this loaded library for | ||
| 786 | all C<Func> objects asking for that .so file, even if the | ||
| 787 | file has been overwritten, causing unexpected behavior) | ||
| 788 | |||
| 789 | =item C<loop> | ||
| 790 | |||
| 791 | The directive C<loop> says that all code before C<loop> is not | ||
| 792 | in the implicit loop, while all code following C<loop> is in | ||
| 793 | the implicit loop. If you omit the directive, then all the code | ||
| 794 | is wrapped in a loop. | ||
| 795 | |||
| 796 | =item C<noloop> | ||
| 797 | |||
| 798 | The directive C<noloop> says that there is no implicit loop anywhere | ||
| 799 | in the function. | ||
| 800 | |||
| 801 | =item Out-of-loop substitutions | ||
| 802 | |||
| 803 | These substitutions translate C<lpp> to C in lines that occur | ||
| 804 | before the implied loop (or everywhere if there is no loop.) | ||
| 805 | In every case you can write the translated C code into your | ||
| 806 | function definition yourself and C<lpp> will leave it | ||
| 807 | untouched. | ||
| 808 | |||
| 809 | =over 3 | ||
| 810 | |||
| 811 | =item pq -> p[q] | ||
| 812 | |||
| 813 | where q is a sequence of digits. | ||
| 814 | |||
| 815 | =item xq -> x[q] | ||
| 816 | |||
| 817 | where q is a sequence of digits. This is applied only in the fit function, | ||
| 818 | not in the jacobian. | ||
| 819 | |||
| 820 | =item dq[r] -> d[q+m*r] | ||
| 821 | |||
| 822 | (where m == $p->nelem), q and r are sequences of | ||
| 823 | digits. This applies only in the jacobian. You usually will | ||
| 824 | only use the fit functions with one value of m. It would | ||
| 825 | make faster code if you were to explicitly write, say C<d[u]>, | ||
| 826 | for each derivative at each point. Presumably there is a | ||
| 827 | small number of data points since this is outside a | ||
| 828 | loop. Some provisions should be added to C<lpp>, say C<m=3> to | ||
| 829 | hard code the value of C<m>. But m is only explicitly used in | ||
| 830 | constructions involving this substitution. | ||
| 831 | |||
| 832 | =back | ||
| 833 | |||
| 834 | =item In-loop substitutions | ||
| 835 | |||
| 836 | These substitutions apply inside the implied loop. The loop variables are | ||
| 837 | i in the fit function and i and j in the jacobian. | ||
| 838 | |||
| 839 | =over 3 | ||
| 840 | |||
| 841 | =item t -> t[i] | ||
| 842 | |||
| 843 | (literal "i") You can also write t[i] or t[expression involving i] by hand. | ||
| 844 | Example: t*t -> t[i]*t[i]. | ||
| 845 | |||
| 846 | =item pq -> p[q] | ||
| 847 | |||
| 848 | where q is a sequence of digits. Example p3 -> p[3]. | ||
| 849 | |||
| 850 | =item x -> x[i] | ||
| 851 | |||
| 852 | only in fit function, not in jacobian. | ||
| 853 | |||
| 854 | =item (dr or dr[i]) -> d[j++] | ||
| 855 | |||
| 856 | where r is a sequence of digits. Note that r and i are | ||
| 857 | ignored. So you are required to list the derivatives in | ||
| 858 | order. An example is | ||
| 859 | |||
| 860 | d0 = t*t; // derivative w.r.t p[0] loop over all points | ||
| 861 | d1 = t; | ||
| 862 | |||
| 863 | If you write C<d1> first and then C<d0>, lpp will incorrectly | ||
| 864 | assign the derivative functions. | ||
| 865 | |||
| 866 | =back | ||
| 867 | |||
| 868 | =back | ||
| 869 | |||
| 870 | =item C Code | ||
| 871 | |||
| 872 | The jacobian name must start with 'jac' when a pure C function definition | ||
| 873 | is used. To see example of fit functions writen in C, call levmar | ||
| 874 | with lpp code and the option C<NOCLEAN>. This will leave the C source | ||
| 875 | in the directory given by C<DIR>. The C code you supply is mangled | ||
| 876 | slightly before passing it to the compiler: It is copied twice, with | ||
| 877 | FLOAT defined in one case as C<double> and in the other as C<float>. | ||
| 878 | The letter C<s> is also appended to the function names in the latter | ||
| 879 | copy. The C code is parsed to find the fit function name and the | ||
| 880 | jacobian function name. | ||
| 881 | |||
| 882 | We should make it possible to pass the function names as a separate option | ||
| 883 | rather than parsing the C code. This will allow auxiallary functions to | ||
| 884 | be defined in the C code; something that is currently not possible. | ||
| 885 | |||
| 886 | =item Perl_Subroutines | ||
| 887 | |||
| 888 | This is how to use perl subroutines as fit functions... (see | ||
| 889 | the examples for now, e.g. L<example 2|/example--2>.) The | ||
| 890 | fit function takes ndarrays $p,$x, and $t, with dimensions | ||
| 891 | m,n, and tn. (often tn ==n ). These are references with | ||
| 892 | storage already allocated (by the user and liblevmar). So | ||
| 893 | you must use C<.=> when setting values. The jacobian takes | ||
| 894 | ndarrays $p,$d, and $t, where $d, the ndarray of derivatives | ||
| 895 | has dimensions (m,n). For example | ||
| 896 | |||
| 897 | $f = sub myexp { | ||
| 898 | my ($p,$x,$t) = @_; | ||
| 899 | my ($p0,$p1,$p2) = list($p); | ||
| 900 | $x .= exp($t/$p0); | ||
| 901 | $x *= $p1; | ||
| 902 | $x += $p2 | ||
| 903 | } | ||
| 904 | |||
| 905 | $jf = sub my expjac { | ||
| 906 | my ($p,$d,$t) = @_; | ||
| 907 | my ($p0,$p1,$p2) = list($p); | ||
| 908 | my $arg = $t/$p0; | ||
| 909 | my $ex = exp($arg); | ||
| 910 | $d((0)) .= -$p1*$ex*$arg/$p0; | ||
| 911 | $d((1)) .= $ex; | ||
| 912 | $d((2)) .= 1.0; | ||
| 913 | } | ||
| 914 | |||
| 915 | =back | ||
| 916 | |||
| 917 | =head1 PDL::Fit::Levmar::Func Objects | ||
| 918 | |||
| 919 | These objects are created every time you call levmar(). The hash | ||
| 920 | returned by levmar contains a ref to the Func object. For instance | ||
| 921 | if you do | ||
| 922 | |||
| 923 | $outh = levmar( FUNC => ..., @opts); | ||
| 924 | |||
| 925 | then $outh->{LFUNC} will contain a ref to the function object. The .so | ||
| 926 | file, if it exists, will not be deleted until the object is destroyed. | ||
| 927 | This will happen, for instance if you do C<$outh = undef>. | ||
| 928 | |||
| 929 | =head1 IMPLEMENTATION | ||
| 930 | |||
| 931 | This section currently only refers to the interface and not the fit algorithms. | ||
| 932 | |||
| 933 | =over 3 | ||
| 934 | |||
| 935 | =item C fit functions | ||
| 936 | |||
| 937 | The module does not use perl interfaces to dlopen or the C | ||
| 938 | compiler. The C compiler options are taken from | ||
| 939 | %Config. This is mostly because I had already written those | ||
| 940 | parts before I found the modules. I imagine the | ||
| 941 | implementation here has less overhead, but is less portable. | ||
| 942 | |||
| 943 | =item perl subroutine fit functions | ||
| 944 | |||
| 945 | Null pdls are created in C code before the fit starts. They | ||
| 946 | are passed in a struct to the C fit function and derivative | ||
| 947 | routines that wrap the user's perl code. At each call the | ||
| 948 | data pointers to the pdls are set to what liblevmar has sent | ||
| 949 | to the fit functions. The pdls are deleted after the fit. | ||
| 950 | Originally, all the information on the fit functions was | ||
| 951 | supposed to be handled by Levmar::Func. But when I added | ||
| 952 | perl subroutine support, it was less clumsy to move most of | ||
| 953 | the code for perl subs to the Levmar module. So the current | ||
| 954 | solution is not very clean. | ||
| 955 | |||
| 956 | =item Efficiency | ||
| 957 | |||
| 958 | Using C<lpp> or C is faster than using perl subs, which is | ||
| 959 | faster than using L<PDL::Fit::LM>, at least in all the tests I have | ||
| 960 | done. For very large data sets, pure C was twice as fast as | ||
| 961 | perl subs and three times as fast as Fit::LM. Some | ||
| 962 | optimization problems have very small data sets and converge | ||
| 963 | very slowly. As the data sets become smaller and the number | ||
| 964 | of iterations increases the advantage of using pure C | ||
| 965 | increases as expected. Also, if I fit a small data set | ||
| 966 | (n=10) a large number of times (just looping over the same | ||
| 967 | problem), Pure C is ten times faster than Fit::LM, while | ||
| 968 | Levmar with perl subs is only about 1.15 times faster than | ||
| 969 | Fit::LM. All of this was observed on only two different | ||
| 970 | problems. | ||
| 971 | |||
| 972 | =back | ||
| 973 | |||
| 974 | =head1 FUNCTIONS | ||
| 975 | |||
| 976 | =head2 levmar() | ||
| 977 | |||
| 978 | =for ref | ||
| 979 | |||
| 980 | Perform Levenberg-Marquardt non-linear least squares fit | ||
| 981 | to data given a model function. | ||
| 982 | |||
| 983 | =for usage | ||
| 984 | |||
| 985 | use PDL::Fit::Levmar; | ||
| 986 | |||
| 987 | $result_hash = levmar($p,$x,$t, FUNC => $func, %OPTIONS ); | ||
| 988 | |||
| 989 | $p is a pdl of input parameters | ||
| 990 | $x is a pdl of ordinate data | ||
| 991 | $t is an optional pdl of co-ordinate data | ||
| 992 | |||
| 993 | levmar() is the main function in the Levmar package. See the | ||
| 994 | PDL::Fit::Levmar for a complete description. | ||
| 995 | |||
| 996 | =for signature | ||
| 997 | |||
| 998 | p(m); x(n); t(nt); int itmax(); | ||
| 999 | [o] covar(m,m) ; int [o] returnval(); | ||
| 1000 | [o] pout(m); [o] info(q=10); | ||
| 1001 | |||
| 1002 | See the module documentation for information on passing | ||
| 1003 | these arguments to levmar. Threading is known to | ||
| 1004 | work with p(m) and x(n), but I have not tested the rest. In | ||
| 1005 | this case all of they output pdls get the correct number of | ||
| 1006 | dimensions (and correct values !). Notice that t(nt) has a | ||
| 1007 | different dimension than x(n). This is correct because in | ||
| 1008 | some problems there is no t at all, and in some it is | ||
| 1009 | pressed into the service of delivering other parameters to | ||
| 1010 | the fit routine. (Formally, even if you use t(n), they are | ||
| 1011 | parameters.) | ||
| 1012 | |||
| 1013 | =head2 levmar_chkjac() | ||
| 1014 | |||
| 1015 | =for ref | ||
| 1016 | |||
| 1017 | Check the analytic jacobian of a function by computing | ||
| 1018 | the derivatives numerically. | ||
| 1019 | |||
| 1020 | =for signature | ||
| 1021 | |||
| 1022 | p(m); t(n); [o] err(n); | ||
| 1023 | This is the relevant part of the signature of the | ||
| 1024 | routine that does the work. | ||
| 1025 | |||
| 1026 | =for usage | ||
| 1027 | |||
| 1028 | use PDL::Fit::Levmar; | ||
| 1029 | |||
| 1030 | $Gh = levmar_func(FUNC=>$Gf); | ||
| 1031 | |||
| 1032 | $err = levmar_chkjac($Gh,$p,$t); | ||
| 1033 | |||
| 1034 | $f is an object of type PDL::Fit::Levmar::Func | ||
| 1035 | $p is a pdl of input parameters | ||
| 1036 | $t is an pdl of co-ordinate data | ||
| 1037 | $err is a pdl of errors computed at the values $t. | ||
| 1038 | |||
| 1039 | Note: No data $x is supplied to this function | ||
| 1040 | |||
| 1041 | The Func object $Gh contains a function f, and a jacobian | ||
| 1042 | jf. The i_th element of $err measures the agreement between | ||
| 1043 | the numeric and analytic gradients of f with respect to $p | ||
| 1044 | at the i_th evaluation point f (normally determined by the | ||
| 1045 | i_th element of t). A value of 1 means that the analytic and | ||
| 1046 | numeric gradients agree well. A value of 0 mean they do not | ||
| 1047 | agree. | ||
| 1048 | |||
| 1049 | Sometimes the number of evaluation points n is hardcoded | ||
| 1050 | into the function (as in almost all the examples taken from | ||
| 1051 | liblevmar and appearing in t/liblevmar.t. In this case the | ||
| 1052 | values that f returns depend only on $p and not on any other | ||
| 1053 | external data (nameley t). In this case, you must pass the | ||
| 1054 | number n as a perl scalar in place of t. For example | ||
| 1055 | |||
| 1056 | $err = levmar_chkjac($Gh,$p,5); | ||
| 1057 | |||
| 1058 | in the case that f is hardcoded to return five values. | ||
| 1059 | |||
| 1060 | Need to put the description from the C code in here. | ||
| 1061 | |||
| 1062 | =head2 levmar_report() | ||
| 1063 | |||
| 1064 | =for ref | ||
| 1065 | |||
| 1066 | Make a human readable report from the hash ref returned | ||
| 1067 | by levmar(). | ||
| 1068 | |||
| 1069 | =for usage | ||
| 1070 | |||
| 1071 | use PDL::Fit::Levmar; | ||
| 1072 | |||
| 1073 | $h = levmar($p,$x,$t, $func); | ||
| 1074 | |||
| 1075 | print levmar_report($h); | ||
| 1076 | |||
| 1077 | =head1 BUGS | ||
| 1078 | |||
| 1079 | With the levmar-2.6 code: Passing workspace currently does not work with | ||
| 1080 | linear inequality constraint. Some of the PDL broadcasting no long works | ||
| 1081 | correctly. These are noted in the tests in t/thread.t. It is not clear | ||
| 1082 | if it is a broadcasting issue or the fitting has changed. | ||
| 1083 | |||
| 1084 | |||
| 1085 | =cut | ||
| 1086 | |||
| 1087 | #-------------------------------------------------------------------- | ||
| 1088 | # Begining of module code | ||
| 1089 | |||
| 1090 | use strict; | ||
| 1091 | use PDL::Fit::Levmar::Func; | ||
| 1092 | use Carp; | ||
| 1093 | use PDL::NiceSlice; | ||
| 1094 | use PDL::Core ':Internal'; # For topdl() | ||
| 1095 | use vars ( '$Levmar_defaults', '$Levmar_defaults_order', | ||
| 1096 | '$Perl_func_wrapper', '$Perl_jac_wrapper', '$LPPEXT', '$DBLMAX' ); | ||
| 1097 | |||
| 1098 | # 'jac' refers to jacobian | ||
| 1099 | $Perl_func_wrapper = get_perl_func_wrapper(); | ||
| 1100 | $Perl_jac_wrapper = get_perl_jac_wrapper(); | ||
| 1101 | $DBLMAX = get_dbl_max(); | ||
| 1102 | |||
| 1103 | $LPPEXT = ".lpp"; | ||
| 1104 | |||
| 1105 | sub deb { print STDERR $_[0],"\n"} | ||
| 1106 | |||
| 1107 | #line 1130 "levmar.pd" | ||
| 1108 | $PDL::Fit::Levmar::HAVE_LAPACK=0; | ||
| 1109 | |||
| 1110 | #line 1165 "levmar.pd" | ||
| 1111 | # check if dims are equal in two pdls | ||
| 1112 | sub chk_eq_dims { | ||
| 1113 | my ($x,$y) = @_; | ||
| 1114 | my (@xd) = $x->dims(); | ||
| 1115 | my (@yd) = $y->dims(); | ||
| 1116 | return -2 if (scalar(@xd) != scalar(@yd) ); | ||
| 1117 | my $ret = 1; | ||
| 1118 | foreach (@xd) { | ||
| 1119 | return -1 if ($_ != shift(@yd) ); | ||
| 1120 | } | ||
| 1121 | return $ret; | ||
| 1122 | } | ||
| 1123 | |||
| 1124 | @PDL::Fit::Levmar::reason_for_terminating = ( | ||
| 1125 | '', | ||
| 1126 | 'stopped by small gradient J^T e', | ||
| 1127 | 'stopped by small Dp', | ||
| 1128 | 'stopped by itmax', | ||
| 1129 | 'singular matrix. Restart from current p with increased \mu', | ||
| 1130 | 'no further error reduction is possible. Restart with increased \mu', | ||
| 1131 | 'stopped by small ||e||_2' | ||
| 1132 | ); | ||
| 1133 | |||
| 1134 | sub levmar_report { | ||
| 1135 | my $h = shift; | ||
| 1136 | make_report($h->{P},$h->{COVAR}, $h->{INFO}); | ||
| 1137 | } | ||
| 1138 | |||
| 1139 | # make a small report out of the results of the optimization | ||
| 1140 | sub make_report { | ||
| 1141 | my ($p,$covar,$info) = @_; | ||
| 1142 | my @ninf = list($info); | ||
| 1143 | # for(my $i=0;$i<9; $i++) { # Tried to get broadcasting to work, but no! | ||
| 1144 | # $ninf[$i] = $info(($i)); | ||
| 1145 | # } | ||
| 1146 | $ninf[6] = | ||
| 1147 | $PDL::Fit::Levmar::reason_for_terminating[$ninf[6]]; # replace int with string | ||
| 1148 | my $form = <<"EOFORM"; | ||
| 1149 | Estimated parameters: %s | ||
| 1150 | Covariance: %s | ||
| 1151 | ||e||_2 at initial parameters = %g | ||
| 1152 | Errors at estimated parameters: | ||
| 1153 | ||e||_2\t = %g | ||
| 1154 | ||J^T e||_inf\t= %g | ||
| 1155 | ||Dp||_2\t= %g | ||
| 1156 | \\mu/max[J^T J]_ii ]\t= %g | ||
| 1157 | number of iterations\t= %d | ||
| 1158 | reason for termination: = %s | ||
| 1159 | number of function evaluations\t= %d | ||
| 1160 | number of jacobian evaluations\t= %d | ||
| 1161 | number of linear systems solved\t= %d | ||
| 1162 | EOFORM | ||
| 1163 | my $st = sprintf($form, $p,$covar,@ninf); | ||
| 1164 | |||
| 1165 | } | ||
| 1166 | |||
| 1167 | $Levmar_defaults_order = qw [ | ||
| 1168 | FUNC | ||
| 1169 | |||
| 1170 | |||
| 1171 | ]; | ||
| 1172 | |||
| 1173 | $Levmar_defaults = { | ||
| 1174 | MAXITS => 100, # maximum iterations | ||
| 1175 | MU => LM_INIT_MU(), | ||
| 1176 | EPS1 => LM_STOP_THRESH(), | ||
| 1177 | EPS2 => LM_STOP_THRESH(), | ||
| 1178 | EPS3 => LM_STOP_THRESH(), | ||
| 1179 | DELTA => LM_DIFF_DELTA(), | ||
| 1180 | DERIVATIVE => 'analytic', | ||
| 1181 | NOCOVAR => undef, | ||
| 1182 | FIX => undef, | ||
| 1183 | FIXB => undef, | ||
| 1184 | A => undef, | ||
| 1185 | B => undef, | ||
| 1186 | C => undef, | ||
| 1187 | D => undef, | ||
| 1188 | UB => undef, | ||
| 1189 | LB => undef, | ||
| 1190 | FUNC => undef, # Levmar::Func object, or function def, or ... | ||
| 1191 | JFUNC => undef, # must be ref to perl sub | ||
| 1192 | X => undef, | ||
| 1193 | P => undef, | ||
| 1194 | T => undef, | ||
| 1195 | WGHTS => undef, | ||
| 1196 | COVAR => undef, # The next 5 params can be set to PDL->null | ||
| 1197 | POUT => undef, # ref for preallocated output parameters | ||
| 1198 | INFO => undef, | ||
| 1199 | RET => undef, | ||
| 1200 | # meant to be private | ||
| 1201 | LFUNC => undef, # only Levmar::Func object, made from FUNC | ||
| 1202 | }; | ||
| 1203 | |||
| 1204 | # This isn't meant to replace help. But for now its doing nothing. | ||
| 1205 | sub get_help_str { | ||
| 1206 | return ' | ||
| 1207 | This is the help string for levmar. | ||
| 1208 | |||
| 1209 | '; | ||
| 1210 | } | ||
| 1211 | |||
| 1212 | ################################################################# | ||
| 1213 | sub levmar { | ||
| 1214 | my($p,$x,$t,$infunc); | ||
| 1215 | my $args; | ||
| 1216 | # get all args before the hash. p,x,t must come in that order | ||
| 1217 | # but (t), or (t and x), or (t,x,and p) can be in the hash | ||
| 1218 | # the function can be anywhere before the hash | ||
| 1219 | while (1) { | ||
| 1220 | $args = 0; | ||
| 1221 | if ( (not defined $p ) and (ref($_[0]) eq 'PDL' or ref($_[0]) eq 'ARRAY')) { | ||
| 1222 | $p = shift ; $args++; | ||
| 1223 | } | ||
| 1224 | last if ( @_ == 0 ); | ||
| 1225 | if ( (not defined $x ) and (ref($_[0]) eq 'PDL' or ref($_[0]) eq 'ARRAY')) { | ||
| 1226 | $x = shift ; $args++; | ||
| 1227 | } | ||
| 1228 | last if ( @_ == 0 ); | ||
| 1229 | if ( (not defined $t) and (ref($_[0]) eq 'PDL' or ref($_[0]) eq 'ARRAY')) { | ||
| 1230 | $t = shift ; $args++; | ||
| 1231 | } | ||
| 1232 | last if ( @_ == 0 ); | ||
| 1233 | if ( not defined $infunc and ref($_[0]) =~ /Func|CODE/ ) { | ||
| 1234 | $infunc = shift; $args++; | ||
| 1235 | } | ||
| 1236 | last if ( @_ == 0 ); | ||
| 1237 | if ( (not defined $infunc) and | ||
| 1238 | ( not ref($_[0]) ) and ( $_[0] =~ /(\.c|$LPPEXT)$/o or $_[0] =~ /\n/ ) ) { | ||
| 1239 | $infunc = shift; $args++; | ||
| 1240 | } | ||
| 1241 | last if ( @_ == 0 or $args == 0); | ||
| 1242 | } | ||
| 1243 | my $inh; | ||
| 1244 | $inh = shift if @_; # input parameter hash | ||
| 1245 | $inh = {} unless defined $inh; | ||
| 1246 | if(ref $inh ne 'HASH') { # turn list into anonymous hash | ||
| 1247 | $inh = defined $inh ? {$inh,@_} : {} ; | ||
| 1248 | } | ||
| 1249 | if( exists $inh->{HELP} ) { | ||
| 1250 | my $s = get_help_str(); | ||
| 1251 | return $s; | ||
| 1252 | } | ||
| 1253 | if( exists $inh->{GETOPTS} ) { | ||
| 1254 | my %h = %$Levmar_defaults; | ||
| 1255 | return \%h; | ||
| 1256 | } | ||
| 1257 | # should already use a ref to string here | ||
| 1258 | $inh->{FUNC} = $infunc if defined $infunc; | ||
| 1259 | die "levmar: neither FUNC nor CSRC defined" | ||
| 1260 | unless defined $inh->{FUNC} or defined $inh->{CSRC}; | ||
| 1261 | |||
| 1262 | #line 1322 "levmar.pd" | ||
| 1263 | |||
| 1264 | foreach (qw( A B C D FIX WGHT )) { | ||
| 1265 | barf "PDL::Fit::Levmar not built with lapack. Found parameter $_" | ||
| 1266 | if exists $inh->{$_}; | ||
| 1267 | } | ||
| 1268 | |||
| 1269 | |||
| 1270 | #line 1331 "levmar.pd" | ||
| 1271 | |||
| 1272 | ######## Handle parameters | ||
| 1273 | my $h = {}; # parameter hash to be built from $inh and defaults | ||
| 1274 | my $funch = {}; # unrecognized parameter hash. This will be passed to Func. | ||
| 1275 | foreach ( keys %$Levmar_defaults ){ # copy defaults to final hash | ||
| 1276 | $h->{$_} = $Levmar_defaults->{$_}; | ||
| 1277 | } | ||
| 1278 | foreach my $k (keys %$inh ) { # replace defaults with input params | ||
| 1279 | if ( exists $Levmar_defaults->{$k} ) { | ||
| 1280 | $h->{$k} = $inh->{$k}; | ||
| 1281 | } | ||
| 1282 | else { # don't recognize, so pass to Func | ||
| 1283 | $funch->{$k} = $inh->{$k}; | ||
| 1284 | } | ||
| 1285 | } | ||
| 1286 | ########## Set up input and output variables | ||
| 1287 | |||
| 1288 | # These must come from parameters if not from the arg list | ||
| 1289 | $p = $h->{P} unless not defined $h->{P} and defined $p; | ||
| 1290 | $x = $h->{X} unless not defined $h->{X} and defined $p; | ||
| 1291 | $t = $h->{T} unless not defined $h->{T} and defined $p; | ||
| 1292 | |||
| 1293 | if ( not defined $p ) { # This looks like some kind of error thing that was | ||
| 1294 | # not implemented consistently | ||
| 1295 | my $st = "No parameter (P) pdl"; | ||
| 1296 | warn $st; | ||
| 1297 | return {RET => -1, ERRS => [$st] }; | ||
| 1298 | } | ||
| 1299 | if ( not defined $x ) { | ||
| 1300 | my $st = "No data (X) pdl"; | ||
| 1301 | warn $st; | ||
| 1302 | return {RET => -1, ERRS => [$st] }; | ||
| 1303 | } | ||
| 1304 | |||
| 1305 | #------------------------------------------------- | ||
| 1306 | # Treat input and output ndarrays for pp_defs | ||
| 1307 | $x = topdl($x); # in case they are refs to arrays | ||
| 1308 | $p = topdl($p); | ||
| 1309 | $t = PDL->zeroes($p->type, 1) unless defined $t; # sometimes $t not needed | ||
| 1310 | $t = topdl($t); | ||
| 1311 | ### output variables | ||
| 1312 | my $pout; | ||
| 1313 | my $info; | ||
| 1314 | my $covar; | ||
| 1315 | my $ret; | ||
| 1316 | my $wghts; | ||
| 1317 | |||
| 1318 | # should put this stuff in a loop | ||
| 1319 | $covar = $h->{COVAR} if defined $h->{COVAR}; | ||
| 1320 | $pout = $h->{POUT} if defined $h->{POUT}; | ||
| 1321 | $info = $h->{INFO} if defined $h->{INFO}; | ||
| 1322 | $ret = $h->{RET} if defined $h->{RET}; | ||
| 1323 | $wghts = $h->{WGHTS} if defined $h->{WGHTS}; | ||
| 1324 | |||
| 1325 | # If they are set here, then there will be no external ref. | ||
| 1326 | $covar = PDL->null unless defined $covar; | ||
| 1327 | $pout = PDL->null unless defined $pout; | ||
| 1328 | $info = PDL->null unless defined $info; | ||
| 1329 | $ret = PDL->null unless defined $ret; | ||
| 1330 | $wghts = PDL->null unless defined $wghts; | ||
| 1331 | |||
| 1332 | # Careful about $m, it is used in construcing $A below (with fix). But this is | ||
| 1333 | # not correct when using implicit broadcasting. Except broadcasting may still be working. | ||
| 1334 | # Need to look into that. | ||
| 1335 | my $m = $p->nelem; | ||
| 1336 | |||
| 1337 | #-------------------------------------------------------- | ||
| 1338 | # Set up Func object | ||
| 1339 | #-------------------------------------------------------- | ||
| 1340 | croak "No FUNC in options to levmar." unless exists $h->{FUNC}; | ||
| 1341 | if ( ref($h->{FUNC}) =~ /CODE/ or | ||
| 1342 | not ref($h->{FUNC}) ) { # probably a string, convert to func object | ||
| 1343 | $funch->{FUNC} = $h->{FUNC}; | ||
| 1344 | my @ret = PDL::Fit::Levmar::Func::levmar_func($funch); | ||
| 1345 | if ($ret[0] == -1 ) { # error in creating function | ||
| 1346 | shift(@ret); | ||
| 1347 | # deb "Error: " . join("\n",@ret); # can turn this off and on | ||
| 1348 | return {RET => -1, ERRS => [@ret] } ; # just return all the other messages. | ||
| 1349 | } | ||
| 1350 | $h->{LFUNC} = $ret[0]; | ||
| 1351 | } | ||
| 1352 | else { # already a Func object | ||
| 1353 | $h->{LFUNC} = $h->{FUNC} ; # copy ref | ||
| 1354 | my @k = keys %$funch; | ||
| 1355 | # It would be good to check for valid options. But if a user switches from a | ||
| 1356 | # string to a Func oject in the call to levmar(), he may not delete the | ||
| 1357 | # other keys. Halting on an error would bit frustrating or puzzling. | ||
| 1358 | # Even a warning is perhaps too much | ||
| 1359 | if ( @k ) { | ||
| 1360 | my $s = ''; $s = 's' if @k>1; | ||
| 1361 | my $str = "Unrecognized or useless option$s to levmar: \n"; | ||
| 1362 | foreach ( @k ) { | ||
| 1363 | $str .= " '$_' => '" . $funch->{$_} . "'\n" ; | ||
| 1364 | } | ||
| 1365 | warn $str .""; | ||
| 1366 | } | ||
| 1367 | } | ||
| 1368 | # C pointers to fit functions | ||
| 1369 | my ($funcn,$sfuncn,$jacn,$sjacn) = # single and double | ||
| 1370 | $h->{LFUNC}->get_fit_pointers(); | ||
| 1371 | my $deriv = $h->{DERIVATIVE}; | ||
| 1372 | |||
| 1373 | # The DFP stuff is to wrap perl functions in C routines to pass to liblevmar. | ||
| 1374 | # It's probably cleaner to move most of this stuff into Levmar::Func | ||
| 1375 | my $DFP = 0; # routines check for $DFP == 0 to bypass perl wrapper | ||
| 1376 | |||
| 1377 | if ( ref($h->{FUNC}) =~ /CODE/) { # setup perl wrapper stuff | ||
| 1378 | my $jfunc = 0; | ||
| 1379 | $DFP = DFP_create(); | ||
| 1380 | if (defined $h->{JFUNC} and ref($h->{JFUNC}) =~ /CODE/) { | ||
| 1381 | $jfunc = $h->{JFUNC}; | ||
| 1382 | } | ||
| 1383 | if ( $deriv eq 'analytic' and $jfunc == 0 ) { | ||
| 1384 | # warn "No jacobian function supplied, using numeric derivatives"; | ||
| 1385 | $deriv = 'numeric'; | ||
| 1386 | $h->{DERIVATIVE} = 'numeric'; | ||
| 1387 | } | ||
| 1388 | DFP_set_perl_funcs($DFP, $h->{FUNC}, $h->{JFUNC}); | ||
| 1389 | $funcn = $Perl_func_wrapper; | ||
| 1390 | $jacn = $Perl_jac_wrapper; | ||
| 1391 | $sfuncn = $Perl_func_wrapper; # Single and double can use same wrapper | ||
| 1392 | $sjacn = $Perl_jac_wrapper; | ||
| 1393 | } | ||
| 1394 | |||
| 1395 | ############ Do a few sanity checks | ||
| 1396 | |||
| 1397 | if ( $deriv eq 'analytic' ) { | ||
| 1398 | if (not defined $jacn or $jacn == 0 ) { | ||
| 1399 | # warn "No jacobian function supplied, using numeric derivatives"; | ||
| 1400 | $deriv = 'numeric'; | ||
| 1401 | $h->{DERIVATIVE} = 'numeric'; | ||
| 1402 | } | ||
| 1403 | } | ||
| 1404 | elsif ( $deriv ne 'numeric' ) { | ||
| 1405 | croak "DERIVATIVE must be 'analytic' or 'numeric'"; | ||
| 1406 | } | ||
| 1407 | |||
| 1408 | # liblevmar uses 5 option for analytic and 6 for numeric. | ||
| 1409 | my $opts = pdl($p->type, @$h{qw(MU EPS1 EPS2 EPS3)}, | ||
| 1410 | $h->{DERIVATIVE} eq 'analytic' ? () : $h->{DELTA} | ||
| 1411 | ); | ||
| 1412 | # We make an integer option array as well, for passing stuff , like maxits. | ||
| 1413 | my $iopts = pdl(long, $h->{MAXITS}); | ||
| 1414 | |||
| 1415 | ########### FIX holds some parameters constant using linear constraints. | ||
| 1416 | # It is a special case of more general constraints using A and b. | ||
| 1417 | # Notice that this fails if FIX has more than one dimension (ie, you are | ||
| 1418 | # broadcasting. FIXB does the same but using box constraints. | ||
| 1419 | |||
| 1420 | if (defined $h->{FIX} ) { | ||
| 1421 | my $ip = topdl( $h->{FIX}); # take array ref or pdl | ||
| 1422 | if ( chk_eq_dims($ip,$p) < 0 ) { | ||
| 1423 | croak "p and FIX must have the same dimensions"; | ||
| 1424 | } | ||
| 1425 | my $nc = $ip->sum; # number of fixed vars | ||
| 1426 | if ($nc > 0) { | ||
| 1427 | my $A = zeroes($p->type, $m,$nc); | ||
| 1428 | my $b = zeroes($p->type, $nc); | ||
| 1429 | my $j=0; | ||
| 1430 | for(my $i=0; $i<$m; $i++) { | ||
| 1431 | if ($ip->at($i) == 1) { | ||
| 1432 | $A($i,$j) .= 1; | ||
| 1433 | $b($j) .= $p->at($i); | ||
| 1434 | $j++; | ||
| 1435 | } | ||
| 1436 | } | ||
| 1437 | $h->{A} = $A; | ||
| 1438 | $h->{B} = $b; | ||
| 1439 | } | ||
| 1440 | } | ||
| 1441 | elsif ( defined $h->{FIXB} ) { | ||
| 1442 | my $f = topdl( $h->{FIXB}); # take array ref or pdl | ||
| 1443 | if ( chk_eq_dims($f,$p) < 0 ) { | ||
| 1444 | croak "p and FIX must have the same dimensions"; | ||
| 1445 | } | ||
| 1446 | $h->{UB} = ones($p) * $DBLMAX if not defined $h->{UB}; | ||
| 1447 | $h->{LB} = ones($p) * -$DBLMAX if not defined $h->{LB}; | ||
| 1448 | $_ = topdl($_) for @$h{qw(UB LB)}; | ||
| 1449 | my $fi = PDL::Primitive::which($f == 1); # indices in p that we want to fix. | ||
| 1450 | $h->{UB}->flat->index($fi) .= $p->flat->index($fi); | ||
| 1451 | $h->{LB}->flat->index($fi) .= $p->flat->index($fi); | ||
| 1452 | # so ub and lb are now at maximum bounds where not fixed and at value of | ||
| 1453 | # p where fixed | ||
| 1454 | } | ||
| 1455 | my $want_covar = 1; | ||
| 1456 | if ( defined $h->{NOCOVAR} ) { | ||
| 1457 | $want_covar = 0; | ||
| 1458 | } | ||
| 1459 | |||
| 1460 | my $errs = check_levmar_args($h); | ||
| 1461 | if ( @$errs > 0 ) { | ||
| 1462 | # print @$errs; | ||
| 1463 | return {RET => -1, ERRS => $errs }; | ||
| 1464 | } | ||
| 1465 | my ($func_key, $arg_list) = build_constraint_arg_combination($h); | ||
| 1466 | # print "func key '$func_key'\n"; | ||
| 1467 | if ( not defined $func_key ) { | ||
| 1468 | croak "Could not find function key"; | ||
| 1469 | } | ||
| 1470 | if ( not exists $PDL::Fit::Levmar::PDL_Levmar_funcs{$func_key} ) { | ||
| 1471 | croak "Could not find function for key"; | ||
| 1472 | } | ||
| 1473 | my $pdl_levmar_func = $PDL::Fit::Levmar::PDL_Levmar_funcs{$func_key}; | ||
| 1474 | # print "func $pdl_levmar_func\n"; | ||
| 1475 | # my $nargs = @$arg_list; | ||
| 1476 | # print "Got $nargs args\n"; | ||
| 1477 | &$pdl_levmar_func($p,$x,$t,@$arg_list,$iopts,$opts, | ||
| 1478 | $covar, $ret, $pout, $info, $funcn, $sfuncn, | ||
| 1479 | ($h->{DERIVATIVE} eq 'analytic' ? ( $jacn, $sjacn ) : ()), | ||
| 1480 | $DFP, $want_covar); | ||
| 1481 | |||
| 1482 | DFP_free($DFP) if $DFP; | ||
| 1483 | |||
| 1484 | my $hout = { | ||
| 1485 | RET => $ret, | ||
| 1486 | COVAR => $covar, | ||
| 1487 | P => $pout, | ||
| 1488 | ERRI => $info((0)), | ||
| 1489 | ERR1 => $info((1)), | ||
| 1490 | ERR2 => $info((2)), | ||
| 1491 | ERR3 => $info((3)), | ||
| 1492 | ERR4 => $info((4)), | ||
| 1493 | ITS => $info((5)), | ||
| 1494 | REASON => $info((6)), | ||
| 1495 | NFUNC => $info((7)), | ||
| 1496 | NJAC => $info((8)), | ||
| 1497 | NLS => $info((9)), | ||
| 1498 | INFO => $info, | ||
| 1499 | FUNC => $h->{LFUNC}, | ||
| 1500 | }; | ||
| 1501 | return $hout; | ||
| 1502 | |||
| 1503 | } # end levmar() | ||
| 1504 | |||
| 1505 | sub PDL::Fit::Levmar::check_levmar_args { | ||
| 1506 | my ($h) = @_; | ||
| 1507 | my @refargs = qw( LB UB A B C D ); | ||
| 1508 | my @errs = (); | ||
| 1509 | foreach my $argname ( @refargs ) { | ||
| 1510 | if ( exists $h->{$argname} and defined $h->{$argname} ) { | ||
| 1511 | my $arg = $h->{$argname}; | ||
| 1512 | if ( not ref($arg) ) { | ||
| 1513 | push @errs, "$argname must be a pdl or ref to array."; | ||
| 1514 | } | ||
| 1515 | } | ||
| 1516 | } | ||
| 1517 | my @combs = ( [ 'A', 'B' ], [ 'C', 'D' ] ); | ||
| 1518 | foreach my $comb (@combs ) { | ||
| 1519 | my $n = @$comb; | ||
| 1520 | my $nf = 0; | ||
| 1521 | foreach my $arg ( @$comb ) { | ||
| 1522 | $nf++ if exists $h->{$arg} and defined $h->{$arg}; | ||
| 1523 | } | ||
| 1524 | if ( $nf != 0 and $n != $nf ) { | ||
| 1525 | push @errs, 'none or all of ' . join(' and ',@$comb) . ' must be defined.'; | ||
| 1526 | } | ||
| 1527 | } | ||
| 1528 | return \@errs; | ||
| 1529 | } | ||
| 1530 | |||
| 1531 | |||
| 1532 | # make a list of strings of names of constraint args that | ||
| 1533 | # have been passed. | ||
| 1534 | # hash is arg hash to top level call | ||
| 1535 | sub PDL::Fit::Levmar::build_constraint_arg_combination { | ||
| 1536 | my ($h) = @_; | ||
| 1537 | my @arg_comb = (); | ||
| 1538 | my @arg_list = (); | ||
| 1539 | # order is important in following | ||
| 1540 | my @possible_args = qw( LB UB A B C D ); | ||
| 1541 | foreach ( @possible_args ) { | ||
| 1542 | my $ucarg = $_; | ||
| 1543 | # $ucarg =~ tr/a-z/A-Z/; # should rewrite so that tr not needed | ||
| 1544 | if ( exists $h->{$ucarg} and defined $h->{$ucarg} ) { | ||
| 1545 | push @arg_comb, $_; | ||
| 1546 | push @arg_list, topdl($h->{$ucarg}); | ||
| 1547 | } | ||
| 1548 | } | ||
| 1549 | my $deriv_type; | ||
| 1550 | if ($h->{DERIVATIVE} eq 'analytic' ) { | ||
| 1551 | $deriv_type = 'DER'; | ||
| 1552 | } | ||
| 1553 | else { | ||
| 1554 | $deriv_type = 'DIFF'; | ||
| 1555 | } | ||
| 1556 | push @arg_list, topdl($h->{WGHTS}) if exists $h->{WGHTS} and defined $h->{WGHTS}; | ||
| 1557 | my $fk = make_pdl_levmar_func_key(make_hash_key_from_arg_comb(\@arg_comb), $deriv_type); | ||
| 1558 | return ($fk,\@arg_list); | ||
| 1559 | } | ||
| 1560 | |||
| 1561 | sub PDL::Fit::Levmar::make_hash_key_from_arg_comb { | ||
| 1562 | my ( $arg_comb ) = @_; | ||
| 1563 | return join( '_', @$arg_comb); | ||
| 1564 | } | ||
| 1565 | |||
| 1566 | sub PDL::Fit::Levmar::make_pdl_levmar_func_key { | ||
| 1567 | my ($arg_str, $deriv_type) = @_; | ||
| 1568 | return $deriv_type . '_' . $arg_str; | ||
| 1569 | } | ||
| 1570 | |||
| 1571 | %PDL::Fit::Levmar::PDL_Levmar_funcs = ( | ||
| 1572 | DER_ => \&PDL::levmar_der_, | ||
| 1573 | DIFF_ => \&PDL::levmar_diff_, | ||
| 1574 | DER_LB_C_D => \&PDL::levmar_der_lb_C_d, | ||
| 1575 | DIFF_LB_C_D => \&PDL::levmar_diff_lb_C_d, | ||
| 1576 | DER_A_B => \&PDL::levmar_der_A_b, | ||
| 1577 | DIFF_A_B => \&PDL::levmar_diff_A_b, | ||
| 1578 | DER_UB_A_B => \&PDL::levmar_der_ub_A_b, | ||
| 1579 | DIFF_UB_A_B => \&PDL::levmar_diff_ub_A_b, | ||
| 1580 | DER_UB => \&PDL::levmar_der_ub, | ||
| 1581 | DIFF_UB => \&PDL::levmar_diff_ub, | ||
| 1582 | DER_A_B_C_D => \&PDL::levmar_der_A_b_C_d, | ||
| 1583 | DIFF_A_B_C_D => \&PDL::levmar_diff_A_b_C_d, | ||
| 1584 | DER_LB_UB_A_B_C_D => \&PDL::levmar_der_lb_ub_A_b_C_d, | ||
| 1585 | DIFF_LB_UB_A_B_C_D => \&PDL::levmar_diff_lb_ub_A_b_C_d, | ||
| 1586 | DER_LB => \&PDL::levmar_der_lb, | ||
| 1587 | DIFF_LB => \&PDL::levmar_diff_lb, | ||
| 1588 | DER_LB_A_B_C_D => \&PDL::levmar_der_lb_A_b_C_d, | ||
| 1589 | DIFF_LB_A_B_C_D => \&PDL::levmar_diff_lb_A_b_C_d, | ||
| 1590 | DER_UB_A_B_C_D => \&PDL::levmar_der_ub_A_b_C_d, | ||
| 1591 | DIFF_UB_A_B_C_D => \&PDL::levmar_diff_ub_A_b_C_d, | ||
| 1592 | DER_LB_UB => \&PDL::levmar_der_lb_ub, | ||
| 1593 | DIFF_LB_UB => \&PDL::levmar_diff_lb_ub, | ||
| 1594 | DER_LB_A_B => \&PDL::levmar_der_lb_A_b, | ||
| 1595 | DIFF_LB_A_B => \&PDL::levmar_diff_lb_A_b, | ||
| 1596 | DER_UB_C_D => \&PDL::levmar_der_ub_C_d, | ||
| 1597 | DIFF_UB_C_D => \&PDL::levmar_diff_ub_C_d, | ||
| 1598 | DER_LB_UB_A_B => \&PDL::levmar_der_lb_ub_A_b, | ||
| 1599 | DIFF_LB_UB_A_B => \&PDL::levmar_diff_lb_ub_A_b, | ||
| 1600 | DER_LB_UB_C_D => \&PDL::levmar_der_lb_ub_C_d, | ||
| 1601 | DIFF_LB_UB_C_D => \&PDL::levmar_diff_lb_ub_C_d, | ||
| 1602 | DER_C_D => \&PDL::levmar_der_C_d, | ||
| 1603 | DIFF_C_D => \&PDL::levmar_diff_C_d, | ||
| 1604 | ); | ||
| 1605 | |||
| 1606 | sub levmar_chkjac { | ||
| 1607 | my ($f,$p,$t) = @_; | ||
| 1608 | my $r = ref $f; | ||
| 1609 | if ( not $r =~ /Levmar::Func/ ) { | ||
| 1610 | warn "levmar_chkjac: not a Levmar::Func object "; | ||
| 1611 | return; | ||
| 1612 | } | ||
| 1613 | my $N; | ||
| 1614 | if ( not ref($t) =~ /PDL/ ) { | ||
| 1615 | $N = $t; # in case there is no t for this func | ||
| 1616 | $t = zeroes( $p->type, 1); just some pdl | ||
| 1617 | } | ||
| 1618 | my $DFP = 0; | ||
| 1619 | my ($funcn,$sfuncn,$jacn,$sjacn); | ||
| 1620 | if ( ref($f->{FUNC}) =~ /CODE/) { # setup perl wrapper stuff | ||
| 1621 | my $jfunc = 0; | ||
| 1622 | $DFP = DFP_create(); | ||
| 1623 | if (not (defined $f->{JFUNC} and ref($f->{FUNC}) =~ /CODE/ ) ) { | ||
| 1624 | warn "levmar_chkjac: no perl code jacobian supplied in JFUNC."; | ||
| 1625 | return undef; | ||
| 1626 | } | ||
| 1627 | DFP_set_perl_funcs($DFP, $f->{FUNC}, $f->{JFUNC}); | ||
| 1628 | $funcn = $Perl_func_wrapper; | ||
| 1629 | $jacn = $Perl_jac_wrapper; | ||
| 1630 | $sfuncn = $Perl_func_wrapper; | ||
| 1631 | $sjacn = $Perl_jac_wrapper; | ||
| 1632 | } | ||
| 1633 | else { # pointers to native c functions. | ||
| 1634 | ($funcn,$sfuncn,$jacn,$sjacn) = | ||
| 1635 | $f->get_fit_pointers(); | ||
| 1636 | } | ||
| 1637 | my $err; | ||
| 1638 | if ( defined $N ) { | ||
| 1639 | $err = _levmar_chkjac_no_t($p,$funcn,$sfuncn,$jacn,$sjacn,$N,$DFP); | ||
| 1640 | } | ||
| 1641 | else { | ||
| 1642 | $err = _levmar_chkjac($p,$t,$funcn,$sfuncn,$jacn,$sjacn,$DFP); | ||
| 1643 | } | ||
| 1644 | DFP_free($DFP); | ||
| 1645 | return $err; | ||
| 1646 | } | ||
| 1647 | #line 1648 "Levmar.pm" | ||
| 1648 | |||
| 1649 | *levmar_der_lb = \&PDL::levmar_der_lb; | ||
| 1650 | |||
| 1651 | |||
| 1652 | |||
| 1653 | |||
| 1654 | *levmar_der_ub = \&PDL::levmar_der_ub; | ||
| 1655 | |||
| 1656 | |||
| 1657 | |||
| 1658 | |||
| 1659 | *levmar_der_ = \&PDL::levmar_der_; | ||
| 1660 | |||
| 1661 | |||
| 1662 | |||
| 1663 | |||
| 1664 | *levmar_der_lb_ub = \&PDL::levmar_der_lb_ub; | ||
| 1665 | |||
| 1666 | |||
| 1667 | |||
| 1668 | |||
| 1669 | *levmar_diff_lb = \&PDL::levmar_diff_lb; | ||
| 1670 | |||
| 1671 | |||
| 1672 | |||
| 1673 | |||
| 1674 | *levmar_diff_ub = \&PDL::levmar_diff_ub; | ||
| 1675 | |||
| 1676 | |||
| 1677 | |||
| 1678 | |||
| 1679 | *levmar_diff_ = \&PDL::levmar_diff_; | ||
| 1680 | |||
| 1681 | |||
| 1682 | |||
| 1683 | |||
| 1684 | *levmar_diff_lb_ub = \&PDL::levmar_diff_lb_ub; | ||
| 1685 | |||
| 1686 | |||
| 1687 | |||
| 1688 | |||
| 1689 | *_levmar_chkjac = \&PDL::_levmar_chkjac; | ||
| 1690 | |||
| 1691 | |||
| 1692 | |||
| 1693 | |||
| 1694 | *_levmar_chkjac_no_t = \&PDL::_levmar_chkjac_no_t; | ||
| 1695 | |||
| 1696 | |||
| 1697 | |||
| 1698 | |||
| 1699 | |||
| 1700 | |||
| 1701 | |||
| 1702 | #line 1132 "levmar.pd" | ||
| 1703 | |||
| 1704 | =head1 AUTHORS | ||
| 1705 | |||
| 1706 | PDL code for Levmar Copyright (C) 2006 John Lapeyre. C | ||
| 1707 | library code Copyright (C) 2006 Manolis Lourakis, licensed | ||
| 1708 | here under the Gnu Public License. | ||
| 1709 | |||
| 1710 | All rights reserved. There is no warranty. You are allowed | ||
| 1711 | to redistribute this software / documentation under certain | ||
| 1712 | conditions. For details, see the file COPYING in the PDL | ||
| 1713 | distribution. If this file is separated from the PDL | ||
| 1714 | distribution, the copyright notice should be included in the | ||
| 1715 | file. | ||
| 1716 | |||
| 1717 | =cut | ||
| 1718 | #line 1719 "Levmar.pm" | ||
| 1719 | |||
| 1720 | # Exit with OK status | ||
| 1721 | |||
| 1722 | 1; | ||