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

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