| 1 | use strict; |
| 2 | use warnings; |
| 3 | use Test::More; |
| 4 | use PDL::LiteF; |
| 5 | use PDL::Opt::Simplex; |
| 6 | use Test::PDL -atol => 1e-3; |
| 7 | |
| 8 | sub test_simplex { |
| 9 | local $Test::Builder::Level = $Test::Builder::Level + 1; |
| 10 | my ($init, $initsize, $dis, $nolog) = @_; |
| 11 | my $log_called = 0; |
| 12 | my $logsub = sub {$log_called++}; |
| 13 | my ( $opt, $ssize, $optval ) = simplex( |
| 14 | $init->copy, $initsize, 1e-4, 1e4, sub { |
| 15 | # f = x^2 + (y-1)^2 + 1 |
| 16 | sumover( ( $_[0] - $dis )**2 ) + 1; |
| 17 | }, $nolog ? () : $logsub, |
| 18 | ); |
| 19 | is_pdl $opt, $dis, 'optimum' or diag "got=$opt"; |
| 20 | is_pdl $ssize, pdl(0), 'ssize' or diag "got=$ssize"; |
| 21 | is_pdl $optval, pdl(1), 'optval' or diag "got=$optval"; |
| 22 | ok $log_called, 'log called' if !$nolog; |
| 23 | my @init_dims = $init->dims; |
| 24 | my @exp_dims = ($init_dims[0], 1, @init_dims[2..$#init_dims]); |
| 25 | is_deeply [$opt->dims], \@exp_dims, 'dims optimum right'; |
| 26 | } |
| 27 | |
| 28 | test_simplex(pdl(2,2), 0.01, pdl([[0,1]])); |
| 29 | test_simplex(pdl(2,2), pdl(0.01,0.01), pdl([[0,1]])); |
| 30 | test_simplex(pdl(2,2), pdl(0.01,0.01), pdl([[0,1]]), 1); |
| 31 | test_simplex(pdl(2,2,2), pdl(0.01,0.01,0.01), pdl([[0,1,2]])); |
| 32 | test_simplex(my $p = pdl(q[-1 -1; -1.1 -1; -1.1 -0.9]), pdl(0.01,0.01), pdl([[0,1]])); |
| 33 | test_simplex($p, undef, pdl([[-1,1]])); |
| 34 | |
| 35 | my $s = make_simplex(pdl(0,0,0), pdl(0.12,0.12,0.12)); |
| 36 | is_pdl $s, pdl '0 -0.06 -0.08; 0.12 -0.06 -0.08; 0 0.06 -0.08; 0 0 0.04'; |
| 37 | |
| 38 | done_testing; |