levmar.pd

filter: Statementstmt 81.5% 212 / 260 Branchbran 68.8% 106 / 154 Conditioncond 72.0% 54 / 75 MC/DCmcdc 51.1% 23 / 45 Subroutinesub 88.2% 15 / 17 Podpod 27.2% 3 / 11 totaltotal 73.4% 413 / 562 CC 113 SCAR 49.9
CC
113
Cov
76%
levmar
212.2
check_levmar_args
14.1
levmar_chkjac
8.7
CRAP 147.1
↑ Summary Func/func.pd »
1 # -*-Perl-*- # for emacs
2 use strict;
3 use warnings;
4 use Carp;
5  
6 our $VERSION = '0.0111';
7 pp_setversion( $VERSION );
8  
9  
10 our $HAVE_LAPACK;
11 require './have_lapack';
12 #print "HAVE_LAPACK = $HAVE_LAPACK\n";
13  
14 pp_addpm({At=>'Top'},<<'===EOD===top_pm===');
15  
16 =head1 NAME
17  
18 PDL::Fit::Levmar - Levenberg-Marquardt fit/optimization routines
19  
20 =head1 DESCRIPTION
21  
22 Levenberg-Marquardt routines for least-squares fit to
23 functions non-linear in fit parameters.
24  
25 This module provides a L<PDL> interface to the non-linear fitting
26 library levmar 2.6 (written in C). Levmar is
27 L<broadcast|/example--6> aware, provides support for analytic
28 or finite difference derivatives (in case no analytic
29 derivatives are supplied), L<linear|/A> and/or L<box|/UB>
30 and/or L<inequality|/C>
31 constraints (with L<parameter fixing|/FIX> as a special
32 case) and pure single or double precision computation. The
33 routines are re-entrant, so they can be used in
34 multi-threaded applications (not tested!). Levmar is suited
35 both for data fitting and for optimization problems.
36  
37 The source code for the C levmar library is included in this
38 distribution. However, linearly-constrained fitting requires
39 that C<PDL::Fit::Levmar> be built with support for B<lapack>
40 and B<blas> libraries. See the files F<INSTALL> and
41 F<Makefile.PL>, for more information. If
42 C<PDL::Fit::Levmar> is built without support for C<lapack>,
43 the fitting options C<A>, C<B>, C<C>, C<D>, and C<FIX> may
44 not be used. All other options, including C<FIXB>, do not
45 require C<lapack>.
46  
47 User supplied fit functions can be written in perl code that
48 takes pdls as arguments, or, for efficiency, in in a simple
49 function description language (C<lpp>), which is rapidly and
50 transparently translated to C, compiled, and dynamically
51 linked. Fit functions may also be written in pure C. If C
52 or C<lpp> fit functions are used, the entire fitting
53 procedure is done in pure compiled C. The compilation and
54 linking is done only the first time the function is defined.
55  
56 There is a document distributed with this module
57 F<./doc/levmar.pdf> by the author of liblevmar describing
58 the fit algorithms. Additional information on liblevmar is available at
59 L<http://www.ics.forth.gr/~lourakis/levmar/>
60  
61 Don't confuse this module with, but see also, L<PDL::Fit::LM>.
62  
63 =head1 SYNOPSIS
64  
65 use PDL::Fit::Levmar;
66 $result_hash = levmar($params,$x,$t, FUNC => '
67 function somename
68 x = p0 * exp(-t*t * p1);');
69 print levmar_report($result_hash);
70  
71  
72 =head1 EXAMPLES
73  
74  
75 A number of examples of invocations of C<levmar> follow. The test
76 directory C<./t> in the module distribution contains many more examples.
77 The following seven examples are included as stand-alone scripts in the
78 ./examples/ directory. Some of the necessary lines are not repeated in
79 each example below.
80  
81 =over 3
82  
83 =item example--1
84  
85 In this example we fill co-ordinate $t and ordinate $x arrays
86 with 100 pairs of sample data. Then we call the fit routine
87 with initial guesses of the parameters.
88  
89 use PDL::LiteF;
90 use PDL::Fit::Levmar;
91 use PDL::NiceSlice;
92
93 $n = 100;
94 $t = 10 * (sequence($n)/$n -1/2);
95 $x = 3 * exp(-$t*$t * .3 );
96 $p = pdl [ 1, 1 ]; # initial parameter guesses
97  
98 $h = levmar($p,$x,$t, FUNC =>
99 ' function
100 x = p0 * exp( -t*t * p1);
101 ');
102 print levmar_report($h);
103  
104 This example gives the output:
105  
106 Estimated parameters: [ 3 0.3]
107 Covariance:
108 [
109 [5.3772081e-25 7.1703376e-26]
110 [7.1703376e-26 2.8682471e-26]
111 ]
112  
113 ||e||_2 at initial parameters = 125.201
114 Errors at estimated parameters:
115 ||e||_2 = 8.03854e-22
116 ||J^T e||_inf = 2.69892e-05
117 ||Dp||_2 = 3.9274e-15
118 \mu/max[J^T J]_ii ] = 1.37223e-05
119 number of iterations = 15
120 reason for termination: = stopped by small ||e||_2
121 number of function evaluations = 20
122 number of jacobian evaluations = 2
123  
124 In the example above and all following examples, it is necessary
125 to include the three C<use> statements at the top of the file.
126 The fit function in this example is in C<lpp> code.
127 The parameter pdl $p is the input parameters (guesses)
128 levmar returns a hash with several elements including a
129 plain text report of the fit, which we chose to print.
130  
131 The interface is flexible-- we could have also called levmar like this
132  
133 $h = levmar($p,$x,$t, ' function
134 x = p0 * exp( -t*t * p1);
135 ');
136  
137 or like this
138  
139 $h = levmar(P =>$p, X => $x, T=> $t, FUNC => ' function
140 x = p0 * exp( -t*t * p1);
141 ');
142  
143 After the fit, the input parameters $p are left
144 unchanged. The output hash $h contains, among other things,
145 the optimized parameters in $h->{P}.
146  
147 =item example--2
148  
149 Next, we do the same fit, but with a perl/PDL fit function.
150  
151 $h = levmar($p,$x,$t, FUNC => sub {
152 my ($p,$x,$t) = @_;
153 my ($p0,$p1) = list $p;
154 $x .= $p0 * exp(-$t*$t * $p1);
155 });
156  
157 Using perl code (second example) results in slower execution
158 than using pure C (first example). How much slower depends
159 on the problem (see L</IMPLEMENTATION> below). See also the
160 section on L<perl subroutines|/Perl_Subroutines>.
161  
162 =item example--3
163  
164 Next, we solve the same problem using a C fit routine.
165  
166 levmar($p,$x,$t, FUNC => '
167 #include <math.h>
168 void gaussian(FLOAT *p, FLOAT *x, int m, int n, FLOAT *t)
169 {
170 int i;
171 for(i=0; i<n; ++i)
172 x[i] = p[0] * exp( -t[i]*t[i] * p[1]);
173 }
174 ');
175  
176 The macro C<FLOAT> is used rather than float or double because
177 the C code will be used for both single and double precision
178 routines. ( The code is automatically compiled twice; once
179 with C<FLOAT> expanded to double and once expanded to float)
180 The correct version is used automatically depending on the
181 type of pdls you give levmar.
182  
183  
184 =item example--4
185  
186 We supply an analytic derivative ( analytic jacobian).
187  
188 $st = '
189 function
190 x = p0 * exp( -t*t * p1);
191  
192 jacobian
193 FLOAT ex, arg;
194 loop
195 arg = -t*t * p1;
196 ex = exp(arg);
197 d0 = ex;
198 d1 = -p0 * t*t * ex ;
199  
200 ';
201  
202 $h = levmar($p,$x,$t, FUNC => $st);
203  
204 If no jacobian function is supplied, levmar automatically
205 uses numeric difference derivatives. You can also explicitly
206 use numeric derivatives with the option C<DERIVATIVE>
207 C<< => 'numeric' >>.
208  
209 Note that the directives C<function> and C<jacobian> begin
210 the function definitions. You can also supply a name if
211 you like, eg. C<function john> and C<jacobian mary>.
212  
213 In C<lpp>, the co-ordinate data is always identified by 't', the
214 ordinate data by 'x' in the fit function and by 'dn', with n a
215 number, in the jacobian. The parameters are identified by
216 'p'. All other identifiers are pure C identifiers and
217 must be defined, as are C<ex> and C<arg> in the example.
218  
219 Referring to the example above, if the directive C<loop> appears
220 on a line by itself, code after it is wrapped in a loop over
221 the data; code before it is not. If C<loop> does not appear,
222 then all the code is wrapped in a loop. 'loop' must occur zero
223 or one times in each of the fit and jacobian definitions.
224 For some problems, you will not want a loop at all. In this
225 case the directive C<noloop> is placed after the declarations.
226  
227 To see what C<lpp> does, pass the option C<NOCLEAN> C<< => 1 >> to levmar
228 and look at the C source file that is written.
229  
230 When defining the derivatives above (d0, d1) etc., you must
231 put the lines in the proper order ( eg, not d1,d0 ). (This
232 is for efficiency, see the generated C code.)
233  
234 One final note on this example-- we declared C<ex> and C<arg> to
235 be type C<FLOAT>. Because they are temporary variables, we could
236 have hard coded them to double, in which case both the float
237 and double code versions would have used type double for them.
238 This is ok, because it doesn't cost any storage or cause
239 a memory fault because of incorrect pointer arithmetic.
240  
241  
242 =item example--5
243  
244 Here is an example from the liblevmar demo program that shows
245 one more bit of C<lpp> syntax.
246  
247 $defst = "
248 function modros
249 noloop
250 x0 = 10 * (p1 -p0*p0);
251 x1 = 1.0 - p0;
252 x2 = 100;
253 jacobian jacmodros
254 noloop
255 d0[0] = -20 * p0;
256 d1[0] = 10;
257 d0[1] = -1;
258 d1[1] = 0;
259 d0[2] = 0;
260 d1[2] = 0;
261 ";
262 $p = pdl [-1.2, 1];
263 $x = pdl [0,0,0];
264 $h = levmar( $p,$x, FUNC => $defst );
265  
266 The directive C<noloop> mentioned above has been used,
267 indicating that there are no implied loops in the
268 function. Note that this model function is designed only for
269 $x->nelem == 3. The additional syntax is in the
270 derivatives. Keeping in mind that there is no loop variable,
271 dq[r] means derivative w.r.t q evaluated at x[r]. (This is
272 translated by C<lpp> to d[q+r*m], which is the index into a
273 1-d array.)
274  
275 =item example--6
276  
277 Here is an example that uses implicit broadcasting. We create data
278 from a gaussian function with four different sets of parameters
279 and fit it all in one function call.
280  
281 $st = '
282 function
283 x = p0 * exp( -t*t * p1);
284 ';
285  
286 $n = 10;
287 $t = 10 * (sequence($n)/$n -1/2);
288 $x = zeroes($n,4);
289 map { $x(:,$_->[0]) .= $_->[1] * exp(-$t*$t * $_->[2] ) }
290 ( [0,3,.2], [1, 28, .1] , [2,2,.01], [3,3,.3] );
291 $p = [ 5, 1]; # initial guess
292 $h = levmar($p,$x,$t, FUNC => $st );
293 print $h->{P} . "\n";
294  
295 [
296 [ 3 0.2]
297 [ 28 0.1]
298 [ 2 0.01]
299 [ 3 0.3]
300 ]
301  
302  
303 =item example--7
304  
305 This example shows how to fit a bivariate Gaussian. Here
306 is the fit function.
307  
308 sub gauss2d {
309 my ($p,$xin,$t) = @_;
310 my ($p0,$p1,$p2) = list $p;
311 my $n = $t->nelem;
312 my $t1 = $t(:,*$n); # first coordinate
313 my $t2 = $t(*$n,:); # second coordinate
314 my $x = $xin->splitdim(0,$n);
315 $x .= $p0 * exp( -$p1*$t1*$t1 - $p2*$t2*$t2);
316 }
317  
318  
319 We would prefer a function that maps t(n,n) --> x(n,n) (with
320 p viewed as parameters.) But the levmar library expects one
321 dimensional x and t. So we design C<gauss2d> to take
322 ndarrays with these dimensions: C<p(3)>, C<xin(n*n)>,
323 C<t(n)>. For this example, we assume that both the co-ordinate
324 axes run over the same range, so we only need to pass n
325 values for t. The ndarrays t1 and t2 are (virtual) copies of
326 t with dummy dimensions inserted. Each represents
327 co-ordinate values along each of the two axes at each point
328 in the 2-d space, but independent of the position along the
329 other axis. For instance C<t1(i,j) == t(i)> and C<t1(i,j)
330 == t(j)>. We assume that the ndarray xin is a flattened
331 version of the ordinate data, so we split the dimensions in
332 x. Then the entire bi-variate gaussian is calculated with
333 one line that operates on 2-d matrices. Now we create some
334 data,
335  
336 my $n = 101; # number of data points along each axis
337 my $scale = 3; # range of co-ordiate data
338 my $t = sequence($n); # co-ordinate data (used for both axes)
339 $t *= $scale/($n-1);
340 $t -= $scale/2; # rescale and shift.
341 my $x = zeroes($n,$n);
342 my $p = pdl [ .5,2,3]; # actual parameters
343 my $xlin = $x->clump(-1); # flatten the x data
344 gauss2d( $p, $xlin, $t->copy); # compute the bivariate gaussian data.
345  
346 Now x contains the ordinate data (so does xlin, but in a flattened shape.)
347 Finally, we fit the data with an incorrect set of initial parameters,
348  
349 my $p1 = pdl [ 1,1,1]; # not the parameters we used to make the data
350 my $h = levmar($p1,$xlin,$t,\&gauss2d);
351  
352 At this point C<$h->{P}> refers to the output parameter ndarray C<[0.5, 2, 3]>.
353  
354 =back
355  
356 =head1 CONSTRAINTS
357  
358 Several of the options below are related to constraints. There are
359 three types: box, linear equation, and linear inequality. They may
360 be used in any combination. (But there is no testing if
361 there is a possible solution.) None or one or two of C<UB> and C<LB> may be
362 specified. None or both of C<A> and C<B> may be specified.
363 None or both of C<C> and C<D> may be specified.
364  
365 =head1 OPTIONS
366  
367 It is best to learn how to call levmar by looking at the
368 examples first, and looking at this section later.
369  
370 levmar() is called like this
371  
372 levmar($arg1, $arg2, ..., OPT1=>$val1, OPT2=>$val2, ...);
373 or this:
374 levmar($arg1, $arg2, ..., {OPT1=>$val1, OPT2=>$val2, ...});
375  
376 When calling levmar, the first 3 ndarray arguments (or refs
377 to arrays), if present, are taken to be C<$p>,C<$x>, and C<$t>
378 (parameters, ordinate data, and co-ordinate data) in that
379 order. The first scalar value that can be interpreted as a
380 function will be. Everything else must be passed as an
381 option in a key-value pair. If you prefer, you can pass some
382 or all of C<$p,$x,$t> and the function as key-values in the
383 hash. Note that after the first key-value pair, you cannot
384 pass any more non-hash arguments. The following calls are equivalent
385 (where $func specifies the function as described in L</FUNC> ).
386  
387 levmar($p, $x, $t, $func);
388 levmar($func,$p, $x, $t);
389 levmar($p, $x, $t, FUNC=> $func);
390 levmar($p, $x, T=>$t, FUNC => $func);
391 levmar($p, X=>$x, T=>$t, FUNC => $func);
392 levmar(P=>$p, X=>$x, T=>$t, FUNC => $func);
393  
394 In the following, if the default value is not mentioned, it is undef.
395 C<$outh> refers to the output hash.
396  
397 Some of these options are actually options to Levmar::Func.
398 All options to Levmar::Func may by given in calls to levmar().
399  
400 =over 4
401  
402 =item FUNC
403  
404 This option is required (but it can be passed before the
405 options hash without the key C<FUNC> ) It can be
406 any of the following, which are auto-detected.
407  
408 a string containing lpp code
409 a string containing pure C code
410 the filename of a file containing lpp code (which must end in '.lpp' )
411 the filename of a file containing pure C code ( which must end in '.c' )
412 a reference to perl code
413 a reference to a previously created Levmar::Func object (which was
414 previously created via one of the preceeding methods.)
415  
416 If you are fitting a lot of data by doing many iterations over
417 a loop of perl code, it is by far most efficient to create a Func
418 object from C or lpp code and pass it to levmar. (Implicit broadcasting
419 does not recompile code in any case.)
420  
421 You can also pass pure C code via the option CSRC.
422  
423 =item JFUNC
424  
425 This parameter is the jacobian as a ref to perl CODE. For
426 C and C<lpp> code, the jacobian, if present, is always in the
427 same source file as the fit function; in this case, you
428 should leave C<JFUNC> undefined. See L</Perl_Subroutines>
429  
430 =item DERIVATIVE
431  
432 This takes the value 'numeric' or 'analytic'. If it is
433 set to 'analytic', but no analytic jacobian of the model
434 function is supplied, then the numeric algorithms will be used
435 anyway.
436  
437 =item NOCLEAN
438  
439 If defined (NOCLEAN => 1), files containing generated C
440 object and dynamic library code are not deleted. If not
441 defined, these files are deleted after they are no longer
442 needed. For the source and object (.c and .o) files, this
443 means immediately after the dynamic library (.so) is built.
444 The dynamic library file is deleted when the corresponding
445 Levmar::Func object is destroyed. (It could be deleted after
446 it is loaded, I suppose, and then be rebuilt if needed
447 again)
448  
449 =item FIX
450  
451 Example: Fix => [1,0,0,1,0].
452 This option takes a pdl (or array ref) of the same shape as
453 the parameters $p. Each element must have the value zero or
454 one. A zero corresponds to a free parameter and a one to a
455 fixed parameter. The best fit is found keeping the fixed
456 parameters at their input values and letting the free
457 parameters vary. This is implemented by using the linear
458 constraint option described below. Each element must be
459 either one or zero. This option currently cannot be
460 broadcasted. That is, if the array FIX has more than one
461 dimension you will not get correct results. Also, PDL will
462 not add dimension correctly if you pass additional
463 dimensions in other quantities. Threading will work if you
464 use linear constraints directly via C<A> and C<b>.
465  
466 =item FIXB
467  
468 This option is almost the same as FIX. It takes the same
469 values with the same meanings. It fixes parameters at the value
470 of the input parameters, but uses
471 box constraints, i.e., UB and LB rather than linear
472 constraints A and B. You can specify all three of UB,LB, and FIXB.
473 In this case, first box constraints determined by UB and LB are applied
474 Then, for those elements of FIXB with value one, the corresponding
475 values of UB and LB are overridden.
476  
477 =item A
478  
479 Example: A =>pdl [ [1,0], [0,1] ] , B => pdl [ 1,2 ]
480  
481 Minimize with linear constraints $A x $p = $b. That is,
482 parameters $p are optimized over the subset of parameters
483 that solve the equation. The dimensions of the quantities
484 are A(k,m), b(m), p(m), where k is the number of
485 constraints. ( k <= m ). Note that $b is a vector (it has one
486 fewer dimensions than A), but the option key is a capital 'B'.
487  
488 =item B
489  
490 See C<A>.
491  
492 =item UB
493  
494 Example: UB => [10,10,10], LB => [-10,0,-5].
495 Box constraints. These have the same shape as the parameter
496 pdl $p. The fit is done with ub forming upper bounds and lb
497 lower bounds on the parameter values. Use, for instance
498 PDL::Fit::Levmar::get_dbl_max() for parameters that you
499 don't want bounded. You can use either linear constraints or
500 box constraints, or both. That is, you may specify A, B, UB, and LB.
501  
502 =item LB
503  
504 See C<UB>.
505  
506  
507 =item WGHTS
508  
509 Penalty weights can be given optionally when box and linear equality
510 constraints are both passed to levmar. See the levmar documenation for
511 how to use this. Note that if C and D are used then the WGHTS must
512 not passed.
513  
514 =item C
515  
516 Example: C => [ [ -1, -2, -1, -1], [ -3, -1, -2, 1] ], D => [ -5, -0.4]
517 Linear inequality constraints. Minimize with constraints $C x $p >= $d.
518 The dimensions are C(k2,m), D(m), p(m).
519  
520 =item D
521  
522 See C<C>
523  
524 =item P
525  
526 Keys P, X, and T can be used to send to the parameters, ordinates and coordinates.
527 Alternatively, you can send them as non-option arguments to levmar before
528 the option arguments.
529  
530 =item X
531  
532 See C<P>
533  
534 =item T
535  
536 See C<P>
537  
538 =item DIR
539  
540 The directory containing files created when compiling C<lpp>
541 and C fit functions. This defaults to being created by
542 L<File::Temp/tempdir>. The .c,
543 .o, and .so files will be written to this directory. This
544 option actually falls through to levmar_func. Such options
545 should be in separate section, or otherwise noted.
546  
547 =item GETOPTS
548  
549 If defined, return a ref to a hash containing the default
550 values of the parameters.
551  
552 =item COVAR
553  
554 Send a pdl reference for the output hash element COVAR. You may
555 want to test if this option is more efficient for
556 some problem. But unless the covariance matrix is very large,
557 it probably won't help much. On the other hand it almost certainly
558 won't make levmar() less efficient.
559  
560 Note that levmar returns an ndarray representing the covariance in
561 the output hash. This will be the the same ndarray that you give
562 as input via this option. So, if you do the following,
563  
564 my $covar = PDL->null
565 my $h =levmar(...., COVAR => $covar);
566  
567 then $covar and $h->{COVAR} are references to the same
568 pdl. The storage for the pdl will not be destroyed until
569 both $covar and $h->{COVAR} become undefined.
570  
571 =item NOCOVAR
572  
573 If defined, no covariance matrix is computed.
574  
575 =item POUT
576  
577 Send a pdl reference for the output hash element P. Don't
578 confuse this with the option P which can be used to send the
579 initial guess for the parameters (see C<COVAR>).
580  
581 =item INFO
582  
583 Send a pdl reference for the output hash element C<INFO>.
584 (see C<COVAR>)
585  
586 =item RET
587  
588 Send a pdl reference for the output hash element C<RET>.
589 (see C<COVAR>)
590  
591  
592 =item MAXITS
593  
594 Maximum number of iterations to try before giving up. The default
595 is 100.
596  
597 =item MU
598  
599 The starting value of the parameter mu in the L-M algorithm.
600  
601 =item EPS1, EPS2, EPS3
602  
603 Stopping thresholds for C<||J^T e||_inf>, C<||Dp||_2> and
604 C<||e||_2>. (see the document levmar.pdf by the author of
605 liblevmar and distributed with this module) The algorithm
606 stops when the first threshold is reached (or C<MAXITS> is reached). See
607 C<REASON> for determining which threshold was reached.
608  
609 Here, C<e> is a the vector of errors between the data and
610 the model function and C<p> is the vector of parameters.
611 S<||J^T e||_inf> is the gradient of C<e> w.r.t C<p>
612 at the current estimate of C<p>; C<||Dp||_2> is the amount
613 by which C<p> is currently being shifted at each iteration;
614 C<||e||_2> is a measure of the error between the model function
615 at the current estimate for C<p> and the data.
616  
617 =item DELTA
618  
619 This is a step size used in computing numeric derivatives. It is
620 not used if the analytic jacobian is used.
621  
622  
623 =item MKOBJ
624  
625 command to compile source into object code. This option is actually set in
626 the Levmar::Func object, but can be given in calls to levmar().
627 The default value is determined by the perl installation and can
628 be determined by examining the Levmar::Func object returned by
629 new or the output hash of a call to levmar. A typical value is
630 cc -c -O2 -fPIC -o %o %c
631  
632 =item MKSO
633  
634 command to convert object code to dynamic library code.
635 This option is actually set in the Levmar::Func object. A
636 typical default value is
637 cc -shared -L/usr/local/lib -fstack-protector %o -o %s
638  
639 =item CTOP
640  
641 The value of this string will be written at the top of the c code
642 written by Levmar::Func. This can be used to include headers and so forth.
643 This option is actually set in the Levmar::Func object. This code is also written
644 at the top of c code translated from lpp code.
645  
646  
647 =item FVERBOSE
648  
649 If true (eg 1) Print the compiling and linking commands to STDERR when compiling fit functions.
650 This option is actually passed to Levmar::Func. Default is 0.
651  
652 =item Default values
653  
654 Here are the default values
655 of some options
656  
657  
658 $Levmar_defaults = {
659 FUNC => undef, # Levmar::Func object, or function def, or ...
660 JFUNC => undef, # must be ref to perl sub
661 MAXITS => 100, # maximum iterations
662 MU => LM_INIT_MU, # These are described in levmar docs
663 EPS1 => LM_STOP_THRESH,
664 EPS2 => LM_STOP_THRESH,
665 EPS3 => LM_STOP_THRESH,
666 DELTA => LM_DIFF_DELTA,
667 DERIVATIVE => 'analytic',
668 FIX => undef,
669 A => undef,
670 B => undef,
671 C => undef,
672 D => undef,
673 UB = undef,
674 LB => undef,
675 X => undef,
676 P => undef,
677 T => undef,
678 WGHTS => undef,
679 # meant to be private
680 LFUNC => undef, # only Levmar::Func object, made from FUNC
681 };
682  
683 =back
684  
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  
728 =item ERRI, ERR1, ERR2, ERR3, ERR4
729  
730 ERRI is C<||e||_2> at the initial paramters. ERR1 through
731 ERR3 are the actual values on termination of the quantities
732 corresponding to the thresholds EPS1 through EPS3 described
733 in the options section. ERR4 is C<mu/max[J^T J]_ii>
734  
735 =item ITS
736  
737 Number of iterations performed
738  
739 =item NFUNC, NJAC, NLS
740  
741 Number of function evaluations, number of jacobian evaluations
742 and number of linear systems solved.
743  
744 =item INFO
745  
746 Array containing ERRI,ERR1, ..., ERR4, ITS, REASON, NFUNC, NJAC, NLS.
747  
748 =back
749  
750 =head1 FIT FUNCTIONS
751  
752 Fit functions, or model functions can be specified in the following
753 ways.
754  
755 =over 3
756  
757 =item lpp
758  
759 It is easier to learn to use C<lpp> by reading the C<EXAMPLES> section.
760  
761 C<lpp> processes a function definition into C code. It writes
762 the opening and closing parts of the function, alters a
763 small number of identifiers if they appear, and wraps some
764 of the code in a loop. C<lpp> recognizes four directives. They
765 must occur on a line with nothing else, not even comments.
766  
767 First, the directives are explained, then the substitutions.
768 The directive lines have a strict format. All other lines
769 can contain any C code including comments and B<cpp>
770 macros. They will be written to a function in C after the
771 substitutions described below.
772  
773 =over 3
774  
775 =item C<function, jacobian>
776  
777 The first line of the fit function definition must be
778 C<function funcname>. The first line of the jacobian
779 definition, if the jacobian is to be defined, is C<jacobian
780 funcname>. The function names can be any valid C function
781 name. The names may also be omitted as they are never needed
782 by the user. The names can be identical. (Note that a
783 numeric suffix will be automatically added to the function
784 name if the .so file already exists. This is because, if
785 another Func object has already loaded the shared library
786 from an .so file, dlopen will use this loaded library for
787 all C<Func> objects asking for that .so file, even if the
788 file has been overwritten, causing unexpected behavior)
789  
790 =item C<loop>
791  
792 The directive C<loop> says that all code before C<loop> is not
793 in the implicit loop, while all code following C<loop> is in
794 the implicit loop. If you omit the directive, then all the code
795 is wrapped in a loop.
796  
797 =item C<noloop>
798  
799 The directive C<noloop> says that there is no implicit loop anywhere
800 in the function.
801  
802 =item Out-of-loop substitutions
803  
804 These substitutions translate C<lpp> to C in lines that occur
805 before the implied loop (or everywhere if there is no loop.)
806 In every case you can write the translated C code into your
807 function definition yourself and C<lpp> will leave it
808 untouched.
809  
810 =over 3
811  
812 =item pq -> p[q]
813  
814 where q is a sequence of digits.
815  
816  
817 =item xq -> x[q]
818  
819 where q is a sequence of digits. This is applied only in the fit function,
820 not in the jacobian.
821  
822  
823 =item dq[r] -> d[q+m*r]
824  
825 (where m == $p->nelem), q and r are sequences of
826 digits. This applies only in the jacobian. You usually will
827 only use the fit functions with one value of m. It would
828 make faster code if you were to explicitly write, say C<d[u]>,
829 for each derivative at each point. Presumably there is a
830 small number of data points since this is outside a
831 loop. Some provisions should be added to C<lpp>, say C<m=3> to
832 hard code the value of C<m>. But m is only explicitly used in
833 constructions involving this substitution.
834  
835  
836 =back
837  
838 =item In-loop substitutions
839  
840 These substitutions apply inside the implied loop. The loop variables are
841 i in the fit function and i and j in the jacobian.
842  
843 =over 3
844  
845 =item t -> t[i]
846  
847 (literal "i") You can also write t[i] or t[expression involving i] by hand.
848 Example: t*t -> t[i]*t[i].
849  
850  
851 =item pq -> p[q]
852  
853 where q is a sequence of digits. Example p3 -> p[3].
854  
855  
856 =item x -> x[i]
857  
858 only in fit function, not in jacobian.
859  
860  
861 =item (dr or dr[i]) -> d[j++]
862  
863 where r is a sequence of digits. Note that r and i are
864 ignored. So you are required to list the derivatives in
865 order. An example is
866  
867 d0 = t*t; // derivative w.r.t p[0] loop over all points
868 d1 = t;
869  
870 If you write C<d1> first and then C<d0>, lpp will incorrectly
871 assign the derivative functions.
872  
873 =back
874  
875  
876 =back
877  
878  
879  
880 =item C Code
881  
882 The jacobian name must start with 'jac' when a pure C function definition
883 is used. To see example of fit functions writen in C, call levmar
884 with lpp code and the option C<NOCLEAN>. This will leave the C source
885 in the directory given by C<DIR>. The C code you supply is mangled
886 slightly before passing it to the compiler: It is copied twice, with
887 FLOAT defined in one case as C<double> and in the other as C<float>.
888 The letter C<s> is also appended to the function names in the latter
889 copy. The C code is parsed to find the fit function name and the
890 jacobian function name.
891  
892 We should make it possible to pass the function names as a separate option
893 rather than parsing the C code. This will allow auxiallary functions to
894 be defined in the C code; something that is currently not possible.
895  
896  
897 =item Perl_Subroutines
898  
899 This is how to use perl subroutines as fit functions... (see
900 the examples for now, e.g. L<example 2|/example--2>.) The
901 fit function takes ndarrays $p,$x, and $t, with dimensions
902 m,n, and tn. (often tn ==n ). These are references with
903 storage already allocated (by the user and liblevmar). So
904 you must use C<.=> when setting values. The jacobian takes
905 ndarrays $p,$d, and $t, where $d, the ndarray of derivatives
906 has dimensions (m,n). For example
907  
908 $f = sub myexp {
909 my ($p,$x,$t) = @_;
910 my ($p0,$p1,$p2) = list($p);
911 $x .= exp($t/$p0);
912 $x *= $p1;
913 $x += $p2
914 }
915  
916 $jf = sub my expjac {
917 my ($p,$d,$t) = @_;
918 my ($p0,$p1,$p2) = list($p);
919 my $arg = $t/$p0;
920 my $ex = exp($arg);
921 $d((0)) .= -$p1*$ex*$arg/$p0;
922 $d((1)) .= $ex;
923 $d((2)) .= 1.0;
924 }
925  
926  
927  
928 =back
929  
930  
931 =head1 PDL::Fit::Levmar::Func Objects
932  
933 These objects are created every time you call levmar(). The hash
934 returned by levmar contains a ref to the Func object. For instance
935 if you do
936  
937 $outh = levmar( FUNC => ..., @opts);
938  
939 then $outh->{LFUNC} will contain a ref to the function object. The .so
940 file, if it exists, will not be deleted until the object is destroyed.
941 This will happen, for instance if you do C<$outh = undef>.
942  
943  
944 =head1 IMPLEMENTATION
945  
946 This section currently only refers to the interface and not the fit algorithms.
947  
948 =over 3
949  
950 =item C fit functions
951  
952 The module does not use perl interfaces to dlopen or the C
953 compiler. The C compiler options are taken from
954 %Config. This is mostly because I had already written those
955 parts before I found the modules. I imagine the
956 implementation here has less overhead, but is less portable.
957  
958  
959 =item perl subroutine fit functions
960  
961 Null pdls are created in C code before the fit starts. They
962 are passed in a struct to the C fit function and derivative
963 routines that wrap the user's perl code. At each call the
964 data pointers to the pdls are set to what liblevmar has sent
965 to the fit functions. The pdls are deleted after the fit.
966 Originally, all the information on the fit functions was
967 supposed to be handled by Levmar::Func. But when I added
968 perl subroutine support, it was less clumsy to move most of
969 the code for perl subs to the Levmar module. So the current
970 solution is not very clean.
971  
972 =item Efficiency
973  
974 Using C<lpp> or C is faster than using perl subs, which is
975 faster than using L<PDL::Fit::LM>, at least in all the tests I have
976 done. For very large data sets, pure C was twice as fast as
977 perl subs and three times as fast as Fit::LM. Some
978 optimization problems have very small data sets and converge
979 very slowly. As the data sets become smaller and the number
980 of iterations increases the advantage of using pure C
981 increases as expected. Also, if I fit a small data set
982 (n=10) a large number of times (just looping over the same
983 problem), Pure C is ten times faster than Fit::LM, while
984 Levmar with perl subs is only about 1.15 times faster than
985 Fit::LM. All of this was observed on only two different
986 problems.
987  
988 =back
989  
990 =head1 FUNCTIONS
991  
992 =head2 levmar()
993  
994 =for ref
995  
996 Perform Levenberg-Marquardt non-linear least squares fit
997 to data given a model function.
998  
999 =for usage
1000  
1001 use PDL::Fit::Levmar;
1002  
1003 $result_hash = levmar($p,$x,$t, FUNC => $func, %OPTIONS );
1004  
1005 $p is a pdl of input parameters
1006 $x is a pdl of ordinate data
1007 $t is an optional pdl of co-ordinate data
1008
1009 levmar() is the main function in the Levmar package. See the
1010 PDL::Fit::Levmar for a complete description.
1011  
1012 =for signature
1013  
1014 p(m); x(n); t(nt); int itmax();
1015 [o] covar(m,m) ; int [o] returnval();
1016 [o] pout(m); [o] info(q=10);
1017  
1018 See the module documentation for information on passing
1019 these arguments to levmar. Threading is known to
1020 work with p(m) and x(n), but I have not tested the rest. In
1021 this case all of they output pdls get the correct number of
1022 dimensions (and correct values !). Notice that t(nt) has a
1023 different dimension than x(n). This is correct because in
1024 some problems there is no t at all, and in some it is
1025 pressed into the service of delivering other parameters to
1026 the fit routine. (Formally, even if you use t(n), they are
1027 parameters.)
1028  
1029  
1030 =head2 levmar_chkjac()
1031  
1032 =for ref
1033  
1034 Check the analytic jacobian of a function by computing
1035 the derivatives numerically.
1036  
1037 =for signature
1038
1039 p(m); t(n); [o] err(n);
1040 This is the relevant part of the signature of the
1041 routine that does the work.
1042  
1043  
1044 =for usage
1045  
1046 use PDL::Fit::Levmar;
1047  
1048 $Gh = levmar_func(FUNC=>$Gf);
1049  
1050 $err = levmar_chkjac($Gh,$p,$t);
1051  
1052 $f is an object of type PDL::Fit::Levmar::Func
1053 $p is a pdl of input parameters
1054 $t is an pdl of co-ordinate data
1055 $err is a pdl of errors computed at the values $t.
1056  
1057 Note: No data $x is supplied to this function
1058  
1059 The Func object $Gh contains a function f, and a jacobian
1060 jf. The i_th element of $err measures the agreement between
1061 the numeric and analytic gradients of f with respect to $p
1062 at the i_th evaluation point f (normally determined by the
1063 i_th element of t). A value of 1 means that the analytic and
1064 numeric gradients agree well. A value of 0 mean they do not
1065 agree.
1066  
1067 Sometimes the number of evaluation points n is hardcoded
1068 into the function (as in almost all the examples taken from
1069 liblevmar and appearing in t/liblevmar.t. In this case the
1070 values that f returns depend only on $p and not on any other
1071 external data (nameley t). In this case, you must pass the
1072 number n as a perl scalar in place of t. For example
1073  
1074 $err = levmar_chkjac($Gh,$p,5);
1075  
1076  
1077 8 ▶in the case that f is hardcoded to return five values.
Subroutine BEGIN: called CC=1 SCAR=0.0
1078 8 ▶ 
Subroutine BEGIN: called CC=1 SCAR=0.0
1079 8 ▶Need to put the description from the C code in here.
Subroutine BEGIN: called CC=1 SCAR=0.0
1080 8 ▶ 
Subroutine BEGIN: called CC=1 SCAR=0.0
1081 8 ▶=head2 levmar_report()
Subroutine BEGIN: called CC=1 SCAR=0.0
1082 16 ▶ 
Subroutine BEGIN: called CC=1 SCAR=0.0
1083 16 =for ref
1084  
1085 Make a human readable report from the hash ref returned
1086 by levmar().
1087  
1088 =for usage
1089  
1090 use PDL::Fit::Levmar;
1091  
1092 8 ▶ $h = levmar($p,$x,$t, $func);
Subroutine deb: not called CC=1 SCAR=0.0
Pod undocumented
1093  
1094 print levmar_report($h);
1095  
1096  
1097 =head1 BUGS
1098  
1099 With the levmar-2.6 code: Passing workspace currently does not work with
1100 linear inequality constraint. Some of the PDL broadcasting no long works
1101 correctly. These are noted in the tests in t/thread.t. It is not clear
1102 if it is a broadcasting issue or the fitting has changed.
1103  
1104
1105 =cut
1106  
1107 #--------------------------------------------------------------------
1108 # Begining of module code
1109  
1110 use strict;
1111 use PDL::Fit::Levmar::Func;
1112 use Carp;
1113 use PDL::NiceSlice;
1114 use PDL::Core ':Internal'; # For topdl()
1115 use vars ( '$Levmar_defaults', '$Levmar_defaults_order',
1116 '$Perl_func_wrapper', '$Perl_jac_wrapper', '$LPPEXT', '$DBLMAX' );
1117  
1118 # 'jac' refers to jacobian
1119 $Perl_func_wrapper = get_perl_func_wrapper();
1120 $Perl_jac_wrapper = get_perl_jac_wrapper();
1121 $DBLMAX = get_dbl_max();
1122  
1123 $LPPEXT = ".lpp";
1124  
1125  
1126 sub deb { print STDERR $_[0],"\n"}
1127  
1128 ===EOD===top_pm===
1129  
1130 pp_addpm({At=>'Top'},"\$PDL::Fit::Levmar::HAVE_LAPACK=$HAVE_LAPACK;\n");
1131  
1132 pp_addpm({At=>'Bot'},<<'===EOD===Authors===');
1133  
1134  
1135 =head1 AUTHORS
1136  
1137 PDL code for Levmar Copyright (C) 2006 John Lapeyre. C
1138 library code Copyright (C) 2006 Manolis Lourakis, licensed
1139 here under the Gnu Public License.
1140  
1141 All rights reserved. There is no warranty. You are allowed
1142 to redistribute this software / documentation under certain
1143 conditions. For details, see the file COPYING in the PDL
1144 distribution. If this file is separated from the PDL
1145 distribution, the copyright notice should be included in the
1146 file.
1147  
1148 =cut
1149  
1150 ===EOD===Authors===
1151  
1152 pp_addhdr('
1153 #include <stdio.h>
1154 #include <stdlib.h>
1155 #include <math.h>
1156 #include <float.h>
1157 #include "pdlperlfunc.h"
1158 #include "levmar.h"
1159 ');
1160  
1161  
1162 pp_add_exported('', 'levmar', 'levmar_report', 'levmar_chkjac');
1163  
1164  
1165 pp_addpm(<<'===EOD===pm_code===one');
1166 1 ▶ 
Subroutine chk_eq_dims: called CC=4 SCAR=14.0
Pod undocumented
1167 9  
1168 9 # check if dims are equal in two pdls
1169 9 sub chk_eq_dims {
1170 9 ▶ my ($x,$y) = @_;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @xd != scalar @yd 0 1 1
1171 9 my (@xd) = $x->dims();
1172 1 my (@yd) = $y->dims();
1173 1 ▶ return -2 if (scalar(@xd) != scalar(@yd) );
Branch: 1 branch
BranchTrueFalseTotal
if $_ != shift @yd 0 1 1
1174 my $ret = 1;
1175 1 foreach (@xd) {
1176 return -1 if ($_ != shift(@yd) );
1177 }
1178 return $ret;
1179 }
1180  
1181 @PDL::Fit::Levmar::reason_for_terminating = (
1182 '',
1183 'stopped by small gradient J^T e',
1184 'stopped by small Dp',
1185 'stopped by itmax',
1186 'singular matrix. Restart from current p with increased \mu',
1187 'no further error reduction is possible. Restart with increased \mu',
1188 8 ▶ 'stopped by small ||e||_2'
Subroutine levmar_report: called CC=1 SCAR=0.0
Pod documented
1189 8 );
1190 8
1191 sub levmar_report {
1192 my $h = shift;
1193 make_report($h->{P},$h->{COVAR}, $h->{INFO});
1194 8 ▶}
Subroutine make_report: called CC=1 SCAR=0.0
Pod undocumented
1195 8  
1196 8 # make a small report out of the results of the optimization
1197 sub make_report {
1198 my ($p,$covar,$info) = @_;
1199 my @ninf = list($info);
1200 8 # for(my $i=0;$i<9; $i++) { # Tried to get broadcasting to work, but no!
1201 # $ninf[$i] = $info(($i));
1202 8 # }
1203 $ninf[6] =
1204 $PDL::Fit::Levmar::reason_for_terminating[$ninf[6]]; # replace int with string
1205 my $form = <<"EOFORM";
1206 Estimated parameters: %s
1207 Covariance: %s
1208 ||e||_2 at initial parameters = %g
1209 Errors at estimated parameters:
1210 ||e||_2\t = %g
1211 ||J^T e||_inf\t= %g
1212 ||Dp||_2\t= %g
1213 \\mu/max[J^T J]_ii ]\t= %g
1214 number of iterations\t= %d
1215 reason for termination: = %s
1216 number of function evaluations\t= %d
1217 number of jacobian evaluations\t= %d
1218 8 number of linear systems solved\t= %d
1219 EOFORM
1220 my $st = sprintf($form, $p,$covar,@ninf);
1221
1222 }
1223  
1224 $Levmar_defaults_order = qw [
1225 FUNC
1226
1227  
1228 ];
1229  
1230  
1231 $Levmar_defaults = {
1232 MAXITS => 100, # maximum iterations
1233 MU => LM_INIT_MU(),
1234 EPS1 => LM_STOP_THRESH(),
1235 EPS2 => LM_STOP_THRESH(),
1236 EPS3 => LM_STOP_THRESH(),
1237 DELTA => LM_DIFF_DELTA(),
1238 DERIVATIVE => 'analytic',
1239 NOCOVAR => undef,
1240 FIX => undef,
1241 FIXB => undef,
1242 A => undef,
1243 B => undef,
1244 C => undef,
1245 D => undef,
1246 UB => undef,
1247 LB => undef,
1248 FUNC => undef, # Levmar::Func object, or function def, or ...
1249 JFUNC => undef, # must be ref to perl sub
1250 X => undef,
1251 P => undef,
1252 T => undef,
1253 WGHTS => undef,
1254 COVAR => undef, # The next 5 params can be set to PDL->null
1255 POUT => undef, # ref for preallocated output parameters
1256 INFO => undef,
1257 RET => undef,
1258 # meant to be private
1259 LFUNC => undef, # only Levmar::Func object, made from FUNC
1260 0 ▶};
Subroutine get_help_str: not called CC=1 SCAR=6.9
Pod undocumented
1261 0  
1262 # This isn't meant to replace help. But for now its doing nothing.
1263 sub get_help_str {
1264 return '
1265 This is the help string for levmar.
1266  
1267 ';
1268 91 ▶}
Subroutine levmar: called CC=88 SCAR=53.6
Pod documented
1269 91  
1270 91 #################################################################
1271 sub levmar {
1272 my($p,$x,$t,$infunc);
1273 my $args;
1274 91 # get all args before the hash. p,x,t must come in that order
1275 178 # but (t), or (t and x), or (t,x,and p) can be in the hash
1276 178 ▶ # the function can be anywhere before the hash
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $p and ref $_[0] eq "PDL" || ref $_[0] eq "ARRAY") 86 92 178
Condition83%5/6
not defined $p and ref $_[0] eq "PDL" || ref $_[0] eq "ARRAY"
!ll&&!rl&&r
791386
ref $_[0] eq "PDL" or ref $_[0] eq "ARRAY"
l!l&&r!l&&!r
86013
MC/DC66%2/3
not defined $p and ref $_[0] eq "PDL" || ref $_[0] eq "ARRAY"
not defined $p ref $_[0] eq "PDL" ref $_[0] eq "ARRAY"
Truth table75%3/4
not(A) and B or C
A= not defined $pB= ref $_[0] eq "PDL"C= ref $_[0] eq "ARRAY"
ABCresult
0XX0
1000
11X1
1011
1277 86 while (1) {
1278 $args = 0;
1279 178 ▶ if ( (not defined $p ) and (ref($_[0]) eq 'PDL' or ref($_[0]) eq 'ARRAY')) {
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 0 0 178 178
1280 178 ▶ $p = shift ; $args++;
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $x and ref $_[0] eq "PDL" || ref $_[0] eq "ARRAY") 78 100 178
Condition83%5/6
not defined $x and ref $_[0] eq "PDL" || ref $_[0] eq "ARRAY"
!ll&&!rl&&r
693178
ref $_[0] eq "PDL" or ref $_[0] eq "ARRAY"
l!l&&r!l&&!r
78031
MC/DC66%2/3
not defined $x and ref $_[0] eq "PDL" || ref $_[0] eq "ARRAY"
not defined $x ref $_[0] eq "PDL" ref $_[0] eq "ARRAY"
Truth table75%3/4
not(A) and B or C
A= not defined $xB= ref $_[0] eq "PDL"C= ref $_[0] eq "ARRAY"
ABCresult
0XX0
1000
11X1
1011
1281 78 }
1282 last if ( @_ == 0 );
1283 178 ▶ if ( (not defined $x ) and (ref($_[0]) eq 'PDL' or ref($_[0]) eq 'ARRAY')) {
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 0 0 178 178
1284 178 ▶ $x = shift ; $args++;
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $t and ref $_[0] eq "PDL" || ref $_[0] eq "ARRAY") 41 137 178
Condition83%5/6
not defined $t and ref $_[0] eq "PDL" || ref $_[0] eq "ARRAY"
!ll&&!rl&&r
3010741
ref $_[0] eq "PDL" or ref $_[0] eq "ARRAY"
l!l&&r!l&&!r
410107
MC/DC66%2/3
not defined $t and ref $_[0] eq "PDL" || ref $_[0] eq "ARRAY"
not defined $t ref $_[0] eq "PDL" ref $_[0] eq "ARRAY"
Truth table75%3/4
not(A) and B or C
A= not defined $tB= ref $_[0] eq "PDL"C= ref $_[0] eq "ARRAY"
ABCresult
0XX0
1000
11X1
1011
1285 41 }
1286 last if ( @_ == 0 );
1287 178 ▶ if ( (not defined $t) and (ref($_[0]) eq 'PDL' or ref($_[0]) eq 'ARRAY')) {
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 0 7 171 178
1288 171 ▶ $t = shift ; $args++;
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $infunc and ref($_[0]) =~ /Func|CODE/) 21 150 171
Condition100%3/3
not defined $infunc and ref($_[0]) =~ /Func|CODE/
!ll&&!rl&&r
2112921
MC/DC100%2/2
not defined $infunc and ref($_[0]) =~ /Func|CODE/
not defined $infunc ref($_[0]) =~ /Func|CODE/
Truth table100%3/3
not(A) and B
A= not defined $infuncB= ref($_[0]) =~ /Func|CODE/
ABresult
0X0
100
111
1289 21 }
1290 last if ( @_ == 0 );
1291 171 ▶ if ( not defined $infunc and ref($_[0]) =~ /Func|CODE/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 0 3 168 171
1292 168 ▶ $infunc = shift; $args++;
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $infunc || ref $_[0] and $_[0] =~ /(\.c|$PDL::Fit::Levmar::LPPEXT)$/o || $_[0] =~ /\n/) 8 160 168
Condition77%7/9
not defined $infunc || ref $_[0] and $_[0] =~ /(\.c|$PDL::Fit::Levmar::LPPEXT)$/o || $_[0] =~ /\n/
!ll&&!rl&&r
391218
defined $infunc || ref $_[0]
l!l&&r!l&&!r
390129
$_[0] =~ /(\.c|$PDL::Fit::Levmar::LPPEXT)$/o or $_[0] =~ /\n/
l!l&&r!l&&!r
80121
MC/DC50%2/4
not defined $infunc || ref $_[0] and $_[0] =~ /(\.c|$PDL::Fit::Levmar::LPPEXT)$/o || $_[0] =~ /\n/
defined $infunc ref $_[0] $_[0] =~ /(\.c|$PDL::Fit::Levmar::LPPEXT)$/o $_[0] =~ /\n/
Truth table60%3/5
not(A || B) and C or D
A= defined $infuncB= ref $_[0]C= $_[0] =~ /(\.c|$PDL::Fit::Levmar::LPPEXT)$/oD= $_[0] =~ /\n/
ABCDresult
1XXX0
01XX0
00000
001X1
00011
1293 }
1294 8 last if ( @_ == 0 );
1295 if ( (not defined $infunc) and
1296 168 ▶ ( not ref($_[0]) ) and ( $_[0] =~ /(\.c|$LPPEXT)$/o or $_[0] =~ /\n/ ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 0 or $args == 0 81 87 168
Condition100%3/3
@_ == 0 or $args == 0
l!l&&r!l&&!r
18087
MC/DC100%2/2
@_ == 0 or $args == 0
@_ == 0 $args == 0
Truth table100%3/3
A or B
A= @_ == 0B= $args == 0
ABresult
1X1
011
000
1297 $infunc = shift; $args++;
1298 91 }
1299 91 ▶ last if ( @_ == 0 or $args == 0);
Branch: 1 branch
BranchTrueFalseTotal
if @_ 80 11 91
1300 91 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
unless defined $inh 11 80 91
1301 91 ▶ my $inh;
Branch: 1 branch
BranchTrueFalseTotal
if (ref $inh ne "HASH") 80 11 91
1302 80 ▶ $inh = shift if @_; # input parameter hash
Branch: 1 branch
BranchTrueFalseTotal
defined $inh ? : 80 0 80
1303 $inh = {} unless defined $inh;
1304 91 ▶ if(ref $inh ne 'HASH') { # turn list into anonymous hash
Branch: 1 branch
BranchTrueFalseTotal
if (exists $inh->{"HELP"}) 0 91 91
1305 0 $inh = defined $inh ? {$inh,@_} : {} ;
1306 0 }
1307 if( exists $inh->{HELP} ) {
1308 91 ▶ my $s = get_help_str();
Branch: 1 branch
BranchTrueFalseTotal
if (exists $inh->{"GETOPTS"}) 1 90 91
1309 1 return $s;
1310 1 }
1311 if( exists $inh->{GETOPTS} ) {
1312 my %h = %$Levmar_defaults;
1313 90 ▶ return \%h;
Branch: 1 branch
BranchTrueFalseTotal
if defined $infunc 29 61 90
1314 }
1315 90 ▶ # should already use a ref to string here
Branch: 1 branch
BranchTrueFalseTotal
unless defined $inh->{"FUNC"} or defined $inh->{"CSRC"} 0 90 90
Condition66%2/3
defined $inh->{"FUNC"} or defined $inh->{"CSRC"}
l!l&&r!l&&!r
78120
MC/DC0%0/2
defined $inh->{"FUNC"} or defined $inh->{"CSRC"}
defined $inh->{"FUNC"} defined $inh->{"CSRC"}
Truth table66%2/3
A or B
A= defined $inh->{"FUNC"}B= defined $inh->{"CSRC"}
ABresult
1X1
011
000
1316 $inh->{FUNC} = $infunc if defined $infunc;
1317 die "levmar: neither FUNC nor CSRC defined"
1318 unless defined $inh->{FUNC} or defined $inh->{CSRC};
1319  
1320 ===EOD===pm_code===one
1321  
1322 if (not $HAVE_LAPACK) {
1323 90 pp_addpm( q!
1324 foreach (qw( A B C D FIX WGHT )) {
1325 540 ▶ barf "PDL::Fit::Levmar not built with lapack. Found parameter $_"
Branch: 1 branch
BranchTrueFalseTotal
if exists $inh->{$_} 0 540 540
1326 if exists $inh->{$_};
1327 }
1328 !)
1329 }
1330  
1331 pp_addpm(<<'===EOD===pm_code===two');
1332  
1333 90
1334 90 ######## Handle parameters
1335 90 my $h = {}; # parameter hash to be built from $inh and defaults
1336 2430 my $funch = {}; # unrecognized parameter hash. This will be passed to Func.
1337 foreach ( keys %$Levmar_defaults ){ # copy defaults to final hash
1338 90 $h->{$_} = $Levmar_defaults->{$_};
1339 234 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
if (exists $PDL::Fit::Levmar::Levmar_defaults->{$k}) { } 221 13 234
1340 221 foreach my $k (keys %$inh ) { # replace defaults with input params
1341 if ( exists $Levmar_defaults->{$k} ) {
1342 $h->{$k} = $inh->{$k};
1343 13 }
1344 else { # don't recognize, so pass to Func
1345 $funch->{$k} = $inh->{$k};
1346 }
1347 }
1348 ########## Set up input and output variables
1349 90 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
unless not defined $h->{"P"} and defined $p 4 86 90
Condition66%2/3
not defined $h->{"P"} and defined $p
!ll&&!rl&&r
4086
MC/DC50%1/2
not defined $h->{"P"} and defined $p
not defined $h->{"P"} defined $p
Truth table66%2/3
not(A) and B
A= not defined $h->{"P"}B= defined $p
ABresult
0X0
100
111
1350 90 ▶ # These must come from parameters if not from the arg list
Branch: 1 branch
BranchTrueFalseTotal
unless not defined $h->{"X"} and defined $p 12 78 90
Condition66%2/3
not defined $h->{"X"} and defined $p
!ll&&!rl&&r
12078
MC/DC50%1/2
not defined $h->{"X"} and defined $p
not defined $h->{"X"} defined $p
Truth table66%2/3
not(A) and B
A= not defined $h->{"X"}B= defined $p
ABresult
0X0
100
111
1351 90 ▶ $p = $h->{P} unless not defined $h->{P} and defined $p;
Branch: 1 branch
BranchTrueFalseTotal
unless not defined $h->{"T"} and defined $p 16 74 90
Condition66%2/3
not defined $h->{"T"} and defined $p
!ll&&!rl&&r
16074
MC/DC50%1/2
not defined $h->{"T"} and defined $p
not defined $h->{"T"} defined $p
Truth table66%2/3
not(A) and B
A= not defined $h->{"T"}B= defined $p
ABresult
0X0
100
111
1352 $x = $h->{X} unless not defined $h->{X} and defined $p;
1353 90 ▶ $t = $h->{T} unless not defined $h->{T} and defined $p;
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $p) 0 90 90
1354  
1355 0 if ( not defined $p ) { # This looks like some kind of error thing that was
1356 0 # not implemented consistently
1357 0 my $st = "No parameter (P) pdl";
1358 warn $st;
1359 90 ▶ return {RET => -1, ERRS => [$st] };
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $x) 0 90 90
1360 0 }
1361 0 if ( not defined $x ) {
1362 0 my $st = "No data (X) pdl";
1363 warn $st;
1364 return {RET => -1, ERRS => [$st] };
1365 }
1366  
1367 90 #-------------------------------------------------
1368 90 # Treat input and output ndarrays for pp_defs
1369 90 ▶ $x = topdl($x); # in case they are refs to arrays
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 33 57 90
1370 90 $p = topdl($p);
1371 $t = PDL->zeroes($p->type, 1) unless defined $t; # sometimes $t not needed
1372 90 $t = topdl($t);
1373 ### output variables
1374 90 my $pout;
1375 90 my $info;
1376 90 my $covar;
1377 my $ret;
1378 my $wghts;
1379 90 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if defined $h->{"COVAR"} 4 86 90
1380 90 ▶# should put this stuff in a loop
Branch: 1 branch
BranchTrueFalseTotal
if defined $h->{"POUT"} 0 90 90
1381 90 ▶ $covar = $h->{COVAR} if defined $h->{COVAR};
Branch: 1 branch
BranchTrueFalseTotal
if defined $h->{"INFO"} 0 90 90
1382 90 ▶ $pout = $h->{POUT} if defined $h->{POUT};
Branch: 1 branch
BranchTrueFalseTotal
if defined $h->{"RET"} 0 90 90
1383 90 ▶ $info = $h->{INFO} if defined $h->{INFO};
Branch: 1 branch
BranchTrueFalseTotal
if defined $h->{"WGHTS"} 0 90 90
1384 $ret = $h->{RET} if defined $h->{RET};
1385 $wghts = $h->{WGHTS} if defined $h->{WGHTS};
1386 90 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
unless defined $covar 86 4 90
1387 90 ▶# If they are set here, then there will be no external ref.
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pout 90 0 90
1388 90 ▶ $covar = PDL->null unless defined $covar;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $info 90 0 90
1389 90 ▶ $pout = PDL->null unless defined $pout;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ret 90 0 90
1390 90 ▶ $info = PDL->null unless defined $info;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $wghts 90 0 90
1391 $ret = PDL->null unless defined $ret;
1392 $wghts = PDL->null unless defined $wghts;
1393  
1394 # Careful about $m, it is used in construcing $A below (with fix). But this is
1395 90 # not correct when using implicit broadcasting. Except broadcasting may still be working.
1396 # Need to look into that.
1397 my $m = $p->nelem;
1398  
1399 #--------------------------------------------------------
1400 90 ▶# Set up Func object
Branch: 1 branch
BranchTrueFalseTotal
unless exists $h->{"FUNC"} 0 90 90
1401 90 ▶#--------------------------------------------------------
Branch: 1 branch
BranchTrueFalseTotal
if (ref($h->{'FUNC'}) =~ /CODE/ or not ref $h->{'FUNC'}) { } 63 27 90
Condition100%3/3
ref($h->{"FUNC"}) =~ /CODE/ or not ref $h->{"FUNC"}
l!l&&r!l&&!r
85527
MC/DC100%2/2
ref($h->{"FUNC"}) =~ /CODE/ or not ref $h->{"FUNC"}
ref($h->{"FUNC"}) =~ /CODE/ not ref $h->{"FUNC"}
Truth table100%3/3
A or not(B)
A= ref($h->{"FUNC"}) =~ /CODE/B= not ref $h->{"FUNC"}
ABresult
1X1
011
000
1402 croak "No FUNC in options to levmar." unless exists $h->{FUNC};
1403 63 if ( ref($h->{FUNC}) =~ /CODE/ or
1404 63 not ref($h->{FUNC}) ) { # probably a string, convert to func object
1405 63 ▶ $funch->{FUNC} = $h->{FUNC};
Branch: 1 branch
BranchTrueFalseTotal
if ($ret[0] == -1) 0 63 63
1406 0 my @ret = PDL::Fit::Levmar::Func::levmar_func($funch);
1407 if ($ret[0] == -1 ) { # error in creating function
1408 0 shift(@ret);
1409 # deb "Error: " . join("\n",@ret); # can turn this off and on
1410 63 return {RET => -1, ERRS => [@ret] } ; # just return all the other messages.
1411 }
1412 $h->{LFUNC} = $ret[0];
1413 27 }
1414 27 else { # already a Func object
1415 $h->{LFUNC} = $h->{FUNC} ; # copy ref
1416 my @k = keys %$funch;
1417 # It would be good to check for valid options. But if a user switches from a
1418 # string to a Func oject in the call to levmar(), he may not delete the
1419 27 ▶# other keys. Halting on an error would bit frustrating or puzzling.
Branch: 1 branch
BranchTrueFalseTotal
if (@k) 0 27 27
1420 0 ▶# Even a warning is perhaps too much
Branch: 1 branch
BranchTrueFalseTotal
if @k > 1 0 0 0
1421 0 if ( @k ) {
1422 0 my $s = ''; $s = 's' if @k>1;
1423 0 my $str = "Unrecognized or useless option$s to levmar: \n";
1424 foreach ( @k ) {
1425 0 $str .= " '$_' => '" . $funch->{$_} . "'\n" ;
1426 }
1427 warn $str ."";
1428 }
1429 }
1430 90 # C pointers to fit functions
1431 90 my ($funcn,$sfuncn,$jacn,$sjacn) = # single and double
1432 $h->{LFUNC}->get_fit_pointers();
1433 my $deriv = $h->{DERIVATIVE};
1434  
1435 90 # The DFP stuff is to wrap perl functions in C routines to pass to liblevmar.
1436 # It's probably cleaner to move most of this stuff into Levmar::Func
1437 90 ▶ my $DFP = 0; # routines check for $DFP == 0 to bypass perl wrapper
Branch: 1 branch
BranchTrueFalseTotal
if (ref($h->{"FUNC"}) =~ /CODE/) 8 82 90
1438 8  
1439 8 if ( ref($h->{FUNC}) =~ /CODE/) { # setup perl wrapper stuff
1440 8 ▶ my $jfunc = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (defined $h->{"JFUNC"} and ref($h->{"JFUNC"}) =~ /CODE/) 6 2 8
Condition66%2/3
defined $h->{"JFUNC"} and ref($h->{"JFUNC"}) =~ /CODE/
!ll&&!rl&&r
206
MC/DC50%1/2
defined $h->{"JFUNC"} and ref($h->{"JFUNC"}) =~ /CODE/
defined $h->{"JFUNC"} ref($h->{"JFUNC"}) =~ /CODE/
Truth table66%2/3
A and B
A= defined $h->{"JFUNC"}B= ref($h->{"JFUNC"}) =~ /CODE/
ABresult
0X0
100
111
1441 6 $DFP = DFP_create();
1442 if (defined $h->{JFUNC} and ref($h->{JFUNC}) =~ /CODE/) {
1443 8 ▶ $jfunc = $h->{JFUNC};
Branch: 1 branch
BranchTrueFalseTotal
if ($deriv eq "analytic" and $jfunc == 0) 2 6 8
Condition100%3/3
$deriv eq "analytic" and $jfunc == 0
!ll&&!rl&&r
242
MC/DC100%2/2
$deriv eq "analytic" and $jfunc == 0
$deriv eq "analytic" $jfunc == 0
Truth table100%3/3
A and B
A= $deriv eq "analytic"B= $jfunc == 0
ABresult
0X0
100
111
1444 }
1445 2 if ( $deriv eq 'analytic' and $jfunc == 0 ) {
1446 2 # warn "No jacobian function supplied, using numeric derivatives";
1447 $deriv = 'numeric';
1448 8 $h->{DERIVATIVE} = 'numeric';
1449 8 }
1450 8 DFP_set_perl_funcs($DFP, $h->{FUNC}, $h->{JFUNC});
1451 8 $funcn = $Perl_func_wrapper;
1452 8 $jacn = $Perl_jac_wrapper;
1453 $sfuncn = $Perl_func_wrapper; # Single and double can use same wrapper
1454 $sjacn = $Perl_jac_wrapper;
1455 }
1456  
1457 90 ▶############ Do a few sanity checks
Branch: 2 branches
BranchTrueFalseTotal
if ($deriv eq 'analytic') { } 71 19 90
elsif ($deriv ne 'numeric') { } 0 19 19
1458 71 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $jacn or $jacn == 0) 1 70 71
Condition66%2/3
not defined $jacn or $jacn == 0
l!l&&r!l&&!r
1070
MC/DC50%1/2
not defined $jacn or $jacn == 0
not defined $jacn $jacn == 0
Truth table66%2/3
not(A) or B
A= not defined $jacnB= $jacn == 0
ABresult
1X1
011
000
1459 if ( $deriv eq 'analytic' ) {
1460 1 if (not defined $jacn or $jacn == 0 ) {
1461 1 # warn "No jacobian function supplied, using numeric derivatives";
1462 $deriv = 'numeric';
1463 $h->{DERIVATIVE} = 'numeric';
1464 }
1465 0 }
1466 elsif ( $deriv ne 'numeric' ) {
1467 croak "DERIVATIVE must be 'analytic' or 'numeric'";
1468 }
1469  
1470 # liblevmar uses 5 option for analytic and 6 for numeric.
1471 90 ▶ my $opts = pdl($p->type, @$h{qw(MU EPS1 EPS2 EPS3)},
Branch: 1 branch
BranchTrueFalseTotal
$h->{'DERIVATIVE'} eq 'analytic' ? : 70 20 90
1472 $h->{DERIVATIVE} eq 'analytic' ? () : $h->{DELTA}
1473 90 );
1474 # We make an integer option array as well, for passing stuff , like maxits.
1475 my $iopts = pdl(long, $h->{MAXITS});
1476  
1477 ########### FIX holds some parameters constant using linear constraints.
1478 # It is a special case of more general constraints using A and b.
1479 # Notice that this fails if FIX has more than one dimension (ie, you are
1480 90 ▶# broadcasting. FIXB does the same but using box constraints.
Branch: 2 branches
BranchTrueFalseTotal
if (defined $h->{'FIX'}) { } 0 90 90
elsif (defined $h->{'FIXB'}) { } 1 89 90
1481 0  
1482 0 ▶ if (defined $h->{FIX} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (chk_eq_dims($ip, $p) < 0) 0 0 0
1483 0 my $ip = topdl( $h->{FIX}); # take array ref or pdl
1484 if ( chk_eq_dims($ip,$p) < 0 ) {
1485 0 croak "p and FIX must have the same dimensions";
1486 0 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
if ($nc > 0) 0 0 0
1487 0 my $nc = $ip->sum; # number of fixed vars
1488 0 if ($nc > 0) {
1489 0 my $A = zeroes($p->type, $m,$nc);
1490 0 ▶ my $b = zeroes($p->type, $nc);
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $m) 0 0 0
1491 0 ▶ my $j=0;
Branch: 1 branch
BranchTrueFalseTotal
if ($ip->at($i) == 1) 0 0 0
1492 0 for(my $i=0; $i<$m; $i++) {
1493 0 if ($ip->at($i) == 1) {
1494 0 $A($i,$j) .= 1;
1495 $b($j) .= $p->at($i);
1496 $j++;
1497 0 }
1498 0 }
1499 $h->{A} = $A;
1500 $h->{B} = $b;
1501 }
1502 1 }
1503 1 ▶ elsif ( defined $h->{FIXB} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (chk_eq_dims($f, $p) < 0) 0 1 1
1504 0 my $f = topdl( $h->{FIXB}); # take array ref or pdl
1505 if ( chk_eq_dims($f,$p) < 0 ) {
1506 1 ▶ croak "p and FIX must have the same dimensions";
Branch: 1 branch
BranchTrueFalseTotal
unless defined $h->{"UB"} 0 1 1
1507 1 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
unless defined $h->{"LB"} 0 1 1
1508 1 $h->{UB} = ones($p) * $DBLMAX if not defined $h->{UB};
1509 1 $h->{LB} = ones($p) * -$DBLMAX if not defined $h->{LB};
1510 1 $_ = topdl($_) for @$h{qw(UB LB)};
1511 1 my $fi = PDL::Primitive::which($f == 1); # indices in p that we want to fix.
1512 $h->{UB}->flat->index($fi) .= $p->flat->index($fi);
1513 $h->{LB}->flat->index($fi) .= $p->flat->index($fi);
1514 # so ub and lb are now at maximum bounds where not fixed and at value of
1515 90 # p where fixed
1516 90 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $h->{"NOCOVAR"}) 0 90 90
1517 0 my $want_covar = 1;
1518 if ( defined $h->{NOCOVAR} ) {
1519 $want_covar = 0;
1520 90 }
1521 90 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if (@$errs > 0) 0 90 90
1522 my $errs = check_levmar_args($h);
1523 0 if ( @$errs > 0 ) {
1524 # print @$errs;
1525 90 return {RET => -1, ERRS => $errs };
1526 }
1527 90 ▶ my ($func_key, $arg_list) = build_constraint_arg_combination($h);
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $func_key) 0 90 90
1528 0 # print "func key '$func_key'\n";
1529 if ( not defined $func_key ) {
1530 90 ▶ croak "Could not find function key";
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $PDL::Fit::Levmar::PDL_Levmar_funcs{$func_key}) 0 90 90
1531 0 }
1532 if ( not exists $PDL::Fit::Levmar::PDL_Levmar_funcs{$func_key} ) {
1533 90 croak "Could not find function for key";
1534 }
1535 my $pdl_levmar_func = $PDL::Fit::Levmar::PDL_Levmar_funcs{$func_key};
1536 # print "func $pdl_levmar_func\n";
1537 # my $nargs = @$arg_list;
1538 # print "Got $nargs args\n";
1539 90 ▶ &$pdl_levmar_func($p,$x,$t,@$arg_list,$iopts,$opts,
Branch: 1 branch
BranchTrueFalseTotal
$h->{'DERIVATIVE'} eq 'analytic' ? : 70 20 90
1540 $covar, $ret, $pout, $info, $funcn, $sfuncn,
1541 ($h->{DERIVATIVE} eq 'analytic' ? ( $jacn, $sjacn ) : ()),
1542 90 ▶ $DFP, $want_covar);
Branch: 1 branch
BranchTrueFalseTotal
if $DFP 8 82 90
1543  
1544 DFP_free($DFP) if $DFP;
1545  
1546 my $hout = {
1547 RET => $ret,
1548 COVAR => $covar,
1549 P => $pout,
1550 ERRI => $info((0)),
1551 ERR1 => $info((1)),
1552 ERR2 => $info((2)),
1553 ERR3 => $info((3)),
1554 ERR4 => $info((4)),
1555 ITS => $info((5)),
1556 REASON => $info((6)),
1557 NFUNC => $info((7)),
1558 NJAC => $info((8)),
1559 NLS => $info((9)),
1560 90 INFO => $info,
1561 90 FUNC => $h->{LFUNC},
1562 };
1563 return $hout;
1564
1565 90 ▶} # end levmar()
Subroutine check_levmar_args: called CC=11 SCAR=26.4
Pod undocumented
1566 90  
1567 90  
1568 90 sub PDL::Fit::Levmar::check_levmar_args {
1569 90 my ($h) = @_;
1570 540 ▶ my @refargs = qw( LB UB A B C D );
Branch: 1 branch
BranchTrueFalseTotal
if (exists $h->{$argname} and defined $h->{$argname}) 30 510 540
Condition66%2/3
exists $h->{$argname} and defined $h->{$argname}
!ll&&!rl&&r
051030
MC/DC50%1/2
exists $h->{$argname} and defined $h->{$argname}
exists $h->{$argname} defined $h->{$argname}
Truth table66%2/3
A and B
A= exists $h->{$argname}B= defined $h->{$argname}
ABresult
0X0
100
111
1571 30 my @errs = ();
1572 30 ▶ foreach my $argname ( @refargs ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $arg) 0 30 30
1573 0 if ( exists $h->{$argname} and defined $h->{$argname} ) {
1574 my $arg = $h->{$argname};
1575 if ( not ref($arg) ) {
1576 push @errs, "$argname must be a pdl or ref to array.";
1577 90 }
1578 90 }
1579 180 }
1580 180 my @combs = ( [ 'A', 'B' ], [ 'C', 'D' ] );
1581 180 foreach my $comb (@combs ) {
1582 360 ▶ my $n = @$comb;
Branch: 1 branch
BranchTrueFalseTotal
if exists $h->{$arg} and defined $h->{$arg} 0 360 360
Condition33%1/3
exists $h->{$arg} and defined $h->{$arg}
!ll&&!rl&&r
03600
MC/DC0%0/2
exists $h->{$arg} and defined $h->{$arg}
exists $h->{$arg} defined $h->{$arg}
Truth table33%1/3
A and B
A= exists $h->{$arg}B= defined $h->{$arg}
ABresult
0X0
100
111
1583 my $nf = 0;
1584 180 ▶ foreach my $arg ( @$comb ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nf != 0 and $n != $nf) 0 180 180
Condition33%1/3
$nf != 0 and $n != $nf
!ll&&!rl&&r
18000
MC/DC0%0/2
$nf != 0 and $n != $nf
$nf != 0 $n != $nf
Truth table33%1/3
A and B
A= $nf != 0B= $n != $nf
ABresult
0X0
100
111
1585 0 $nf++ if exists $h->{$arg} and defined $h->{$arg};
1586 }
1587 if ( $nf != 0 and $n != $nf ) {
1588 90 push @errs, 'none or all of ' . join(' and ',@$comb) . ' must be defined.';
1589 }
1590 }
1591 return \@errs;
1592 }
1593  
1594
1595 90 ▶# make a list of strings of names of constraint args that
Subroutine build_constraint_arg_combination: called CC=7 SCAR=19.7
Pod undocumented
1596 90 # have been passed.
1597 90 # hash is arg hash to top level call
1598 90 sub PDL::Fit::Levmar::build_constraint_arg_combination {
1599 my ($h) = @_;
1600 90 my @arg_comb = ();
1601 90 my @arg_list = ();
1602 540 # order is important in following
1603 my @possible_args = qw( LB UB A B C D );
1604 540 ▶ foreach ( @possible_args ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $h->{$ucarg} and defined $h->{$ucarg}) 30 510 540
Condition66%2/3
exists $h->{$ucarg} and defined $h->{$ucarg}
!ll&&!rl&&r
051030
MC/DC50%1/2
exists $h->{$ucarg} and defined $h->{$ucarg}
exists $h->{$ucarg} defined $h->{$ucarg}
Truth table66%2/3
A and B
A= exists $h->{$ucarg}B= defined $h->{$ucarg}
ABresult
0X0
100
111
1605 30 my $ucarg = $_;
1606 30 # $ucarg =~ tr/a-z/A-Z/; # should rewrite so that tr not needed
1607 if ( exists $h->{$ucarg} and defined $h->{$ucarg} ) {
1608 push @arg_comb, $_;
1609 90 push @arg_list, topdl($h->{$ucarg});
1610 90 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
if ($h->{'DERIVATIVE'} eq 'analytic') { } 70 20 90
1611 70 }
1612 my $deriv_type;
1613 if ($h->{DERIVATIVE} eq 'analytic' ) {
1614 20 $deriv_type = 'DER';
1615 }
1616 90 ▶ else {
Branch: 1 branch
BranchTrueFalseTotal
if exists $h->{"WGHTS"} and defined $h->{"WGHTS"} 0 90 90
Condition33%1/3
exists $h->{"WGHTS"} and defined $h->{"WGHTS"}
!ll&&!rl&&r
0900
MC/DC0%0/2
exists $h->{"WGHTS"} and defined $h->{"WGHTS"}
exists $h->{"WGHTS"} defined $h->{"WGHTS"}
Truth table33%1/3
A and B
A= exists $h->{"WGHTS"}B= defined $h->{"WGHTS"}
ABresult
0X0
100
111
1617 90 $deriv_type = 'DIFF';
1618 90 }
1619 push @arg_list, topdl($h->{WGHTS}) if exists $h->{WGHTS} and defined $h->{WGHTS};
1620 my $fk = make_pdl_levmar_func_key(make_hash_key_from_arg_comb(\@arg_comb), $deriv_type);
1621 90 ▶ return ($fk,\@arg_list);
Subroutine make_hash_key_from_arg_comb: called CC=1 SCAR=0.0
Pod undocumented
1622 90 }
1623 90  
1624 sub PDL::Fit::Levmar::make_hash_key_from_arg_comb {
1625 my ( $arg_comb ) = @_;
1626 90 ▶ return join( '_', @$arg_comb);
Subroutine make_pdl_levmar_func_key: called CC=1 SCAR=0.0
Pod undocumented
1627 90 }
1628 90  
1629  
1630 sub PDL::Fit::Levmar::make_pdl_levmar_func_key {
1631 my ($arg_str, $deriv_type) = @_;
1632 return $deriv_type . '_' . $arg_str;
1633 }
1634  
1635  
1636 %PDL::Fit::Levmar::PDL_Levmar_funcs = (
1637 DER_ => \&PDL::levmar_der_,
1638 DIFF_ => \&PDL::levmar_diff_,
1639 DER_LB_C_D => \&PDL::levmar_der_lb_C_d,
1640 DIFF_LB_C_D => \&PDL::levmar_diff_lb_C_d,
1641 DER_A_B => \&PDL::levmar_der_A_b,
1642 DIFF_A_B => \&PDL::levmar_diff_A_b,
1643 DER_UB_A_B => \&PDL::levmar_der_ub_A_b,
1644 DIFF_UB_A_B => \&PDL::levmar_diff_ub_A_b,
1645 DER_UB => \&PDL::levmar_der_ub,
1646 DIFF_UB => \&PDL::levmar_diff_ub,
1647 DER_A_B_C_D => \&PDL::levmar_der_A_b_C_d,
1648 DIFF_A_B_C_D => \&PDL::levmar_diff_A_b_C_d,
1649 DER_LB_UB_A_B_C_D => \&PDL::levmar_der_lb_ub_A_b_C_d,
1650 DIFF_LB_UB_A_B_C_D => \&PDL::levmar_diff_lb_ub_A_b_C_d,
1651 DER_LB => \&PDL::levmar_der_lb,
1652 DIFF_LB => \&PDL::levmar_diff_lb,
1653 DER_LB_A_B_C_D => \&PDL::levmar_der_lb_A_b_C_d,
1654 DIFF_LB_A_B_C_D => \&PDL::levmar_diff_lb_A_b_C_d,
1655 DER_UB_A_B_C_D => \&PDL::levmar_der_ub_A_b_C_d,
1656 DIFF_UB_A_B_C_D => \&PDL::levmar_diff_ub_A_b_C_d,
1657 DER_LB_UB => \&PDL::levmar_der_lb_ub,
1658 DIFF_LB_UB => \&PDL::levmar_diff_lb_ub,
1659 DER_LB_A_B => \&PDL::levmar_der_lb_A_b,
1660 DIFF_LB_A_B => \&PDL::levmar_diff_lb_A_b,
1661 DER_UB_C_D => \&PDL::levmar_der_ub_C_d,
1662 DIFF_UB_C_D => \&PDL::levmar_diff_ub_C_d,
1663 DER_LB_UB_A_B => \&PDL::levmar_der_lb_ub_A_b,
1664 DIFF_LB_UB_A_B => \&PDL::levmar_diff_lb_ub_A_b,
1665 DER_LB_UB_C_D => \&PDL::levmar_der_lb_ub_C_d,
1666 4 ▶ DIFF_LB_UB_C_D => \&PDL::levmar_diff_lb_ub_C_d,
Subroutine levmar_chkjac: called CC=7 SCAR=21.6
Pod documented
1667 4 DER_C_D => \&PDL::levmar_der_C_d,
1668 4 DIFF_C_D => \&PDL::levmar_diff_C_d,
1669 4 ▶);
Branch: 1 branch
BranchTrueFalseTotal
unless ($r =~ /Levmar::Func/) 0 4 4
1670 0  
1671 0  
1672  
1673 4  
1674 4 ▶sub levmar_chkjac {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref($t) =~ /PDL/) 0 4 4
1675 0 my ($f,$p,$t) = @_;
1676 0 my $r = ref $f;
1677 if ( not $r =~ /Levmar::Func/ ) {
1678 4 warn "levmar_chkjac: not a Levmar::Func object ";
1679 4 return;
1680 4 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
if (ref($f->{'FUNC'}) =~ /CODE/) { } 2 2 4
1681 2 my $N;
1682 2 if ( not ref($t) =~ /PDL/ ) {
1683 2 ▶ $N = $t; # in case there is no t for this func
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $f->{"JFUNC"} and ref($f->{"FUNC"}) =~ /CODE/) 0 2 2
Condition33%1/3
defined $f->{"JFUNC"} and ref($f->{"FUNC"}) =~ /CODE/
!ll&&!rl&&r
002
MC/DC0%0/2
defined $f->{"JFUNC"} and ref($f->{"FUNC"}) =~ /CODE/
defined $f->{"JFUNC"} ref($f->{"FUNC"}) =~ /CODE/
Truth table33%1/3
A and B
A= defined $f->{"JFUNC"}B= ref($f->{"FUNC"}) =~ /CODE/
ABresult
0X0
100
111
1684 0 $t = zeroes( $p->type, 1); just some pdl
1685 0 }
1686 my $DFP = 0;
1687 2 my ($funcn,$sfuncn,$jacn,$sjacn);
1688 2 if ( ref($f->{FUNC}) =~ /CODE/) { # setup perl wrapper stuff
1689 2 my $jfunc = 0;
1690 2 $DFP = DFP_create();
1691 2 if (not (defined $f->{JFUNC} and ref($f->{FUNC}) =~ /CODE/ ) ) {
1692 warn "levmar_chkjac: no perl code jacobian supplied in JFUNC.";
1693 return undef;
1694 2 }
1695 DFP_set_perl_funcs($DFP, $f->{FUNC}, $f->{JFUNC});
1696 $funcn = $Perl_func_wrapper;
1697 4 $jacn = $Perl_jac_wrapper;
1698 4 ▶ $sfuncn = $Perl_func_wrapper;
Branch: 1 branch
BranchTrueFalseTotal
if (defined $N) { } 0 4 4
1699 0 $sjacn = $Perl_jac_wrapper;
1700 }
1701 else { # pointers to native c functions.
1702 4 ($funcn,$sfuncn,$jacn,$sjacn) =
1703 $f->get_fit_pointers();
1704 4 }
1705 4 my $err;
1706 if ( defined $N ) {
1707 $err = _levmar_chkjac_no_t($p,$funcn,$sfuncn,$jacn,$sjacn,$N,$DFP);
1708 }
1709 else {
1710 $err = _levmar_chkjac($p,$t,$funcn,$sfuncn,$jacn,$sjacn,$DFP);
1711 }
1712 DFP_free($DFP);
1713 return $err;
1714 }
1715  
1716 ===EOD===pm_code===two
1717  
1718 =pod
1719  
1720 =begin comment
1721  
1722 The following comments are not intended to appear in documentation.
1723 But short of removing them, I find it impossible to keep them from
1724 appearing in the documentation.
1725  
1726 The following provides an interface to 12 functions in
1727 liblevmar. 2 (float or double) * 2 (numeric or analytic)
1728 * 3 (bc, lec, no constraint). There are 6 pp_defs. pp
1729 takes care of the float , double code itself (with some
1730 macros) You can't nest pp macros, so I use DUMI below.
1731 Note that I put a conditional in the broadcast loop. Not a
1732 big deal, I think, because the broadcastloop is calling a big
1733 routine with lots of conditionals and lots of calls to
1734 other similar routines.
1735  
1736 I pass pdl of type long iopts for some
1737 parameters. Currently only maxits is there. I suppose I
1738 could also put want_covar in there, but now its an other
1739 parameter. Whatever is in iopts can be broadcasted. I suppose
1740 someone might want to broadcast whether to compute
1741 covariance.
1742  
1743 =end comment
1744  
1745 =cut
1746  
1747 # Note very carefully the placement of trailing commas and semi-colons here.
1748  
1749 sub find_levmar_func_name_from_args {
1750 my ($arglist, $arg_descr) = @_;
1751 my %seen = ();
1752 my $nargs = @$arglist;
1753 my $max_seen = 0;
1754 foreach my $arg ( @$arglist ) {
1755 foreach my $routine ( @{ $arg_descr->{$arg}->{ALLOWEDIN} } ) {
1756 $seen{$routine}++;
1757 $max_seen = $seen{$routine} if $max_seen < $seen{$routine};
1758 }
1759 }
1760 my @routine_priority = qw( bc lec blec bleic );
1761 my $routine = 'none';
1762 foreach my $try_routine ( @routine_priority ) {
1763 if ( exists $seen{$try_routine} and $seen{$try_routine} == $max_seen ) {
1764 $routine = $try_routine;
1765 last;
1766 }
1767 }
1768 # print join(':',@$arglist)," => ";
1769 # print $routine, "\n";
1770 return $routine;
1771 }
1772  
1773 sub make_hash_key_from_arg_comb {
1774 my ( $arg_comb ) = @_;
1775 return join( '_', @$arg_comb);
1776 }
1777  
1778 # Make the string for Pars =>
1779 sub make_constraint_signature {
1780 my ( $arg_comb, $arg_descr ) = @_;
1781 my $sig_str = '';
1782 foreach my $arg ( @$arg_comb ) {
1783 $sig_str .= $arg_descr->{$arg}->{SIGNATURE} . '; ';
1784 }
1785 $sig_str =~ s/;\s$//;
1786 return $sig_str;
1787 }
1788  
1789 sub array_to_hash {
1790 my ($a) = @_;
1791 my $h = {};
1792 foreach ( @$a) {
1793 $h->{$_} = 1;
1794 }
1795 return $h;
1796 }
1797  
1798 # not working now,
1799 # need to use $levmar_routine_description
1800 # below to build correct call arguments
1801 # test if arg is present in arg_comb and write NULL , if not
1802 sub make_constraint_call_args {
1803 my ( $arg_comb, $arg_descr, $levmar_routine_description, $levmar_funtion_name ) = @_;
1804 my $route_descr = $levmar_routine_description->{$levmar_funtion_name};
1805 my $args = $route_descr->{ARGS};
1806 my $reqr = {};
1807 my $arg_comb_hash = array_to_hash($arg_comb);
1808 $reqr = $route_descr->{REQR} if exists $route_descr->{REQR};
1809 my $call_str = '';
1810 foreach my $arg ( @$args ) {
1811 if ( exists $reqr->{$arg}) {
1812 if ( exists $arg_comb_hash->{$reqr->{$arg}} ) {
1813 $call_str .= "$arg,";
1814 }
1815 else {
1816 $call_str .= '0,';
1817 }
1818 next;
1819 }
1820 if ( not exists $arg_comb_hash->{$arg} ) {
1821 $call_str .= 'NULL,';
1822 next;
1823 }
1824 $call_str .= $arg_descr->{$arg}->{CALLARG} . ', ';
1825 }
1826 # $call_str =~ s/,\s$//;
1827 return $call_str;
1828 }
1829  
1830 # We will write 64 (perhaps) pdl function definitions.
1831 # For each constraint option (A,b,C... etc) we have the following:
1832 # SIGNATURE is the string that is part of the ppdef pdl signature
1833 # CALLARG is the pp_def argument in the call to the C routine
1834 # ALLOWEDIN is the list of levmar C routines that take this constraint as an argument
1835 sub make_argument_combinations {
1836 my $arg_descr = {
1837 A => {
1838 SIGNATURE => 'A(m,k)',
1839 CALLARG => '$P(A)',
1840 ALLOWEDIN => [qw( lec blec bleic )],
1841 },
1842 b => {
1843 SIGNATURE => 'b(k)',
1844 CALLARG => '$P(b)',
1845 ALLOWEDIN => [qw( lec blec bleic )],
1846 },
1847 ub => {
1848 SIGNATURE => 'ub(m)',
1849 CALLARG => '$P(ub)',
1850 ALLOWEDIN => [qw( bc blec bleic )],
1851 },
1852 lb => {
1853 SIGNATURE => 'lb(m)',
1854 CALLARG => '$P(lb)',
1855 ALLOWEDIN => [qw( bc blec bleic )],
1856 },
1857 C => {
1858 SIGNATURE => 'C(m,k2)',
1859 CALLARG => '$P(C)',
1860 ALLOWEDIN => [qw( bleic )],
1861 },
1862 d => {
1863 SIGNATURE => 'd(k2)',
1864 CALLARG => '$P(d)',
1865 ALLOWEDIN => [qw( bleic )],
1866 },
1867 # WGHTS => {
1868 # SIGNATURE => 'wghts(m)',
1869 # CALLARG => '$P(wghts)',
1870 # ALLOWEDIN => [qw( blec )],
1871 # },
1872 };
1873  
1874 my $levmar_routine_description = {
1875 none => { ARGS => [] },
1876 bc => { ARGS => [qw( lb ub )] },
1877 lec => { ARGS => [ 'A', 'b', '$SIZE(k)' ],
1878 REQR => { '$SIZE(k)' => 'A' },
1879 },
1880 blec => { ARGS => [ 'lb', 'ub', 'A', 'b' , '$SIZE(k)' ],
1881 REQR => { '$SIZE(k)' => 'A' },
1882 },
1883 bleic => { ARGS => [ 'lb', 'ub', 'A', 'b', '$SIZE(k)', 'C', 'd', '$SIZE(k2)' ],
1884 REQR => { '$SIZE(k)' => 'A', '$SIZE(k2)' => 'C' },
1885 }
1886 };
1887  
1888  
1889 my %arg_combs_analysis =();
1890 # These are intended to be legal constraint combinations
1891 # result should also be used to check if a call is legal
1892 # This should make all leval combinations
1893 my $arg_combs = [];
1894 foreach my $linear ( [ ] , $HAVE_LAPACK ? [ 'A', 'b' ] : () ) {
1895 foreach my $box ( [ ] , [ 'lb', 'ub' ] , [ 'lb' ], [ 'ub' ] ) {
1896 foreach my $ineq ( [ ] , $HAVE_LAPACK ? [ 'C', 'd' ] : () ) {
1897 push @$arg_combs, [ @$box, @$linear, @$ineq ];
1898 }
1899 }
1900 }
1901 foreach my $arg_comb ( @$arg_combs ) {
1902 my $levmar_funtion_name = find_levmar_func_name_from_args( $arg_comb, $arg_descr );
1903 my $comb_key = make_hash_key_from_arg_comb( $arg_comb );
1904 my $constraint_signature = make_constraint_signature( $arg_comb, $arg_descr );
1905 my $call_args = make_constraint_call_args( $arg_comb, $arg_descr,
1906 $levmar_routine_description, $levmar_funtion_name );
1907 $arg_combs_analysis{$comb_key} = {
1908 LEVMAR_FUNCTION_NAME => $levmar_funtion_name,
1909 ARG_COMB => [ @$arg_comb ],
1910 SIGNATURE => $constraint_signature,
1911 CALLARGS => $call_args,
1912 PDL_FUNC_NAME_DER => make_pdl_levmar_func_name_from_strings($comb_key, 'der'),
1913 PDL_FUNC_NAME_DIFF => make_pdl_levmar_func_name_from_strings($comb_key, 'diff'),
1914 };
1915 }
1916 return \%arg_combs_analysis;
1917 }
1918  
1919 sub write_pp_defs {
1920 my ($arg_combs_analysis) = @_;
1921 foreach my $der ( 'analytic', 'numeric' ) {
1922 # foreach my $con ( 'none', 'bc', 'lec', 'blec', 'bleic','blic','leic','lic' ) {
1923 foreach my $argcomb ( keys %$arg_combs_analysis ) {
1924 # passing workspace is broken for some routines, so...
1925 my $arg_anal = $arg_combs_analysis->{$argcomb};
1926 my $h = {NOWORK => 0}; # default
1927 if ($der eq 'analytic') { # analytic derivative
1928 $h->{OPAR} = ' IV jacn; IV sjacn; ';
1929 $h->{CALL} = 'der';
1930 $h->{ARG} = 't$TFD(s,)jacn,';
1931 $h->{DUMI}= 'void * tjacn = (void *) $COMP(jacn);
1932 void * tsjacn = (void *) $COMP(sjacn);';
1933 $h->{WORKFAC} = 2; # needs less workspace than numeric
1934 }
1935 else { # numeric derivative
1936 $h->{OPAR} = '';
1937 $h->{CALL} = 'dif';
1938 $h->{ARG} = '';
1939 $h->{DUMI}= '';
1940 $h->{WORKFAC} = 4;
1941 }
1942 $h->{SIG} = $arg_anal->{SIGNATURE} . '; ' ;
1943 $h->{ARG2} = $arg_anal->{CALLARGS};
1944 if ($arg_anal->{LEVMAR_FUNCTION_NAME} eq 'bleic' ) {
1945 $h->{NOWORK} = 1;
1946 }
1947 my $funcname = '';
1948 $funcname = $arg_anal->{LEVMAR_FUNCTION_NAME} unless $arg_anal->{LEVMAR_FUNCTION_NAME} eq 'none';
1949 $h->{CALL} = $funcname . '_' . $h->{CALL} unless $arg_anal->{LEVMAR_FUNCTION_NAME} eq 'none';
1950 if ($arg_anal->{LEVMAR_FUNCTION_NAME} eq 'blec') {
1951 $h->{SIG} .= 'wghts(m); ';
1952 $h->{ARG2} .= '$P(wghts), ';
1953 }
1954 $h->{ARG2} .= 'NULL, ' if $arg_anal->{LEVMAR_FUNCTION_NAME} eq 'bc' and @{$arg_anal->{ARG_COMB}}; # as of levmar-2.6, a dscl arg
1955 my $pdl_func_name;
1956 $pdl_func_name = $arg_anal->{PDL_FUNC_NAME_DER} if $der eq 'analytic';
1957 $pdl_func_name = $arg_anal->{PDL_FUNC_NAME_DIFF} if $der eq 'numeric';
1958 pp_def( $pdl_func_name,
1959 Pars => " p(m); x(n); t(nt); $h->{SIG} int iopts(in); opts(nopt); [t] work(wn);
1960 [o] covar(m,m) ; int [o] returnval();
1961 [o] pout(m); [o] info(q=10); ",
1962 OtherPars => " IV funcn; IV sfuncn; $h->{OPAR} IV indat; "
1963 . " int want_covar; ",
1964 RedoDimsCode => "
1965 int im = \$PDL(p)->dims[0];
1966 int in = \$PDL(x)->dims[0];
1967 int min = $h->{WORKFAC}*in + 4*im + in*im + im*im;
1968 int inw = \$PDL(work)->dims[0];
1969 \$SIZE(wn) = inw >= min ? inw : min;
1970 ",
1971 GenericTypes => ['F','D'], Doc => undef,
1972 Code => "
1973 int * iopts;
1974 int maxits;
1975 void * tfuncn = (void *) \$COMP(funcn);
1976 void * tsfuncn = (void *) \$COMP(sfuncn);
1977 \$GENERIC(covar) * pcovar;
1978 \$GENERIC(work) * pwork;
1979 $h->{DUMI};
1980 DFP *dat = (void *) \$COMP(indat);
1981 DFP_check( &dat, PDL_\$TFD(F,D), \$SIZE(m), \$SIZE(n),
1982 \$SIZE(nt), \$P(t) );
1983 broadcastloop %{
1984 loop(m) %{
1985 \$pout() = \$p();
1986 %}
1987 iopts = \$P(iopts);
1988 pcovar = \$COMP(want_covar) == 1 ? \$P(covar) : NULL;
1989 pwork = $h->{NOWORK} == 1 ? NULL : \$P(work);
1990 maxits = iopts[0]; /* for clarity. we hope optimized away */
1991 \$returnval() = \$TFD(s,d)levmar_$h->{CALL} (
1992 t\$TFD(s,)funcn , $h->{ARG}
1993 \$P(pout), \$P(x), \$SIZE(m), \$SIZE(n), $h->{ARG2}
1994 maxits, \$P(opts), \$P(info), pwork, pcovar, dat);
1995 %}
1996 "
1997 );
1998 }
1999 }
2000 }
2001  
2002 # same routine defined above, but in Levmar.pm code
2003 sub make_pdl_levmar_func_key {
2004 my ($arg_str, $deriv_type) = @_;
2005 return $deriv_type . '_' . $arg_str;
2006 }
2007  
2008  
2009  
2010 sub make_pdl_levmar_func_name_from_strings {
2011 my ($arg_str, $deriv_type) = @_;
2012 return 'levmar_' . make_pdl_levmar_func_key($arg_str, $deriv_type);
2013 }
2014  
2015  
2016 my $a = make_argument_combinations();
2017 write_pp_defs($a);
2018  
2019  
2020  
2021 =pod
2022  
2023 =begin comment
2024  
2025 /*
2026 * Check the jacobian of a n-valued nonlinear function in m variables
2027 * evaluated at a point p, for consistency with the function itself.
2028 *
2029 * Based on fortran77 subroutine CHKDER by
2030 * Burton S. Garbow, Kenneth E. Hillstrom, Jorge J. More
2031 * Argonne National Laboratory. MINPACK project. March 1980.
2032 *
2033 *
2034 * func points to a function from R^m --> R^n: Given a p in R^m it yields hx in R^n
2035 * jacf points to a function implementing the jacobian of func, whose correctness
2036 * is to be tested. Given a p in R^m, jacf computes into the nxm matrix j the
2037 * jacobian of func at p. Note that row i of j corresponds to the gradient of
2038 * the i-th component of func, evaluated at p.
2039 * p is an input array of length m containing the point of evaluation.
2040 * m is the number of variables
2041 * n is the number of functions
2042 * adata points to possible additional data and is passed uninterpreted
2043 * to func, jacf.
2044 * err is an array of length n. On output, err contains measures
2045 * of correctness of the respective gradients. if there is
2046 * no severe loss of significance, then if err[i] is 1.0 the
2047 * i-th gradient is correct, while if err[i] is 0.0 the i-th
2048 * gradient is incorrect. For values of err between 0.0 and 1.0,
2049 * the categorization is less certain. In general, a value of
2050 * err[i] greater than 0.5 indicates that the i-th gradient is
2051 * probably correct, while a value of err[i] less than 0.5
2052 * indicates that the i-th gradient is probably incorrect.
2053 *
2054 *
2055 * The function does not perform reliably if cancellation or
2056 * rounding errors cause a severe loss of significance in the
2057 * evaluation of a function. therefore, none of the components
2058 * of p should be unusually small (in particular, zero) or any
2059 * other value which may cause loss of significance.
2060 */
2061  
2062 =end comment
2063  
2064 =cut
2065  
2066 pp_def('_levmar_chkjac', Pars => ' p(m); t(n); [o] err(n); ',
2067 OtherPars => ' IV func; IV sfunc; IV jac; IV sjac; IV indat; ',
2068 GenericTypes => ['F','D'], Doc => undef,
2069 Code => '
2070 void * f = (void *) $COMP(func);
2071 void * sf = (void *) $COMP(sfunc);
2072 void * j = (void *) $COMP(jac);
2073 void * sj = (void *) $COMP(sjac);
2074 DFP *dat = (void *) $COMP(indat);
2075 DFP_check( &dat, PDL_$TFD(F,D), $SIZE(m), $SIZE(n), $SIZE(n), $P(t) );
2076 $TFD(s,d)levmar_chkjac (
2077 $TFD(s,)f, $TFD(s,)j,$P(p),$SIZE(m),$SIZE(n),dat,$P(err)
2078 );
2079 '
2080 );
2081  
2082 # From perl5 internals, chapter 4 ...
2083 #Perl's integer type is not necessarily a C int; it's called
2084 #an IV, or Integer Value. The difference is that an IV is
2085 #guaranteed to hold a pointer.
2086  
2087  
2088 pp_def('_levmar_chkjac_no_t', Pars => ' p(m); [o] err(n); ',
2089 OtherPars => 'IV func; IV sfunc; IV jac; IV sjac; int N; IV indat; ',
2090 GenericTypes => ['F','D'], Doc => undef,
2091 RedoDimsCode => "
2092 int N = \$COMP(N);
2093 int nin = \$PDL(err)->dims[0];
2094 \$SIZE(n) = nin >= N ? nin : N;
2095 ",
2096 Code => '
2097 void * f = (void *) $COMP(func);
2098 void * sf = (void *) $COMP(sfunc);
2099 void * j = (void *) $COMP(jac);
2100 void * sj =(void *) $COMP(sjac);
2101 DFP *dat = (void *) $COMP(indat);
2102 DFP_check( &dat, PDL_$TFD(F,D), $SIZE(m), $SIZE(n), $SIZE(n), NULL );
2103 $TFD(s,d)levmar_chkjac (
2104 $TFD(s,)f, $TFD(s,)j,$P(p),$SIZE(m),$SIZE(n),dat,$P(err)
2105 );
2106 '
2107 );
2108  
2109  
2110 =pod
2111  
2112 =begin comment
2113  
2114 No end of trouble cause by confusion over passing ints and chars
2115 and so forth. I am sticking with using ints for pointers for the
2116 time being.
2117  
2118 =end comment
2119  
2120 =cut
2121  
2122  
2123 pp_addxs( '', '
2124  
2125  
2126 void *
2127 DFP_create()
2128  
2129 CODE:
2130 DFP * dat;
2131 dat = (DFP *)malloc(sizeof( DFP ));
2132 if ( NULL == dat ) {
2133 fprintf(stderr, "Can\'t allocate storage for dat in DFP_create\n");
2134 exit(1);
2135 }
2136 RETVAL = dat;
2137 OUTPUT:
2138 RETVAL
2139  
2140 void
2141 DFP_free( dat )
2142 IV dat
2143
2144 CODE:
2145 if ( (DFP *) dat) free( (DFP *) dat);
2146  
2147  
2148 void
2149 DFP_set_perl_funcs ( data, perl_fit_func, perl_jac_func )
2150 IV data
2151 SV* perl_fit_func
2152 SV* perl_jac_func
2153  
2154 CODE:
2155 DFP *dat = (DFP *) data;
2156 if ( dat == NULL ) {
2157 fprintf(stderr, "DFP_set_perl_funcs got null struct\n");
2158 exit(1);
2159 }
2160 dat->perl_fit_func = perl_fit_func;
2161 dat->perl_jac_func = perl_jac_func;
2162  
2163  
2164 double
2165 get_dbl_max( )
2166 CODE:
2167 RETVAL = DBL_MAX;
2168 OUTPUT:
2169 RETVAL
2170  
2171 double
2172 LM_INIT_MU( )
2173 CODE:
2174 RETVAL = LM_INIT_MU;
2175 OUTPUT:
2176 RETVAL
2177  
2178 double
2179 LM_STOP_THRESH( )
2180 CODE:
2181 RETVAL = LM_STOP_THRESH;
2182 OUTPUT:
2183 RETVAL
2184  
2185 double
2186 LM_DIFF_DELTA( )
2187 CODE:
2188 RETVAL = LM_DIFF_DELTA;
2189 OUTPUT:
2190 RETVAL
2191  
2192  
2193 =pod
2194  
2195  
2196 =begin comment
2197  
2198 The next two routines just get pointers to functions from
2199 the C code and return them as SVs to perl. The functions
2200 are the C wrappers to the users _perl_ fit and jacobian
2201 functions. LEVFUNC and JLEVFUNC should be re-entrant so
2202 the following two routines can called once when the
2203 Levmar::Func module is loaded and can be shared by all
2204 object instances.
2205  
2206 =end comment
2207  
2208 =cut
2209  
2210 void *
2211 get_perl_func_wrapper( )
2212  
2213 CODE:
2214 RETVAL = &LEVFUNC;
2215 OUTPUT:
2216 RETVAL
2217  
2218 void *
2219 get_perl_jac_wrapper( )
2220  
2221 CODE:
2222 RETVAL = &JLEVFUNC;
2223 OUTPUT:
2224 RETVAL
2225  
2226  
2227  
2228 ');
2229  
2230  
2231 pp_done();
2232  
2233  
↑ Summary Func/func.pd »