blib/lib/ICC/Support/nPINT.pm untested

filter: Statementstmt 0.0% 0 / 246 Branchbran 0.0% 0 / 64 Conditioncond 0.0% 0 / 124 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 474 CC 33 SCAR 28.0
CC
33
Cov
0%
transform
56.0
jacobian
20.0
sdump
20.0
CRAP 16.4
1 package ICC::Support::nPINT;
2  
3 use strict;
4 use Carp;
5  
6 our $VERSION = 0.71;
7  
8 # revised 2016-05-17
9 #
10 # Copyright © 2004-2018 by William B. Birkett
11  
12 # add development directory
13 use lib 'lib';
14  
15 # inherit from Shared
16 use parent qw(ICC::Shared);
17  
18 # support modules
19 use File::Glob;
20 use POSIX ();
21  
22 =encoding utf-8
23  
24 n-channel polynomial interpolation engine (nPINT), inspired by Francois Lekien, Chad Coulliette and Jerry
25 Marsden, authors of "Tricubic interpolation in three dimensions" and "Tricubic Engine Technical Notes and
26 Full Matrix".
27  
28 create new nPINT object parameter hash structure:
29  
30 {'pda' => [polynomial_degree_array], 'coef' => [nPINT_coefficients]}
31  
32 the polynomial_degree_array contains the polynomial degree for each input channel, e.g. [3, 3, 3, 3] => 4
33 channels, each of degree 3
34  
35 the nPINT coefficients define the behavior of the model. they are normally obtained using the 'fit'
36 method, which uses linear least squares to fit the model to the supplied data. the number of rows in the
37 coefficient array is equal to the product of each channel's degree + 1, e.g. if the pda is [3, 3, 3, 3],
38 there are 256 coefficient rows. the number columns in the coefficient array is equal to the number of
39 output channels.
40  
41 =cut
42  
43 # optional usage forms:
44 # parameters: ()
45 # parameters: (ref_to_parameter_hash)
46 # parameters: (path_to_storable_file)
47 # returns: (object_reference)
48 sub new {
49  
50 # get object class
51 my $class = shift();
52  
53 # create empty nPINT object
54 my $self = [
55 {}, # object header
56 [], # input polynomial degree array
57 [], # output coefficient array
58 undef # cached output coefficient array
59 ];
60  
61 # if one parameter, a hash reference
62 if (@_ == 1 && ref($_[0]) eq 'HASH') {
63
64 # create new object from parameter hash
65 _new_from_hash($self, @_);
66
67 # if any parameters
68 } elsif (@_) {
69
70 # create new object from Storable file
71 _new_from_storable($self, @_) || carp("couldn't read Storable file: $_[0]");
72
73 }
74  
75 # bless object
76 bless($self, $class);
77  
78 # return object reference
79 return($self);
80  
81 }
82  
83 # fit nPINT object to data
84 # uses LAPACK dgels function to perform a least-squares fit
85 # parameters: (ref_to_pda_array, ref_to_input_array, ref_to_output_array)
86 # returns: (dgels_info_value)
87 sub fit {
88  
89 # get parameters
90 my ($self, $pda, $in, $out) = @_;
91  
92 # local variables
93 my ($info, $cols, $coef);
94  
95 # get number of coefficients
96 $cols = ICC::Support::Lapack::xcols($pda);
97
98 # verify input is an array or Math::Matrix object
99 (ref($in) eq 'ARRAY' || UNIVERSAL::isa($in, 'Math::Matrix')) || croak('improper input array type');
100  
101 # verify input structure
102 (ref($in->[0]) eq 'ARRAY' && ! ref($in->[0][0])) || croak('improper input array structure');
103  
104 # verify output is an array or Math::Matrix object
105 (ref($out) eq 'ARRAY' || UNIVERSAL::isa($out, 'Math::Matrix')) || croak('improper output array type');
106  
107 # verify output structure
108 (ref($out->[0]) eq 'ARRAY' && ! ref($out->[0][0])) || croak('improper output array structure');
109  
110 # verify array dimensions
111 ($#{$in} == $#{$out}) || croak('fit input and output arrays have different number of rows');
112  
113 # fit nPINT model
114 ($info, $coef) = ICC::Support::Lapack::nPINT_fit($pda, $in, $out);
115  
116 # check result
117 carp('fit failed - bad parameter when calling dgels') if ($info < 0);
118 carp('fit failed - A matrix not full rank') if ($info > 0);
119  
120 # copy pda to object
121 $self->[1] = [@{$pda}];
122  
123 # copy coefficients to object
124 $self->[2] = [@{$coef}[0 .. $cols - 1]];
125  
126 # update cache
127 $self->[3] = ICC::Support::Lapack::cache_2D($self->[2]);
128  
129 # return info value
130 return($info);
131  
132 }
133  
134 # get/set reference to header hash
135 # parameters: ([ref_to_new_hash])
136 # returns: (ref_to_hash)
137 sub header {
138  
139 # get object reference
140 my $self = shift();
141  
142 # if there are parameters
143 if (@_) {
144
145 # if one parameter, a hash reference
146 if (@_ == 1 && ref($_[0]) eq 'HASH') {
147
148 # set header to new hash
149 $self->[0] = {%{shift()}};
150
151 } else {
152
153 # error
154 croak('parameter must be a hash reference');
155
156 }
157
158 }
159  
160 # return reference
161 return($self->[0]);
162  
163 }
164  
165 # get/set reference to pda array
166 # parameters: ([ref_to_new_array])
167 # returns: (ref_to_array)
168 sub pda {
169  
170 # get object reference
171 my $self = shift();
172  
173 # if there are parameters
174 if (@_) {
175
176 # if one parameter, an array reference
177 if (@_ == 1 && ref($_[0]) eq 'ARRAY') {
178
179 # set CLUT to new array
180 $self->[1] = [@{shift()}];
181
182 } else {
183
184 # error
185 croak('parameter must be an array reference');
186
187 }
188
189 }
190  
191 # return reference
192 return($self->[1]);
193  
194 }
195  
196 # get/set reference to coefficient array
197 # parameters: ([ref_to_new_array])
198 # returns: (ref_to_array)
199 sub array {
200  
201 # get object reference
202 my $self = shift();
203  
204 # if there are parameters
205 if (@_) {
206
207 # if one parameter, an array or a Math::Matrix object
208 if (@_ == 1 && (ref($_[0]) eq 'ARRAY' || UNIVERSAL::isa($_[0], 'Math::Matrix'))) {
209
210 # verify array structure
211 (ref($_[0][0]) eq 'ARRAY' && ! ref($_[0][0][0])) || croak('improper coefficient array structure');
212
213 # set CLUT to new array
214 $self->[2] = bless(Storable::dclone(shift()), 'Math::Matrix');
215
216 # update cache
217 $self->[3] = ICC::Support::Lapack::cache_2D($self->[2]);
218
219 } else {
220
221 # error
222 croak('improper coefficient array type');
223
224 }
225
226 }
227  
228 # return reference
229 return($self->[2]);
230  
231 }
232  
233 # transform data
234 # nominal input range is (0 - 1)
235 # hash key 'ubox' enables unit box extrapolation
236 # supported input types:
237 # parameters: (list, [hash])
238 # parameters: (vector, [hash])
239 # parameters: (matrix, [hash])
240 # parameters: (Math::Matrix_object, [hash])
241 # parameters: (structure, [hash])
242 # returns: (same_type_as_input)
243 sub transform {
244  
245 # set hash value (0 or 1)
246 my $h = ref($_[-1]) eq 'HASH' ? 1 : 0;
247  
248 # if input a 'Math::Matrix' object
249 if (@_ == $h + 2 && UNIVERSAL::isa($_[1], 'Math::Matrix')) {
250
251 # call matrix transform
252 &_trans2;
253
254 # if input an array reference
255 } elsif (@_ == $h + 2 && ref($_[1]) eq 'ARRAY') {
256
257 # if array contains numbers (vector)
258 if (! ref($_[1][0]) && @{$_[1]} == grep {Scalar::Util::looks_like_number($_)} @{$_[1]}) {
259
260 # call vector transform
261 &_trans1;
262
263 # if array contains vectors (2-D array)
264 } elsif (ref($_[1][0]) eq 'ARRAY' && @{$_[1]} == grep {ref($_) eq 'ARRAY' && Scalar::Util::looks_like_number($_->[0])} @{$_[1]}) {
265
266 # call matrix transform
267 &_trans2;
268
269 } else {
270
271 # call structure transform
272 &_trans3;
273
274 }
275
276 # if input a list (of numbers)
277 } elsif (@_ == $h + 1 + grep {Scalar::Util::looks_like_number($_)} @_) {
278
279 # call list transform
280 &_trans0;
281
282 } else {
283
284 # error
285 croak('invalid transform input');
286
287 }
288  
289 }
290  
291 # inverse transform
292 # note: number of undefined output values must equal number of defined input values
293 # note: the input and output vectors contain the final solution on return
294 # hash key 'init' specifies initial value vector
295 # hash key 'ubox' enables unit box extrapolation
296 # parameters: (input_vector, output_vector, [hash])
297 # returns: (RMS_error_value)
298 sub inverse {
299  
300 # get parameters
301 my ($self, $in, $out, $hash) = @_;
302  
303 # local variables
304 my ($i, $j, @si, @so, $init);
305 my ($int, $jac, $mat, $delta);
306 my ($max, $elim, $dlim, $accum, $error);
307  
308 # initialize indices
309 $i = $j = -1;
310  
311 # build slice arrays while validating input and output arrays
312 ((grep {$i++; defined() && push(@si, $i)} @{$in}) == (grep {$j++; ! defined() && push(@so, $j)} @{$out})) || croak('wrong number of undefined values');
313  
314 # get init array
315 $init = $hash->{'init'};
316  
317 # for each undefined output value
318 for my $i (@so) {
319
320 # set to supplied initial value or 0.5
321 $out->[$i] = defined($init->[$i]) ? $init->[$i] : 0.5;
322
323 }
324  
325 # set maximum loop count
326 $max = $hash->{'inv_max'} || 10;
327  
328 # loop error limit
329 $elim = $hash->{'inv_elim'} || 1E-6;
330  
331 # set delta limit
332 $dlim = $hash->{'inv_dlim'} || 0.5;
333  
334 # create empty solution matrix
335 $mat = Math::Matrix->new([]);
336  
337 # compute initial transform values
338 ($jac, $int) = jacobian($self, $out, $hash);
339  
340 # solution loop
341 for (1 .. $max) {
342
343 # for each input
344 for my $i (0 .. $#si) {
345
346 # for each output
347 for my $j (0 .. $#so) {
348
349 # copy Jacobian value to solution matrix
350 $mat->[$i][$j] = $jac->[$si[$i]][$so[$j]];
351
352 }
353
354 # save residual value to solution matrix
355 $mat->[$i][$#si + 1] = $in->[$si[$i]] - $int->[$si[$i]];
356
357 }
358
359 # solve for delta values
360 $delta = $mat->solve;
361
362 # for each output value
363 for my $i (0 .. $#so) {
364
365 # add delta (limited using hyperbolic tangent)
366 $out->[$so[$i]] += POSIX::tanh($delta->[$i][0]/$dlim) * $dlim;
367
368 }
369
370 # compute updated transform values
371 ($jac, $int) = jacobian($self, $out, $hash);
372
373 # initialize error accumulator
374 $accum = 0;
375
376 # for each input
377 for my $i (0 .. $#si) {
378
379 # accumulate delta squared
380 $accum += ($in->[$si[$i]] - $int->[$si[$i]])**2;
381
382 }
383
384 # compute RMS error
385 $error = sqrt($accum/@si);
386
387 # if error less than limit
388 last if ($error < $elim);
389
390 }
391  
392 # update input vector with final values
393 @{$in} = @{$int};
394  
395 # return
396 return($error);
397  
398 }
399  
400 # compute Jacobian matrix
401 # nominal input range is (0 - 1)
402 # hash key 'ubox' enables unit box extrapolation
403 # parameters: (input_vector, [hash])
404 # returns: (Jacobian_matrix, [output_vector])
405 sub jacobian {
406  
407 # get parameters
408 my ($self, $in, $hash) = @_;
409  
410 # local variables
411 my ($xflag, $ext, $ubox, $jac, $delta, $out);
412  
413 # verify input vector
414 (ref($in) eq 'ARRAY' && @{$in} == @{$self->[1]} && @{$in} == grep {! ref()} @{$in}) || croak('invalid jacobian input');
415  
416 # if extrapolation required (any input outside the unit box)
417 if ($xflag = $hash->{'ubox'} && grep {$_ < 0 || $_ > 1} @{$in}) {
418
419 # get unit box intersection values
420 ($ext, $ubox) = _intersect($in);
421
422 # get Jacobian (at unit box surface)
423 $jac = ICC::Support::Lapack::nPINT_jacobian($self->[1], $ubox, $self->[3]);
424
425 } else {
426
427 # get Jacobian (at input values)
428 $jac = ICC::Support::Lapack::nPINT_jacobian($self->[1], $in, $self->[3]);
429 }
430  
431 # bless to Math::Matrix object
432 bless($jac, 'Math::Matrix');
433  
434 # if output values wanted
435 if (wantarray) {
436
437 # if extrapolation required
438 if ($xflag) {
439
440 # compute ouptut values (at unit box surface)
441 $out = ICC::Support::Lapack::nPINT_vec_trans($self->[1], $ubox, $self->[3]);
442
443 # for each output
444 for my $i (0 .. $#{$out}) {
445
446 # add delta value
447 $out->[$i] += ICC::Shared::dotProduct($jac->[$i], $ext);
448
449 }
450
451 } else {
452
453 # compute ouptut values (at input values)
454 $out = ICC::Support::Lapack::nPINT_vec_trans($self->[1], $in, $self->[3]);
455
456 }
457
458 # return Jacobian and output values
459 return($jac, $out);
460
461 } else {
462
463 # return Jacobian only
464 return($jac);
465
466 }
467
468 }
469  
470 # print object contents to string
471 # format is an array structure
472 # parameter: ([format])
473 # returns: (string)
474 sub sdump {
475  
476 # get parameters
477 my ($self, $p) = @_;
478  
479 # local variables
480 my ($s, $fmt);
481  
482 # resolve parameter to an array reference
483 $p = defined($p) ? ref($p) eq 'ARRAY' ? $p : [$p] : [];
484  
485 # get format string
486 $fmt = defined($p->[0]) && ! ref($p->[0]) ? $p->[0] : 'undef';
487  
488 # set string to object ID
489 $s = sprintf("'%s' object, (0x%x)\n", ref($self), $self);
490  
491 # return
492 return($s);
493  
494 }
495  
496 # transform list
497 # parameters: (object_reference, list, [hash])
498 # returns: (list)
499 sub _trans0 {
500  
501 # local variables
502 my ($self, $hash);
503  
504 # get object reference
505 $self = shift();
506  
507 # get optional hash
508 $hash = pop() if (ref($_[-1]) eq 'HASH');
509  
510 # call _trans1
511 return(@{_trans1($self, \@_, $hash)});
512  
513 }
514  
515 # transform vector
516 # parameters: (object_reference, vector, [hash])
517 # returns: (vector)
518 sub _trans1 {
519  
520 # get parameters
521 my ($self, $in, $hash) = @_;
522  
523 # local variables
524 my ($ext, $ubox, $out, $jac);
525  
526 # if unit box extrapolation
527 if ($hash->{'ubox'} && grep {$_ < 0.0 || $_ > 1.0} @{$in}) {
528
529 # get unit box intersection values
530 ($ext, $ubox) = _intersect($in);
531
532 # get transformed values (at unit box surface)
533 $out = ICC::Support::Lapack::nPINT_vec_trans($self->[1], $ubox, $self->[3]);
534
535 # get Jacobian (at unit box surface)
536 $jac = ICC::Support::Lapack::nPINT_jacobian($self->[1], $ubox, $self->[3]);
537
538 # for each output
539 for my $i (0 .. $#{$out}) {
540
541 # add delta value
542 $out->[$i] += ICC::Shared::dotProduct($jac->[$i], $ext);
543
544 }
545
546 # return extrapolated value
547 return($out);
548
549 } else {
550
551 # call BLAS-based vector transform function
552 return(ICC::Support::Lapack::nPINT_vec_trans($self->[1], $in, $self->[3]));
553
554 }
555  
556 }
557  
558 # transform matrix (2-D array -or- Math::Matrix object)
559 # parameters: (object_reference, matrix, [hash])
560 # returns: (matrix)
561 sub _trans2 {
562  
563 # get parameters
564 my ($self, $in, $hash) = @_;
565  
566 # local variable
567 my ($out);
568  
569 # if unit box extrapolation
570 if ($hash->{'ubox'}) {
571
572 # for each matrix row
573 for my $i (0 .. $#{$in}) {
574
575 # compute output vector
576 $out->[$i] = _trans1($self, $in->[$i], $hash);
577
578 }
579
580 } else {
581
582 # call BLAS-based vector transform function
583 $out = ICC::Support::Lapack::nPINT_mat_trans($self->[1], $in, $self->[3]);
584
585 }
586  
587 # return matrix, same form as input
588 return(UNIVERSAL::isa($in, 'Math::Matrix') ? bless($out, 'Math::Matrix') : $out);
589  
590 }
591  
592 # transform structure
593 # parameters: (object_reference, structure, [hash])
594 # returns: (structure)
595 sub _trans3 {
596  
597 # get parameters
598 my ($self, $in, $hash) = @_;
599  
600 # transform the array structure
601 _crawl($self, $in, my $out = []);
602  
603 # return output array reference
604 return($out);
605  
606 }
607  
608 # recursive transform
609 # array structure is traversed until scalar arrays are found and transformed
610 # parameters: (object_reference, input_array_reference, output_array_reference, hash)
611 sub _crawl {
612  
613 # get parameters
614 my ($self, $in, $out, $hash) = @_;
615  
616 # if input is a vector (reference to a scalar array)
617 if (@{$in} == grep {! ref()} @{$in}) {
618
619 # transform input vector and copy to output
620 @{$out} = @{_trans1($self, $in, $hash)};
621
622 } else {
623
624 # for each input element
625 for my $i (0 .. $#{$in}) {
626
627 # if an array reference
628 if (ref($in->[$i]) eq 'ARRAY') {
629
630 # transform next level
631 _crawl($self, $in->[$i], $out->[$i] = [], $hash);
632
633 } else {
634
635 # error
636 croak('invalid transform input');
637
638 }
639
640 }
641
642 }
643
644 }
645  
646 # find unit box intersection
647 # with line from input to box-center
648 # parameters: (input_vector)
649 # returns: (extrapolation_vector, unit_box_intersection)
650 sub _intersect {
651  
652 # get input vector
653 my $in = shift();
654  
655 # local variables
656 my (@cin, $dmax, $ubox);
657  
658 # compute input to center difference
659 @cin = map {$_ - 0.5} @{$in};
660  
661 # initialize
662 $dmax = 0;
663  
664 # for each difference
665 for (@cin) {
666
667 # if larger absolute value
668 if (abs($_) > $dmax) {
669
670 # new max difference
671 $dmax = abs($_);
672
673 }
674
675 }
676  
677 # multiply max difference by 2
678 $dmax *= 2;
679  
680 # compute output values (on surface of unit box)
681 $ubox = [map {$_/$dmax + 0.5} @cin];
682  
683 # return extrapolation vector ($in - $ubox) and unit-box intersection vector
684 return([map {$in->[$_] - $ubox->[$_]} (0 .. $#{$in})], $ubox);
685  
686 }
687  
688 # make nPINT object from parameter hash
689 # parameters: (object_reference, ref_to_parameter_hash)
690 sub _new_from_hash {
691  
692 # get parameters
693 my ($self, $hash) = @_;
694  
695 # local variables
696 my ($pda, $coef, $size);
697  
698 # get input polynomial degree array (pda) reference
699 $pda = $hash->{'pda'} || croak('missing polynomial degree array');
700  
701 # get output coefficient array reference
702 $coef = $hash->{'coef'} || croak('missing coefficient array');
703  
704 # verify pda structure
705 (ref($pda) eq 'ARRAY' && ! ref($pda->[0])) || croak('improper polynomial degree array');
706  
707 # copy pda to object
708 $self->[1] = [@{$pda}];
709  
710 # initialize coefficient array size
711 $size = 1;
712  
713 # for each pda element
714 for my $d (@{$pda}) {
715
716 # multiply by (degree + 1)
717 $size *= ($d + 1);
718
719 }
720  
721 # verify coef is array or Math::Matrix object
722 (ref($coef) eq 'ARRAY' || UNIVERSAL::isa($coef, 'Math::Matrix')) || croak('improper coefficient array type');
723  
724 # verify coef structure
725 (ref($coef->[0]) eq 'ARRAY' && ! ref($coef->[0][0]) && @{$coef} == $size) || croak('improper coefficient array structure');
726  
727 # copy coefficient array to object
728 $self->[2] = bless(Storable::dclone($coef), 'Math::Matrix');
729  
730 # update cache
731 $self->[3] = ICC::Support::Lapack::cache_2D($self->[2]);
732  
733 }
734  
735 # make nPINT object from Storable file
736 # parameters: (object_reference, path_to_storable_file)
737 sub _new_from_storable {
738  
739 # get parameters
740 my ($self, $path) = @_;
741  
742 # local variables
743 my ($hash, @files);
744  
745 # resolve file list from path
746 (@files = File::Glob::bsd_glob($path)) || croak('invalid file path');
747  
748 # verify file path is unique
749 (@files == 1) || carp('file path not unique');
750  
751 # retrieve hash reference
752 $hash = Storable::retrieve($files[0]);
753  
754 # if successful
755 if (defined($hash)) {
756
757 # create nPINT object from hash reference
758 _new_from_hash($self, $hash);
759
760 # return success flag
761 return(1);
762
763 } else {
764
765 # return failure flag
766 return(0);
767
768 }
769
770 }
771  
772 1;