| 1 | package PDL::Opt::Simplex; |
| 2 | use strict; |
| 3 | use warnings; |
| 4 | use PDL; |
| 5 | use PDL::Exporter; |
| 6 | |
| 7 | our @ISA = qw/PDL::Exporter/; |
| 8 | our @EXPORT_OK = qw/simplex make_simplex/; |
| 9 | our %EXPORT_TAGS = ( Func => [@EXPORT_OK] ); |
| 10 | our $VERSION = '2.098'; |
| 11 | |
| 12 | *simplex = \&PDL::simplex; |
| 13 | |
| 14 | sub make_simplex { |
| 15 | my ($init, $initsize) = @_; |
| 16 | my ( $nd, $nd2, @otherdims ) = ( $init->dims, 1 ); |
| 17 | pop @otherdims if @otherdims; # drop the spurious "1" |
| 18 | return unless $nd2 == $nd + 1 or $nd2 == 1; |
| 19 | return $init if $nd2 == $nd + 1; |
| 20 | my $simp = PDL->zeroes( $nd, $nd + 1, @otherdims ); |
| 21 | # Constructing a tetrahedron: |
| 22 | # At step n (starting from zero) |
| 23 | # take vertices 0..n and move them 1/(n+1) to negative dir on axis n. |
| 24 | # Take vertex n+1 and move it n/(n+1) to positive dir on axis n |
| 25 | my $uppertri = $simp->copy; |
| 26 | ones($nd * ($nd+1) / 2)->tritosquare($uppertri->slice(",:-2")->t); |
| 27 | my $iseq = sequence($nd); |
| 28 | my $pjseq = $iseq / ( $iseq + 1 ); |
| 29 | $simp .= $init - $initsize * $pjseq * $uppertri; |
| 30 | $simp->slice(",1:")->diagonal(0,1) += $initsize * (1-$pjseq); |
| 31 | $simp; |
| 32 | } |
| 33 | |
| 34 | sub PDL::simplex { |
| 35 | my ( $init, $initsize, $minsize, $maxiter, $sub, $logsub, $t ) = @_; |
| 36 | my $simp = make_simplex($init, $initsize) // return; |
| 37 | my $nd = $simp->dim(0); |
| 38 | my $vals = $sub->($simp); |
| 39 | my $ssize; |
| 40 | while ($maxiter--) { |
| 41 | $ssize = ( $simp - $simp->slice(":,0") )->magnover->maxover; |
| 42 | $logsub->( $simp, $vals, $ssize ) if $logsub; |
| 43 | last unless $ssize > $minsize; |
| 44 | my $valsn = !$t ? $vals : $vals - $t * log( $vals->random + 0.00001 ); |
| 45 | my $minind = $valsn->minimum_ind; |
| 46 | my $maxind = $valsn->maxover_n_ind(2); |
| 47 | my $maxind0 = $maxind->at(0); |
| 48 | my @worstvals = $valsn->index($maxind)->list; |
| 49 | my $bestval = $valsn->at($minind); |
| 50 | my $ssum = ($simp->t->sumover - (my $worst = $simp->slice(":,($maxind0)"))) / $nd; |
| 51 | my $new = 2 * $ssum - $worst; |
| 52 | my $val = $sub->($new)->at(0); |
| 53 | $val += $t * log( rand() + 0.00001 ) if $t; |
| 54 | my $removetop = 0; |
| 55 | if ( $val < $bestval ) { |
| 56 | my $newnew = $new + $ssum - $worst; |
| 57 | my $val2 = $sub->($newnew); |
| 58 | if ( $val2->at(0) < $val ) { # CASE1 Reflection and Expansion |
| 59 | $new = $newnew; |
| 60 | $val = $val2; |
| 61 | } # else CASE2 Reflection |
| 62 | $removetop = 1; |
| 63 | } elsif ( $val < $worstvals[1] ) { # CASE3 Reflection |
| 64 | $removetop = 1; |
| 65 | } else { |
| 66 | my $newnew = 0.5 * ($ssum + $worst); |
| 67 | my $val2 = $sub->($newnew); |
| 68 | if ( $val2->at(0) < $worstvals[0] ) { # CASE4 Contraction |
| 69 | $new = $newnew; |
| 70 | $val = $val2; |
| 71 | $removetop = 1; |
| 72 | } |
| 73 | } |
| 74 | if ($removetop) { |
| 75 | $worst .= $new; |
| 76 | $vals->slice( "($maxind0)" ) .= $val; |
| 77 | } else { # CASE5 Multiple Contraction |
| 78 | $simp .= 0.5 * ($simp->slice(":,$minind") + $simp); |
| 79 | my $idx = which( sequence($nd+1) != $minind ); |
| 80 | $vals->index($idx) .= $sub->($simp->dice_axis(1,$idx)); |
| 81 | } |
| 82 | } |
| 83 | my $mmind = $vals->minimum_ind; |
| 84 | return ( $simp->slice(":,$mmind"), $ssize, $vals->index($mmind) ); |
| 85 | } |
| 86 | |
| 87 | 1; |
| 88 | |
| 89 | __END__ |
| 90 | |
| 91 | =head1 NAME |
| 92 | |
| 93 | PDL::Opt::Simplex -- Simplex optimization routines |
| 94 | |
| 95 | =head1 SYNOPSIS |
| 96 | |
| 97 | use PDL::Opt::Simplex; |
| 98 | |
| 99 | ($optimum,$ssize,$optval) = simplex($init,$initsize,$minsize, |
| 100 | $maxiter, |
| 101 | sub {evaluate_func_at($_[0])}, |
| 102 | sub {display_simplex($_[0])} |
| 103 | ); |
| 104 | |
| 105 | # more involved: |
| 106 | use PDL; |
| 107 | use PDL::Opt::Simplex; |
| 108 | my $count = 0; |
| 109 | # find value of $x that returns a minimum |
| 110 | sub f { |
| 111 | my ($vec) = @_; |
| 112 | $count++; |
| 113 | my $x = $vec->slice('(0)'); |
| 114 | # The parabola (x+3)^2 - 5 has a minimum at x=-3: |
| 115 | return (($x+3)**2 - 5); |
| 116 | } |
| 117 | sub log { |
| 118 | my ($vec, $vals, $ssize) = @_; |
| 119 | # $vec is the array of values being optimized |
| 120 | # $vals is f($vec) |
| 121 | # $ssize is the simplex size, or roughly, how close to being converged. |
| 122 | my $x = $vec->slice('(0)'); |
| 123 | # each vector element passed to log() has a min and max value. |
| 124 | # ie: x=[6 0] -> vals=[76 4] |
| 125 | # so, from above: f(6) == 76 and f(0) == 4 |
| 126 | print "$count [$ssize]: $x -> $vals\n"; |
| 127 | } |
| 128 | my ($optimum, $ssize, $optval) = simplex(pdl(30), 3, 1e-6, 100, \&f, \&log); |
| 129 | print "ssize=$ssize opt=$optimum -> minimum=$optval\n"; |
| 130 | |
| 131 | =head1 DESCRIPTION |
| 132 | |
| 133 | This package implements the commonly used simplex optimization |
| 134 | algorithm. The basic idea of the algorithm is to move |
| 135 | a "simplex" of N+1 points in the N-dimensional search space |
| 136 | according to certain rules. The main |
| 137 | benefit of the algorithm is that you do not need to calculate |
| 138 | the derivatives of your function. |
| 139 | |
| 140 | C<$init> is a 1D vector holding the initial values of the N fitted |
| 141 | parameters, C<$optimum> is a vector holding the final values. |
| 142 | C<$optval> is the evaluation of the final values. |
| 143 | |
| 144 | C<$initsize> is the size of C<$init>. It is only used if your supplied |
| 145 | C<$init> is a single point in your search space, to construct the simplex |
| 146 | ("cloud") of N+1 points the algorithm uses, being the distance away from |
| 147 | your single C<$init> point along each dimension. This is done by the |
| 148 | exportable function C<make_simplex($init, $initsize)>, e.g.: |
| 149 | |
| 150 | pdl> use PDL::Opt::Simplex |
| 151 | pdl> p $t = make_simplex(pdl(0,0,0), pdl(0.12,0.12,0.12)) |
| 152 | [ |
| 153 | [ 0 -0.06 -0.08] |
| 154 | [ 0.12 -0.06 -0.08] |
| 155 | [ 0 0.06 -0.08] |
| 156 | [ 0 0 0.04] |
| 157 | ] |
| 158 | pdl> use PDL::Graphics::TriD |
| 159 | pdl> spheres3d $t # spheres not points so can easily see |
| 160 | |
| 161 | C<$minsize> is the convergence criterion, e.g. C<$minsize> = 1e-6; |
| 162 | the algorithm will terminate when all the values of C<$ssize> are less |
| 163 | than C<$minsize>. |
| 164 | |
| 165 | The sub is assumed to understand more than 1 dimensions and broadcasting. |
| 166 | Its signature is C<inp(nparams); [ret]out()>. An example would be |
| 167 | |
| 168 | sub evaluate_func_at { |
| 169 | my($xv) = @_; |
| 170 | my ($x1, $x2) = $xv->using(0,1); |
| 171 | return $x1**4 + ($x2-5)**4 + $x1*$x2; |
| 172 | } |
| 173 | |
| 174 | Here C<$xv> is a vector holding the current values of the parameters |
| 175 | being fitted which are then sliced out explicitly as C<$x1> and C<$x2>. |
| 176 | |
| 177 | C<$ssize> gives a very very approximate estimate of how close we might |
| 178 | be - it might be miles wrong. It is the largest Euclidean distance between |
| 179 | the first vertex and any other. If it is not very small, the algorithm |
| 180 | has not converged. |
| 181 | |
| 182 | =head1 FUNCTIONS |
| 183 | |
| 184 | =head2 simplex |
| 185 | |
| 186 | =for ref |
| 187 | |
| 188 | Simplex optimization routine |
| 189 | |
| 190 | Mutates its C<$init> input if given as a full simplex (dims C<n,n+1>). |
| 191 | |
| 192 | =for usage |
| 193 | |
| 194 | ($optimum,$ssize,$optval) = simplex($init,$initsize,$minsize, |
| 195 | $maxiter, |
| 196 | sub {evaluate_func_at($_[0])}, |
| 197 | sub {display_simplex($_[0])} |
| 198 | ); |
| 199 | |
| 200 | See module C<PDL::Opt::Simplex> for more information. |
| 201 | |
| 202 | =head1 CAVEATS |
| 203 | |
| 204 | Do not use the simplex method if your function has local minima. |
| 205 | It will not work. Use genetic algorithms or simulated annealing |
| 206 | or conjugate gradient or momentum gradient descent. |
| 207 | |
| 208 | They will not really work either but they are not guaranteed not to work ;) |
| 209 | (if you have infinite time, simulated annealing is guaranteed to work |
| 210 | but only after it has visited every point in your space). |
| 211 | |
| 212 | =head1 SEE ALSO |
| 213 | |
| 214 | =over |
| 215 | |
| 216 | =item L<PDL::Opt::Simplex::Simple> - Use names for Simplex-optimized values |
| 217 | |
| 218 | =item L<PDL::Opt::ParticleSwarm> - A PDL implementation of Particle Swarm |
| 219 | |
| 220 | =item L<PDL::Opt::ParticleSwarm::Simple> - Use names for Particle Swarm-optimized values |
| 221 | |
| 222 | =item L<https://web.archive.org/web/19981206200518/http://chem1.nrl.navy.mil/~shaffer/chemoweb.html> - Ron Shaffer's chemometrics web page and references therein (archive from 1998) |
| 223 | |
| 224 | =back |
| 225 | |
| 226 | The demonstration (Examples/Simplex/tsimp.pl and tsimp2.pl). |
| 227 | |
| 228 | =head1 AUTHOR |
| 229 | |
| 230 | Copyright(C) 1997 Tuomas J. Lukka. |
| 231 | All rights reserved. There is no warranty. You are allowed |
| 232 | to redistribute this software / documentation under certain |
| 233 | conditions. For details, see the file COPYING in the PDL |
| 234 | distribution. If this file is separated from the PDL distribution, |
| 235 | the copyright notice should be included in the file. |
| 236 | |
| 237 | =cut |