blib/lib/PDL/Opt/Simplex/Simple.pm

filter: Statementstmt 90.0% 18 / 20 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.5% 25 / 27 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 # This program is free software; you can redistribute it and/or modify
2 # it under the terms of the GNU General Public License as published by
3 # the Free Software Foundation; either version 3 of the License, or
4 # (at your option) any later version.
5 #
6 # This program is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # GNU Library General Public License for more details.
10 #
11 # You should have received a copy of the GNU General Public License
12 # along with this program; if not, write to the Free Software
13 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
14 #
15 # Copyright (C) 2021- eWheeler, Inc. L<https://www.linuxglobal.com/>
16 # Originally written by Eric Wheeler, KJ7LNW
17 # All rights reserved.
18 #
19 # All tradmarks, product names, logos, and brands are property of their
20 # respective owners and no grant or license is provided thereof.
21  
22 package PDL::Opt::Simplex::Simple;
23 $VERSION = '1.7';
24  
25 1 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 1 ▶use Math::Round qw/nearest/;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 1 ▶use Time::HiRes qw/time/;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 #use Data::Dumper;
32  
33 1 ▶use PDL;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 1 ▶use PDL::Opt::Simplex;
Subroutine BEGIN: called CC=1 SCAR=2.6
35  
36 sub new
37 {
38 my ($class, %args) = @_;
39  
40 my %valid_opts = map { $_ => 1 }
41 qw/f log vars ssize nocache max_iter tolerance srand
42 stagnant_minima_count stagnant_minima_tolerance
43 reduce_search/;
44  
45 foreach my $k (keys %args)
46 {
47 next if $k =~ /^_/;
48 die "invalid option: $k" if !$valid_opts{$k};
49 }
50  
51 my $self = bless(\%args, $class);
52  
53 $self->{tolerance} //= 1e-6;
54 $self->{max_iter} //= 1000;
55 $self->{ssize} //= 1;
56 $self->{stagnant_minima_tolerance} //= $self->{tolerance};
57
58 if ($self->{srand})
59 {
60 srand($self->{srand});
61 }
62 else
63 {
64 # Generate a 15-digit random seed. This is necessary because
65 # PDL::srand does not return the seed---so we generate one, set
66 # it, and keep it for the calling application if they are
67 # interested. Note that this is not meant to be
68 # cryptographically strong, just a way to set a known seed to
69 # replay the same simplex cycle for testing. If you get a good
70 # result and it is dependent on this value then you might want
71 # to keep it around.
72 #
73 # See this issue for detail:
74 # https://github.com/PDLPorters/pdl/issues/398
75 $self->{srand} = int(rand() * (10**15));
76 srand($self->{srand});
77 }
78  
79 # _ssize is the array for multiple simplex retries.
80 if (ref($self->{ssize}) eq 'ARRAY')
81 {
82 $self->{_ssize} = $self->{ssize};
83  
84 $self->{ssize} = $self->{ssize}[0];
85 }
86 else
87 {
88 $self->{_ssize} = [ $self->{ssize} ];
89 }
90  
91 $self->set_vars($self->{vars});
92  
93 # vars, ssize, tolerance, max_iter, f, log
94 return $self;
95 }
96  
97 sub optimize
98 {
99 my $self = shift;
100  
101 $self->{optimization_pass} = 1;
102 $self->{log_count} = 0;
103  
104 delete $self->{best_minima};
105 delete $self->{best_vars};
106 delete $self->{best_vec};
107 delete $self->{best_pass};
108  
109 if (@{ $self->{_ssize} } == 1)
110 {
111 return $self->_optimize;
112 }
113  
114 # Iterate multiple ssize passes if {ssize} was passed as an array:
115 my $result;
116 foreach my $ssize (@{ $self->{_ssize} })
117 {
118 $self->set_ssize($ssize);
119 $result = $self->_optimize;
120 $self->set_vars($result);
121 $self->{optimization_pass}++;
122 $self->{log_count} = 0;
123 }
124  
125 return $result;
126 }
127  
128 sub _optimize
129 {
130 my $self = shift;
131  
132 my $vec_initial = $self->_build_simplex_vars();
133  
134 $self->{cancel} = 0;
135  
136 delete $self->{prev_minima};
137 delete $self->{prev_minima_count};
138  
139 # Make an initial call if this is the first pass to create a basis for
140 # {best_vars} in case the starting point is better than all other
141 # simplex attempts. The result will be cached so if Simplex calls with
142 # the same value then it will not waste an iteration (unless nocache is
143 # flagged).
144 #
145 # Also call the log function in case it is useful:
146 if ($self->{optimization_pass} == 1)
147 {
148 my $vec_result = $self->_simplex_f($vec_initial);
149 $self->_simplex_log($vec_initial, $vec_result, pdl $self->{ssize});
150 }
151  
152 my ( $vec_optimal, $opt_ssize, $optval );
153  
154 # Catch early cancellation
155 eval {
156 ($vec_optimal, $opt_ssize, $optval) = simplex($vec_initial,
157 $self->{ssize},
158 $self->{tolerance},
159 $self->{max_iter},
160  
161 # We need to lambda $self into place for the f() and log() callbacks:
162 sub {
163 my ($vec) = @_;
164 return $self->_simplex_f($vec);
165 },
166  
167 # log callback
168 sub {
169 my ($vec, $vals, $ssize) = @_;
170 $self->_simplex_log(@_);
171 }
172 );
173 };
174 my $err = $@;
175  
176 if (!$err)
177 {
178 $self->{vec_optimal} = $vec_optimal;
179 $self->{opt_ssize} = $opt_ssize;
180 $self->{minima} = $optval->sclr;
181 }
182 elsif (!$self->{cancel})
183 {
184 # re-die if it died for a reason other than cancellation:
185 die $err;
186 }
187 else
188 {
189 # Log the cancellation:
190 $self->_simplex_log(
191 $self->{best_vec},
192 $self->_simplex_f($self->{best_vec}),
193 $self->{prev_ssize}
194 );
195 }
196  
197 # Return the result in the original vars format that was
198 # passed to new(vars => {...}) so it matches what the user
199 # is expecting by converting it from simple to expanded
200 # and finally to original:
201  
202  
203 # Using {best_vec} might end up using a value from a previous pass,
204 # completely disregarding the current pass best of $vec_optimal. This
205 # should be OK because we make sure that {best_vars} is always populed
206 # by the minimum value returned by f().
207 my $result = $self->{best_vars};
208  
209 $result = _simple_to_expanded($result);
210  
211 $result = $self->_expanded_to_original($result);
212  
213 # Round final values if any vars have round_result defined:
214 _vars_round_result($result);
215  
216 # Store the result in the user's format:
217 $self->{result} = $result;
218  
219 return $result;
220 }
221  
222 # This is the simplex callback to evaluate the function "f()"
223 # based on the content of $self->{vars}:
224 sub _simplex_f
225 {
226 my ($self, $vec) = @_;
227  
228 my @vars = $self->_get_simplex_vars($vec);
229  
230 die "BUG: _vars_are_pdl but \@vars > 1!" if $self->{_vars_are_pdl} and @vars > 1;
231  
232 # @f_ret is accumulated with iterations over f() when
233 # vars are not PDL's because simplex may provide f() with an
234 # array of values to test even though the caller's {f}->() may
235 # not support PDLs.
236 #
237 # However, if the caller's vars are all PDLs then _get_simplex_vars
238 # will return a single-element array.
239 my @f_ret;
240  
241 # Sometimes PDL provides multiple variable sets to calculate. If 'reduce_search'
242 # is flagged then treat them as the same and only evaluate the first variable set.
243 # This speeds up the optimization but may provide suboptimal results.
244 if ($self->{reduce_search})
245 {
246 # Call the user's function and pass their vars.
247 my $ret = $self->call_f($vars[0]);
248  
249 # @f_ret is the resulting weight, which is the same for _all_ vars:
250 push @f_ret, $ret foreach @vars;
251 }
252 else
253 {
254 foreach my $vars (@vars)
255 {
256 # Call the user's function and pass their vars.
257 # @f_ret is the resulting weight for _each_ var:
258 push @f_ret, $self->call_f($vars);
259 }
260 }
261  
262 # We could always `pdl \@f_ret` but it creates a double-nested single
263 # dimension array pdl. Better to leave things as they are and only
264 # create a PDL from the array if it wasn't a PDL to begin with
265 # (ie, when !$self->{_vars_are_pdl}).
266 my $f_ret;
267  
268 if ($self->{_vars_are_pdl})
269 {
270 die "BUG: _vars_are_pdl but \@f_ret > 1!" if @f_ret > 1;
271 $f_ret = $f_ret[0];
272 }
273 else
274 {
275 $f_ret = pdl \@f_ret;
276 }
277  
278 # $f_ret is guaranteed to be PDL here. Find the minimum result,
279 # that is our best index for this iteration:
280 my $min_ind = minimum_ind($f_ret);
281 die "best_minima: min_ind > 1: $f_ret" if ($min_ind->nelem > 1);
282  
283 my $best_minima = $f_ret->index($min_ind);
284 my $best_vars = $vars[$min_ind->sclr]; # better way to unpdl?
285 if (!defined($self->{best_minima}) || $best_minima < $self->{best_minima})
286 {
287 $self->{best_minima} = $best_minima;
288 $self->{best_vec} = $vec;
289 $self->{best_vars} = $best_vars;
290 $self->{best_pass} = $self->{optimization_pass};
291 }
292  
293 return $f_ret;
294 }
295  
296 sub _simplex_log
297 {
298 # $vec is the array of values being optimized
299 # $vals is f($vec)
300 # $ssize is the simplex size, or roughly, how close to being converged.
301 my ($self, $vec, $vals, $ssize) = @_;
302  
303 $self->{prev_ssize} = $ssize;
304 return unless (defined($self->{log}));
305  
306 my $elapsed;
307 if ($self->{prev_time})
308 {
309 $elapsed = time() - $self->{prev_time};
310 }
311 $self->{prev_time} = time();
312  
313 $self->{log_count}++;
314  
315 my $minima = $self->{best_minima};
316  
317 # Cancel early if stagnated:
318 if (defined($self->{stagnant_minima_count}) &&
319 defined($self->{prev_minima}) && $self->{prev_minima} < $minima &&
320 abs($self->{prev_minima} - $minima) < $self->{stagnant_minima_tolerance})
321 {
322 $self->{prev_minima_count}++;
323 if (!$self->{cancel} && $self->{prev_minima_count} > $self->{stagnant_minima_count})
324 {
325 $self->{cancel} = 1;
326 die "CANCEL";
327 }
328 }
329 elsif (!$self->{cancel})
330 {
331 # Record the minima for the previous iteration
332 # to see if it needs to cancel (above).
333 $self->{prev_minima} = $minima;
334 $self->{prev_minima_count} = 0;
335 }
336  
337  
338 my @log_vars = $self->_get_simplex_vars($vec);
339 $self->{log}->($log_vars[0], {
340 ssize => $ssize->sclr,
341 minima => $minima,
342 elapsed => $elapsed,
343 srand => $self->{srand},
344 optimization_pass => $self->{optimization_pass},
345  
346 num_passes => scalar( @{ $self->{_ssize} }),
347 best_pass => $self->{best_pass},
348 best_minima => $self->{best_minima}->sclr,
349 best_vars => $self->{best_vars},
350 log_count => $self->{log_count},
351 cancel => $self->{cancel},
352 prev_minima_count => $self->{prev_minima_count},
353 cache_hits => $self->{cache_hits},
354 cache_misses => $self->{cache_misses},
355 all_vars => \@log_vars
356 });
357 }
358  
359  
360 sub get_vars_expanded
361 {
362 my $self = shift;
363  
364 return $self->{vars};
365 }
366  
367 sub get_vars_orig
368 {
369 my $self = shift;
370  
371 return $self->{_vars_orig};
372 }
373  
374  
375 sub get_vars_simple
376 {
377 my $self = shift;
378  
379 return _expanded_to_simple($self->{vars});
380 }
381  
382 sub get_result_expanded
383 {
384 my $self = shift;
385  
386 return $self->{result};
387 }
388  
389 sub get_result_simple
390 {
391 my $self = shift;
392  
393 return _expanded_to_simple($self->{result});
394 }
395  
396 sub set_vars
397 {
398 my ($self, $vars) = @_;
399  
400 # _simple_to_expanded will die if invalid:
401 $self->{_vars_orig} = $vars;
402 $self->{vars} = _simple_to_expanded($vars);
403 }
404  
405 sub set_ssize
406 {
407 my ($self, $ssize) = @_;
408  
409 $self->{ssize} = $ssize;
410 }
411  
412 sub scale_ssize
413 {
414 my ($self, $scale) = @_;
415  
416 $self->{ssize} *= $scale;
417 }
418  
419  
420  
421 # build a pdl for use by simplex()
422 sub _build_simplex_vars
423 {
424 my ($self) = @_;
425  
426 my $vars = $self->{vars};
427  
428 my @pdl_vars;
429  
430 my $any_pdl;
431 my $any_scalar;
432 foreach my $var_name (sort keys(%$vars))
433 {
434 my $var = $vars->{$var_name};
435  
436 my $n = scalar(@{ $var->{values} });
437  
438 for (my $i = 0; $i < $n; $i++)
439 {
440 # var is enabled for simplex if enabled[$i] == 1
441 if ($var->{enabled}->[$i])
442 {
443 my $val = $var->{values}->[$i];
444 $any_pdl++ if ref($val) eq 'PDL';
445 $any_scalar++ if !ref($val);
446 push(@pdl_vars, $val / $var->{perturb_scale}->[$i]);
447 }
448 }
449 }
450  
451 die "Your {vars} must be either all scalar or all PDL's" if ($any_pdl && $any_scalar);
452  
453 $self->{_vars_are_pdl} = 1 if ($any_pdl);
454  
455 my $pdl = pdl \@pdl_vars;
456 return $pdl;
457 }
458  
459 sub _simple_to_expanded
460 {
461 my ($vars) = @_;
462  
463 my %valid_opts = map { $_ => 1 } qw/values enabled minmax perturb_scale round_each round_result/;
464  
465 my %exp;
466 foreach my $var_name (keys(%$vars))
467 {
468 my $var = $vars->{$var_name};
469  
470 # Copy the structure from what was passed into the %exp
471 # hash so we can modify it without changing the orignal.
472 if (is_numeric($var))
473 {
474 $var = $exp{$var_name} = { values => [ $vars->{$var_name} ] }
475 }
476 elsif (ref($var) eq 'ARRAY')
477 {
478 $var = $exp{$var_name} = { values => $vars->{$var_name} }
479 }
480 elsif (ref($var) eq 'HASH')
481 {
482 my $newvar = $exp{$var_name} = {};
483  
484 foreach my $opt (keys %$var)
485 {
486 die "invalid option for $var_name: $opt" if (!$valid_opts{$opt});
487 }
488  
489 foreach my $opt (keys %valid_opts)
490 {
491 $newvar->{$opt} = $var->{$opt} if exists($var->{$opt});
492 }
493  
494 $var = $newvar;
495 }
496 else
497 {
498 die "invalid type for $var_name: " . ref($var);
499 }
500  
501 # Make sure values is valid:
502 if (!defined($var->{values}) ||
503 (ref($var->{values}) eq 'ARRAY' && !@{$var->{values}}))
504 {
505 die "$var_name\-\>{values} must be defined"
506 }
507  
508 if (ref($var->{values}) eq 'ARRAY')
509 {
510 # make a copy to release the original reference:
511 $var->{values} = [ @{ $var->{values} } ];
512 }
513 elsif (is_numeric($var->{values}))
514 {
515 $var->{values} = [ $var->{values} ];
516 }
517 else
518 {
519 die "invalid type for $var_name\-\>{values}: " . ref($var->{values});
520 }
521  
522 my $n = scalar(@{ $var->{values} });
523  
524  
525 # If enabled is missing or a non-scalar (ie =1 or =0) then form it properly
526 # as either all 1's or all 0's:
527 if (!defined($var->{enabled}) || (is_numeric($var->{enabled}) && $var->{enabled}))
528 {
529 $var->{enabled} = [ map { 1 } (1..$n) ]
530 }
531 elsif (defined($var->{enabled}) && is_numeric($var->{enabled}) && !$var->{enabled})
532 {
533 $var->{enabled} = [ map { 0 } (1..$n) ]
534 }
535  
536 if (ref($var->{minmax}) eq 'ARRAY' && is_numeric($var->{minmax}->[0]) && @{$var->{minmax}} == 2)
537 {
538 $var->{minmax} = [ map { $var->{minmax} } (1..$n) ];
539 }
540  
541 # Default the perturb_scale to 1x
542 $var->{perturb_scale} //= [ map { 1 } (1..$n) ];
543  
544 # Make it an array the of length $n:
545 if (is_numeric($var->{perturb_scale}))
546 {
547 $var->{perturb_scale} = [ map { $var->{perturb_scale} } (1..$n) ]
548 }
549  
550 if (defined($var->{round_each}) && is_numeric($var->{round_each}))
551 {
552 $var->{round_each} = [ map { $var->{round_each} } (1..$n) ]
553 }
554  
555 if (defined($var->{round_result}) && is_numeric($var->{round_result}))
556 {
557 $var->{round_result} = [ map { $var->{round_result} } (1..$n) ]
558 }
559  
560 # Sanity checks
561 if (defined($var->{enabled}) && $n != scalar(@{ $var->{enabled} }))
562 {
563 die "variable $var_name must have the same length array for 'values' as for 'enabled'"
564 }
565  
566 if (defined($var->{perturb_scale}) && $n != scalar(@{ $var->{perturb_scale} }))
567 {
568 die "variable $var_name must have the same length array for 'values' as for 'perturb_scale'"
569 }
570  
571 if (defined($var->{minmax}))
572 {
573 if ($n != scalar(@{ $var->{minmax} }))
574 {
575 die "variable $var_name must have the same length array for 'values' as for 'minmax'"
576 }
577  
578 for (my $i = 0; $i < $n; $i++)
579 {
580 my $mm = $var->{minmax}->[$i];
581  
582 if (ref($mm) ne 'ARRAY' || @$mm != 2)
583 {
584 die "$var_name\-\>{minmax} is not a 2-dimensional arrayref with [min,max] for each.";
585 }
586  
587 my ($min, $max) = @$mm;
588  
589 if ($var->{values}->[$i] < $min)
590 {
591 die "initial value for $var_name\[$i] beyond constraint: $var->{values}->[$i] < $min "
592 }
593  
594 if ($var->{values}->[$i] > $max)
595 {
596 die "initial value for $var_name\[$i] beyond constraint: $var->{values}->[$i] > $max "
597 }
598 }
599 }
600 }
601  
602 return \%exp;
603 }
604  
605 # Return vars as documented below in POD:
606 sub _expanded_to_simple
607 {
608 my $vars = shift;
609  
610 my %h;
611  
612 foreach my $var (keys %$vars)
613 {
614 if (ref($vars->{$var}) eq 'HASH')
615 {
616 defined($vars->{$var}->{values}) or die "undefined 'values' array for var: $var";
617 $h{$var} = $vars->{$var}->{values};
618 }
619 elsif (ref($vars->{$var}) eq 'ARRAY')
620 {
621 $h{$var} = $vars->{$var};
622 }
623 elsif (is_numeric($vars->{$var}))
624 {
625 $h{$var} = [ $vars->{$var} ];
626 }
627 else
628 {
629 die "unknown ref for var=$var: " . ref($vars->{$var});
630 }
631  
632 if (ref($h{$var}) eq 'ARRAY' && scalar(@{ $h{$var} } ) == 1)
633 {
634 $h{$var} = $h{$var}->[0];
635 }
636 }
637  
638 return \%h;
639 }
640  
641  
642 # Return the $exp vars in the same original format as defined by $orig. This is called as follows:
643 # $self->_expanded_to_original($self->{vars})
644 #
645 sub _expanded_to_original
646 {
647 my ($self, $exp) = @_;
648  
649 my $orig = $self->{_vars_orig};
650  
651 my %result;
652 foreach my $var_name (keys(%$orig))
653 {
654 if (is_numeric($orig->{$var_name}))
655 {
656 $result{$var_name} = $exp->{$var_name}->{values}->[0];
657 }
658 elsif (ref($orig->{$var_name}) eq 'ARRAY')
659 {
660 $result{$var_name} = [ @{ $exp->{$var_name}->{values} } ];
661 }
662 elsif (ref($orig->{$var_name}) eq 'HASH')
663 {
664 my $origvar = $orig->{$var_name};
665 my $newvar = {};
666  
667 if (ref($orig->{$var_name}->{values}) eq 'ARRAY')
668 {
669 $newvar->{values} = [ @{ $exp->{$var_name}->{values} } ];
670 }
671 else
672 {
673 $newvar->{values} = $exp->{$var_name}->{values}->[0];
674 }
675  
676 foreach my $opt (qw/enabled minmax perturb_scale round_each round_result/)
677 {
678 $newvar->{$opt} = $origvar->{$opt} if exists($origvar->{$opt});
679 }
680  
681 $result{$var_name} = $newvar;
682 }
683 }
684  
685 return \%result;
686 }
687  
688 # Use the round_result attribute of each var (if defined) to round
689 # the var to its nearest value. $vars must be in expanded format.
690 sub _vars_round_result
691 {
692 my ($vars) = @_;
693  
694 foreach my $var_name (keys(%$vars))
695 {
696 my $var = $vars->{$var_name};
697 my @round_result;
698  
699 next if ref($var) ne 'HASH';
700 next unless defined $var->{round_result};
701  
702 # In case values it not an array:
703 if (is_numeric($var->{values}))
704 {
705 $var->{values} = pdl_nearest($var->{round_result}, $var->{values}, 'round_result');
706 next;
707 }
708  
709 my $n = @{ $var->{values} };
710  
711 # use temp var @round_result so we don't mess with the $vars structure.
712 if (is_numeric($var->{round_result}))
713 {
714 @round_result = map { $var->{round_result} } (1..$n);
715 }
716 else
717 {
718 @round_result = @{ $var->{round_result} };
719 }
720  
721 # Round to a precision if defined:
722 foreach (my $i = 0; $i < $n; $i++)
723 {
724 $var->{values}->[$i] = pdl_nearest($round_result[$i], $var->{values}->[$i], 'round_result');
725 }
726 }
727  
728 }
729  
730 # get a var by name from $self->{vars} but get the value from the pdl if
731 # the var is enabled for optimization. Also minmax/perturb_scale as if defined.
732 # Returns an array of values representing the variable vector, even if the
733 # variable is single-valued.
734 sub _get_simplex_var
735 {
736 my ($self, $pdl, $var_name) = @_;
737  
738 my $vars = $self->{vars};
739  
740 my @ret;
741
742 my $var = $vars->{$var_name};
743  
744 my $pdl_idx = 0;
745  
746 # skip ahead to where the pdl_idx that we need is located if $var_name
747 # is not the first $var we find in the list:
748 foreach my $vn (sort keys(%$vars))
749 {
750 my $var = $vars->{$vn};
751  
752 # done if we find it:
753 last if $vn eq $var_name;
754  
755 # Increment pdl_idx for each element of the {enabled} array
756 # that is enabled because that is how it is packed into the pdl.
757 # The value of $_ in grep{} is either 1 or 0:
758 $pdl_idx++ foreach (grep { $_ } @{ $var->{enabled} });
759 }
760  
761 # Iterate each value and pull it in from the simplex vector
762 # if that particular array index is enabled:
763 my $n = scalar(@{ $var->{values} });
764  
765 for (my $i = 0; $i < $n; $i++)
766 {
767 my $val;
768  
769 # use the pdl index if it is enabled for optimization
770 # otherwise use the original index in $var.
771 if ($var->{enabled}->[$i])
772 {
773 $val = $pdl->slice("($pdl_idx)");
774 $val *= $var->{perturb_scale}->[$i];
775 $pdl_idx++;
776 }
777 else
778 {
779 $val = $var->{values}->[$i];
780 }
781  
782 # Modify the resulting value depending on these rules:
783 if (defined($var->{minmax}))
784 {
785 my ($min, $max) = @{ $var->{minmax}->[$i] };
786 $val = clamp_minmax($val, $min => $max, $var_name);
787 }
788  
789 # Round to the nearest value on each iteration.
790 # It is probably best to round at the end to keep
791 # precision during each iteration, but the option
792 # is available:
793 if (defined($var->{round_each}))
794 {
795 $val = pdl_nearest($var->{round_each}->[$i], $val, $var_name);
796 }
797  
798 push @ret, $val;
799 }
800  
801 return \@ret;
802 }
803  
804 sub pdl_nearest
805 {
806 my ($nearest, $val, $noun) = @_;
807  
808 $noun //= 'round_each/round_result';
809  
810 if (ref($val) ne 'PDL')
811 {
812 $val = nearest($nearest, $val);
813 }
814 else
815 {
816 # Is there a better way? This assumes the round_each array is not a pdl.
817 # The problem is that simplex will give us a piddle of piddles: we might be
818 # passed a PDL with several sliceable values and we need to call nearest on
819 # each element of each element.
820 #
821 # It would be helpful if PDL had a native nearest() impelementation.
822  
823 my $idx = 0;
824 $val = pdl_map(sub { nearest($nearest, $_[0]) }, $val);
825 }
826  
827 return $val;
828 }
829  
830 sub pdl_map
831 {
832 my ($sub, $val) = @_;
833 my @slices;
834 for (my $slice_idx = 0; $slice_idx < $val->nelem; $slice_idx++)
835 {
836 my $s = $val->slice("($slice_idx)");
837  
838 my $idx = 0;
839 if ($s->nelem > 1)
840 {
841 die "BUG: PDLs with more than one value do not work with the pdl_map function."
842 }
843  
844 $s = $sub->(@{ unpdl $s });
845 push @slices, $s;
846 }
847  
848 # Avoid the PDL of "123" becoming "[123]":
849 if (@slices > 1)
850 {
851 $val = pdl \@slices;
852 }
853 else
854 {
855 $val = pdl $slices[0];
856 }
857  
858 return $val;
859 }
860  
861 sub clamp_minmax
862 {
863 my ($val, $min, $max) = @_;
864  
865 if (ref($val) eq 'PDL')
866 {
867 $val .= $val->clip($min, $max);
868 }
869 elsif ($val < $min)
870 {
871 $val = $min;
872 }
873 elsif ($val > $max)
874 {
875 $val = $max;
876 }
877  
878 return $val;
879 }
880  
881 # get all vars replaced with resultant simplex values if enabled=>1 for that var.
882 sub _get_simplex_vars
883 {
884 my ($self, $pdl) = @_;
885
886 my $vars = $self->{vars};
887  
888 my %h;
889  
890 # Get values by name from _get_simplex_var: each of these will be ARRAY-ref's
891 # even if there is only one value:
892 foreach my $var_name (keys %$vars)
893 {
894 $h{$var_name} = $self->_get_simplex_var($pdl, $var_name);
895 }
896  
897 # If all the input variables are PDL's, then f() must support PDL's as inputs.
898 #
899 # else: If all the input variables are _not_ PDLs, then break the PDL's into
900 # an array of var-hashes and _optimize() will evaluate them iteratively.
901 my @ret;
902 if ($self->{_vars_are_pdl})
903 {
904 @ret = (\%h);
905 }
906 else
907 {
908 # Note: Many of the foreach loops below are dependent on the previous loop
909 # finishing. It is not possible to merge all loops into one as currently
910 # implemented.
911  
912 # First find the $pdl->nelem that was passed by simplex. This is the number of
913 # entries that must be evaluated, and any non-PDL items that exist when
914 # `!$vars->{$var_name}->{enabled}->[$i]` need to be turned into PDLs
915 # of the same number of elements so simplex is happy.
916 #
917 # Really we should be able to `last` at the first PDL we find, but
918 # we iterate all of them to sanity-check the code and trigger a `die` below
919 # if they differ, because that means our assumption about how simplex works is wrong:
920 my $pdl_size;
921 foreach my $var_name (keys %h)
922 {
923 foreach my $a (grep { ref($_) eq 'PDL' } @{ $h{$var_name} })
924 {
925 my $nelem = $a->nelem;
926  
927 if (defined($pdl_size) && $pdl_size != $nelem)
928 {
929 die "BUG: $var_name\->nelem differs from previous vars ($pdl_size != $nelem)";
930 }
931 else
932 {
933 $pdl_size //= $nelem;
934 }
935 }
936 }
937  
938 if (!$pdl_size)
939 {
940 die "pdl_size is undefined or zero, are you using any zero-dimension variable arrays?"
941 }
942  
943 # Now that we know the $pdl_size, make PDLs of the right size for any non-PDLs
944 # so we can slice them into multiple var sets.
945 foreach my $var_name (keys %h)
946 {
947 my @a;
948 foreach my $a (@{ $h{$var_name} })
949 {
950 if (ref($a) eq 'PDL')
951 {
952 push @a, $a;
953 }
954 elsif (ref($a) eq '')
955 {
956 push @a, pdl [ map { $a } (1..$pdl_size ) ]
957 }
958 else
959 {
960 die "$var_name: unhandled ref type: " . ref($a);
961 }
962 }
963 $h{$var_name} = \@a;
964 }
965  
966  
967 # At this point all elements to pass to f() should be PDLs.
968 # Break them into an independent vars hash and place each in
969 # @ret. Note that each of $h{$var_name} is still an ARRAY-ref
970 # even if there is a single element:
971 foreach my $var_name (keys %h)
972 {
973 my $a_idx = 0;
974 foreach my $a (@{ $h{$var_name} })
975 {
976 my $pdl_idx = 0;
977 foreach my $e ($a->list)
978 {
979 $ret[$pdl_idx]->{$var_name}->[$a_idx] = $e;
980 $pdl_idx++;
981 }
982 $a_idx++;
983 }
984 }
985 }
986  
987 # Collapse single-element arrays as scalars so f() doesn't need to
988 # do something like $vars->{x}[0] and can just use $vars->{x} directly:
989 foreach my $r (@ret)
990 {
991 foreach my $var_name (keys %$r)
992 {
993 if (scalar(@{ $r->{$var_name} }) == 1)
994 {
995 $r->{$var_name} = $r->{$var_name}->[0];
996 }
997 }
998 }
999  
1000 die "BUG: _get_simplex_vars: !wantarray but \@ret > 1: pdl=$pdl" if @ret > 1 and !wantarray;
1001  
1002 return $ret[0] if (!wantarray);
1003  
1004 return @ret;
1005 }
1006  
1007 sub get_best_simplex_vars
1008 {
1009 my $self = shift;
1010  
1011 return $self->_get_simplex_vars($self->{best_vec});
1012 }
1013  
1014 sub var_cache
1015 {
1016 my ($self, $vars, $value) = @_;
1017  
1018 return undef if ($self->{nocache});
1019  
1020 my $key = '';
1021 foreach my $var_name (sort keys(%$vars))
1022 {
1023 $key .= "$var_name=";
1024 if (is_numeric($vars->{$var_name}))
1025 {
1026 $key .= $vars->{$var_name}
1027 }
1028 elsif (ref $vars->{$var_name} eq 'ARRAY')
1029 {
1030 $key .= join(',', @{ $vars->{$var_name} });
1031 }
1032 else
1033 {
1034 die "$var_name: invalid ref: " . ref($vars->{$var_name});
1035 }
1036  
1037 $key .= ';'
1038 }
1039  
1040 if (defined($value) && !defined($self->{_var_cache}{$key}))
1041 {
1042 $self->{_var_cache}{$key} = $value;
1043 return $value;
1044 }
1045 elsif (defined($self->{_var_cache}{$key}))
1046 {
1047 $self->{cache_hits}++;
1048 return $self->{_var_cache}{$key};
1049 }
1050 else
1051 {
1052 $self->{cache_misses}++;
1053  
1054 return undef;
1055 }
1056 }
1057  
1058 sub call_f
1059 {
1060 my ($self, $vars) = @_;
1061  
1062 # Try to use a cached result:
1063 my $result = $self->var_cache($vars);
1064  
1065 if (!defined($result))
1066 {
1067 $result = $self->{f}->($vars);
1068 $self->var_cache($vars => $result);
1069 }
1070  
1071 return $result;
1072 }
1073  
1074 sub is_numeric
1075 {
1076 my $var = shift;
1077 return (!ref($var) || ref($var) eq 'PDL')
1078 }
1079  
1080 # This is for debugging:
1081 #
1082 # Builds a tree from $h that is suitable for passing to Data::Dumper.
1083 # This is neccesary because PDL's need to be stringified since Dumper()
1084 # will dump at the object itself.
1085 sub dumpify
1086 {
1087 my $h = shift;
1088  
1089 return "(undef)" if (!defined($h));
1090 return "scalar:$h" if (ref($h) eq '');
1091 return "PDL:$h" if (ref($h) eq 'PDL');
1092  
1093 return { map { $_ => dumpify($h->{$_}) } keys(%$h) } if (ref($h) eq 'HASH');
1094 return [ map { dumpify($_) } @$h ] if (ref($h) eq 'ARRAY');
1095  
1096 die 'dumpify: unhandled reference: ' . ref($h);
1097 }
1098  
1099 1;
1100  
1101 __END__
↑ Summary